Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(memory-plugin): add ov-memory-doctor skill and diagnostics script for Claude Code and Codex (#4389)
t0saki206054cf150a
diff --git a/.github/scripts/stage-memory-plugin-marketplace.sh b/.github/scripts/stage-memory-plugin-marketplace.shindex 399a97ad2..96b9f151e 100644--- a/.github/scripts/stage-memory-plugin-marketplace.sh+++ b/.github/scripts/stage-memory-plugin-marketplace.sh@@ -40,7 +40,11 @@ for required in \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 \diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.ymlindex f9794f603..4dffb1eee 100644--- a/.github/workflows/pr.yml+++ b/.github/workflows/pr.yml@@ -55,6 +55,7 @@ jobs: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-opencode-jsonc.test.mjs \examples/memory-plugin-shared/install-tui.test.mjs \diff --git a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json b/examples/claude-code-memory-plugin/.claude-plugin/plugin.jsonindex ae86dcc50..5ad01512f 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.4",+ "version": "0.4.5","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.mdindex af7d82e09..441b8b7aa 100644--- a/examples/claude-code-memory-plugin/README.md+++ b/examples/claude-code-memory-plugin/README.md@@ -309,6 +309,14 @@ Set `claude_code.debug: true` in `ov.conf` or `OPENVIKING_DEBUG=1` to write hook## Troubleshooting+Start with the bundled doctor — it checks the install (marketplace, enablement, hooks, MCP wiring), the resolved config (which file won, API key shown masked), the connection (reachability, auth, `/mcp`) and recent hook activity, and prints a fix for every finding:++```bash+node "$(jq -r '.plugins["openviking-memory@openviking"][0].installPath' ~/.claude/plugins/installed_plugins.json)/scripts/ov-memory-doctor.mjs"+```++Or just ask Claude to check the plugin: the `ov-memory-doctor` skill 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`.+| Symptom | Cause | Fix ||--------------------------------------------|--------------------------------------------------------------|----------------------------------------------------------------------------------------------------|| Plugin not activating | No `ov.conf` / `ovcli.conf` found | Create one, or set `OPENVIKING_MEMORY_ENABLED=1` plus the URL/API_KEY env vars |@@ -401,6 +409,12 @@ claude-code-memory-plugin/│ └── plugin.json # plugin manifest├── hooks/│ └── hooks.json # 9 hook registrations+├── commands/+│ └── ov.md # /ov status command+├── skills/+│ ├── openviking-memory/ # how to use the memory tools+│ ├── ov-experience-memory/+│ └── ov-memory-doctor/ # install / config / connection / local-server troubleshooting├── servers/│ └── mcp-proxy.mjs # stdio -> OpenViking /mcp bridge├── scripts/@@ -415,6 +429,8 @@ claude-code-memory-plugin/│ ├── 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/│ ├── ov-session.mjs # OV HTTP client + session helpers + bypass check│ └── async-writer.mjs # detached-worker helper for write-path hooksdiff --git a/examples/claude-code-memory-plugin/README_CN.md b/examples/claude-code-memory-plugin/README_CN.mdindex 0dc48db04..eb5d87959 100644--- a/examples/claude-code-memory-plugin/README_CN.md+++ b/examples/claude-code-memory-plugin/README_CN.md@@ -299,6 +299,14 @@ OV ✓ │ 🔗 resumed │ +3 today session 已恢复上下文;## 故障排除+先跑内置的体检脚本——它会检查安装(marketplace、启用状态、hooks、MCP 接线)、解析后的配置(哪个文件生效、API key 脱敏展示)、连接(可达性、鉴权、`/mcp`)和最近的 hook 活动,并给每个问题附上修复建议:++```bash+node "$(jq -r '.plugins["openviking-memory@openviking"][0].installPath' ~/.claude/plugins/installed_plugins.json)/scripts/ov-memory-doctor.mjs"+```++也可以直接让 Claude 检查插件:`ov-memory-doctor` skill 会运行同一个脚本并解读报告。当 server 与插件在同一台机器上(loopback url)时,报告还会多一节 Server health:端口上是否有 server 在监听、ov.conf 里只有插件会读而 server 会拒绝启动的键、以及 `GET /ready`;其余 server 端检查(配置校验、实际 embedding 探测、native engine、磁盘)仍由 `openviking-server doctor` 负责。+| 症状 | 原因 | 解决方案 ||----------------------------------------------|------------------------------------------------------|-----------------------------------------------------------------------------------------------|| 插件没激活 | 找不到 `ov.conf` / `ovcli.conf` | 创建一个;或设 `OPENVIKING_MEMORY_ENABLED=1` 加上 URL/API_KEY 等环境变量 |@@ -391,6 +399,12 @@ claude-code-memory-plugin/│ └── plugin.json # plugin manifest├── hooks/│ └── hooks.json # 9 个 hook 注册+├── commands/+│ └── ov.md # /ov 状态命令+├── skills/+│ ├── openviking-memory/ # 记忆工具使用指南+│ ├── ov-experience-memory/+│ └── ov-memory-doctor/ # 安装 / 配置 / 连接 / 本机 server 排障├── servers/│ └── mcp-proxy.mjs # stdio -> OpenViking /mcp 桥接├── scripts/@@ -405,6 +419,8 @@ claude-code-memory-plugin/│ ├── subagent-stop.mjs # SubagentStop│ ├── debug-recall.mjs # 召回独立诊断│ ├── debug-capture.mjs # 捕获独立诊断+│ ├── ov-status.mjs # /ov 状态报告+│ ├── ov-memory-doctor.mjs # 体检脚本(ov-memory-doctor skill)│ └── lib/│ ├── ov-session.mjs # OV HTTP 客户端 + session 帮助 + bypass 检查│ └── async-writer.mjs # 写路径 detach-worker 帮助diff --git a/examples/claude-code-memory-plugin/package.json b/examples/claude-code-memory-plugin/package.jsonindex fb5df652c..e9750dbc8 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.4",+ "version": "0.4.5","description": "OpenViking memory plugin for Claude Code — semantic long-term memory","type": "module","scripts": {diff --git a/examples/claude-code-memory-plugin/scripts/marketplace.test.mjs b/examples/claude-code-memory-plugin/scripts/marketplace.test.mjsindex 840431e68..a430ffd81 100644--- a/examples/claude-code-memory-plugin/scripts/marketplace.test.mjs+++ b/examples/claude-code-memory-plugin/scripts/marketplace.test.mjs@@ -91,3 +91,12 @@ test("Claude hooks include PreToolUse URI guard for filesystem tools", () => {);execFileSync("node", ["--check", join(pluginDir, "scripts", "uri-guard.mjs")], { stdio: "pipe" });});++test("Claude plugin ships the memory doctor skill and script", () => {+ const skill = join(pluginDir, "skills", "ov-memory-doctor", "SKILL.md");+ assert.ok(existsSync(skill), "missing skills/ov-memory-doctor/SKILL.md");+ assert.match(readFileSync(skill, "utf-8"), /node \$\{CLAUDE_PLUGIN_ROOT\}\/scripts\/ov-memory-doctor\.mjs/);+ assert.ok(existsSync(join(pluginDir, "skills", "ov-memory-doctor", "reference.md")));+ execFileSync("node", ["--check", join(pluginDir, "scripts", "ov-memory-doctor.mjs")], { stdio: "pipe" });+ execFileSync("node", ["--check", join(pluginDir, "scripts", "shared", "doctor-core.mjs")], { stdio: "pipe" });+});diff --git a/examples/claude-code-memory-plugin/scripts/ov-memory-doctor.mjs b/examples/claude-code-memory-plugin/scripts/ov-memory-doctor.mjsnew file mode 100644index 000000000..f8f8e4e19--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/ov-memory-doctor.mjs@@ -0,0 +1,514 @@+#!/usr/bin/env node++/**+ * Client-side diagnostics for the OpenViking Claude Code memory plugin.+ *+ * Covers the three things that go wrong on a user's machine — the plugin+ * install (marketplace / enablement / hooks / MCP wiring), the client config+ * (which file won, is the JSON valid, what the key claims) and the connection+ * to the server (reachability, auth, tenant-data access, /mcp) — plus the+ * runtime evidence the hooks leave behind. When the server runs on this+ * machine (loopback url) it also checks+ * the port, plugin-only keys in ov.conf and `GET /ready`. Provider-level validation stays with `openviking-server doctor`.+ *+ * Usage:+ * node ov-memory-doctor.mjs [--json] [--offline] [--timeout <ms>] [--no-color]+ *+ * Exit code 1 when any check fails, 0 otherwise. Never prints a full api key.+ */++import { readFileSync } from "node:fs";+import { homedir } from "node:os";+import { dirname, join, resolve as resolvePath } from "node:path";+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,+ fileInfo,+ fmtAge,+ fmtBytes,+ homeShort,+ inspectJsonFile,+ isLoopbackUrl,+ lintBaseUrl,+ parseNodeMajor,+ probeOpenViking,+ readStateFiles,+ runCommand,+ scanDebugLog,+ scanRcFiles,+ unknownOvcliKeys,+ whichCommand,+} from "./shared/doctor-core.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";+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;+ const lower = v.trim().toLowerCase();+ if (["0", "false", "no"].includes(lower)) return false;+ if (["1", "true", "yes"].includes(lower)) return true;+ return undefined;+}++// ---------------------------------------------------------------------------+// 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 }) {+ report.section("Plugin install");+ const manifest = tryJson(join(PLUGIN_ROOT, ".claude-plugin", "plugin.json"));+ const version = manifest?.version || "?";+ const inCache = PLUGIN_ROOT.includes(`${join(".claude", "plugins", "cache")}`);+ report.info(`running from ${homeShort(PLUGIN_ROOT)} (version ${version}, ${inCache ? "marketplace cache" : "directory install / dev checkout"})`);++ const missing = REQUIRED_PLUGIN_FILES.filter((rel) => !existsPath(join(PLUGIN_ROOT, rel)));+ if (missing.length) report.fail("plugin files missing", missing.join(", "), "reinstall: claude plugin uninstall openviking-memory@openviking && claude plugin install openviking-memory@openviking");+ else report.ok("plugin files present (hooks, MCP proxy, scripts)");+ if (!existsPath(join(PLUGIN_ROOT, "skills"))) {+ report.warn("no skills/ directory in this plugin copy", "the installed copy predates the bundled skills; Claude Code caches by version, so `claude plugin update` is a no-op until the version changes",+ "claude plugin marketplace update openviking && claude plugin uninstall openviking-memory@openviking && claude plugin install openviking-memory@openviking");+ }++ // Registry: installed_plugins.json+ const installed = inspectJsonFile(join(CLAUDE_DIR, "plugins", "installed_plugins.json"));+ let installPath = "";+ if (!installed.exists) {+ report.warn("~/.claude/plugins/installed_plugins.json not found", "no plugin has ever been installed through the marketplace on this machine");+ } else if (!installed.ok) {+ report.fail("~/.claude/plugins/installed_plugins.json is unreadable", installed.error);+ } else {+ const plugins = installed.data.plugins || {};+ const ids = Object.keys(plugins).filter((id) => id.startsWith(`${PLUGIN_NAME}@`) || id.startsWith("claude-code-memory-plugin@"));+ const entries = Array.isArray(plugins[PLUGIN_ID]) ? plugins[PLUGIN_ID] : (plugins[PLUGIN_ID] ? [plugins[PLUGIN_ID]] : []);+ if (!entries.length) {+ report.fail(`${PLUGIN_ID} is not registered in installed_plugins.json`, ids.length ? `found instead: ${ids.join(", ")}` : "",+ "bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) --harness claude");+ } else {+ const entry = entries[0];+ installPath = entry.installPath || "";+ report.ok(`registered ${PLUGIN_ID} ${entry.version || "?"} (scope ${entry.scope || "?"}, updated ${entry.lastUpdated || "?"})`);+ if (installPath && resolvePath(installPath) !== PLUGIN_ROOT) {+ const registeredDoctor = join(installPath, "scripts", "ov-memory-doctor.mjs");+ report.warn("this script is not running from the registered install", `registered: ${homeShort(installPath)}\nrunning: ${homeShort(PLUGIN_ROOT)}`,+ existsPath(registeredDoctor)+ ? `Claude Code executes hooks from the registered copy; check that one with: node ${homeShort(registeredDoctor)}`+ : `Claude Code executes hooks from the registered copy (${entry.version || "?"}), which predates this script — update the plugin, then rerun from there`);+ }+ if (installPath && !existsPath(join(installPath, ".claude-plugin", "plugin.json"))) {+ report.fail("registered installPath no longer exists", homeShort(installPath), "reinstall the plugin");+ }+ if (entries.length > 1) report.warn(`${PLUGIN_ID} has ${entries.length} install records`, entries.map((e) => `${e.scope}: ${homeShort(e.installPath || "")}`).join("\n"));+ }+ const extra = ids.filter((id) => id !== PLUGIN_ID);+ if (extra.length) {+ report.warn("additional openviking plugin ids are installed", extra.join(", "), `claude plugin uninstall <id> for each stale copy (legacy marketplace ${LEGACY_MARKETPLACE})`);+ }+ }++ // Marketplace+ const known = inspectJsonFile(join(CLAUDE_DIR, "plugins", "known_marketplaces.json"));+ if (known.ok) {+ const entry = known.data[MARKETPLACE];+ if (!entry) {+ report.fail(`marketplace '${MARKETPLACE}' is not registered`, `known: ${Object.keys(known.data).join(", ") || "(none)"}`,+ "re-run the installer, or: claude plugin marketplace add ~/.openviking/marketplaces/openviking-claude");+ } else {+ const source = entry.source || {};+ const location = entry.installLocation || source.path || "";+ const desc = source.source === "directory" ? `directory ${homeShort(source.path || "")}` : source.source === "github" ? `github ${source.repo || ""}` : JSON.stringify(source);+ if (/\.json$/i.test(String(source.path || ""))) {+ report.warn(`marketplace '${MARKETPLACE}' is registered as a file (${homeShort(source.path)})`, "file-type marketplaces mis-derive installLocation and `claude plugin marketplace update` fails with EISDIR",+ "claude plugin marketplace remove openviking && re-run the installer (it registers a directory)");+ } else if (location && !existsPath(join(location, ".claude-plugin", "marketplace.json"))) {+ report.fail(`marketplace '${MARKETPLACE}' points at a missing directory`, `${desc}\nexpected ${homeShort(join(location, ".claude-plugin", "marketplace.json"))}`,+ "the checkout/archive was moved or deleted; re-run the installer");+ } else {+ report.ok(`marketplace '${MARKETPLACE}' → ${desc}`);+ if (source.source === "directory" && location) {+ const manifest = tryJson(join(location, ".claude-plugin", "marketplace.json"));+ const pluginSrc = manifest?.plugins?.find?.((p) => p?.name === PLUGIN_NAME)?.source;+ if (pluginSrc && typeof pluginSrc === "object" && pluginSrc.source === "git-subdir") {+ report.info(`marketplace fetches ${pluginSrc.url || "?"}@${pluginSrc.ref || "?"} ${pluginSrc.path || ""} (update: claude plugin marketplace update openviking && claude plugin update ${PLUGIN_ID})`);+ } else if (pluginSrc) {+ report.info("directory marketplace: updates need the installer to be re-run (claude plugin update cannot fetch)");+ }+ }+ }+ }+ if (known.data[LEGACY_MARKETPLACE]) {+ report.warn(`legacy marketplace '${LEGACY_MARKETPLACE}' is still registered`, "", `claude plugin marketplace remove ${LEGACY_MARKETPLACE}`);+ }+ } else if (known.exists) {+ report.fail("~/.claude/plugins/known_marketplaces.json is unreadable", known.error);+ }++ // settings.json+ const settings = inspectJsonFile(join(CLAUDE_DIR, "settings.json"));+ if (settings.exists && !settings.ok) {+ report.fail("~/.claude/settings.json is not valid JSON", settings.error, "fix the JSON — Claude Code ignores the whole file otherwise");+ } else if (settings.ok) {+ const enabled = settings.data.enabledPlugins?.[PLUGIN_ID];+ if (enabled === true) report.ok(`enabledPlugins["${PLUGIN_ID}"] = true`);+ else if (enabled === false) report.fail(`plugin is disabled in ~/.claude/settings.json`, "", `claude plugin enable ${PLUGIN_ID}`);+ else report.warn(`enabledPlugins has no entry for ${PLUGIN_ID}`, "installed but never enabled (or enabled at another scope)", `claude plugin enable ${PLUGIN_ID}`);+ const otherEnabled = Object.entries(settings.data.enabledPlugins || {}).filter(([id, on]) => on && id !== PLUGIN_ID && /openviking|claude-code-memory-plugin/.test(id));+ if (otherEnabled.length) report.warn("more than one openviking plugin is enabled", otherEnabled.map(([id]) => id).join(", "), "disable/uninstall the stale one or hooks fire twice");++ const hooksText = JSON.stringify(settings.data.hooks || {});+ if (/openviking|auto-recall\.mjs|auto-capture\.mjs/.test(hooksText)) {+ report.warn("legacy openviking hooks are still merged into ~/.claude/settings.json", "pre-2.0 installs wrote hooks there; together with the plugin every hook now fires twice (double recall/capture)",+ "remove the openviking entries from .hooks in ~/.claude/settings.json (back it up first)");+ }+ const statusCmd = String(settings.data.statusLine?.command || "");+ if (statusCmd.includes("statusline.mjs")) {+ const m = /node\s+"?([^"]+statusline\.mjs)"?/.exec(statusCmd);+ const path = m ? expandHome(m[1]) : "";+ if (path && !existsPath(path)) report.warn("statusLine points at a missing statusline.mjs", homeShort(path), "re-run the installer or fix .statusLine.command in ~/.claude/settings.json");+ else if (path && !path.startsWith(PLUGIN_ROOT) && !(installPath && path.startsWith(resolvePath(installPath)))) {+ report.warn("statusline runs from a different plugin copy than the hooks", homeShort(path), "point .statusLine.command at the registered install, or accept that the two may differ in version");+ } else report.ok(`statusline registered (${homeShort(path)})`);+ } else {+ report.info("statusline not registered (optional; OPENVIKING_STATUSLINE=off also silences it)");+ }+ const envBlock = settings.data.env || {};+ const envKeys = Object.keys(envBlock).filter((k) => k.startsWith("OPENVIKING_"));+ if (envKeys.length) report.info(`~/.claude/settings.json env block sets ${envKeys.join(", ")}`);+ } else {+ report.warn("~/.claude/settings.json not found", "no enabledPlugins entry can exist without it");+ }++ // Legacy MCP registration + rc blocks+ const claudeJson = tryJson(join(homedir(), ".claude.json"));+ const userMcp = claudeJson?.mcpServers?.openviking;+ if (userMcp) {+ 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 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));+ if (conn.length) report.warn(`${h.file} exports ${conn.join(", ")}`, "shell exports override ovcli.conf in every session started from that shell", "remove the export or keep ovcli.conf in sync with it");+ else report.info(`${h.file} exports ${h.detail}`);+ }++ if (claudeOnPath) {+ const list = runCommand("claude", ["plugin", "list", "--json"], { timeoutMs: 30000 });+ if (list.ok) {+ let rows = [];+ try { rows = JSON.parse(list.stdout); } catch { rows = []; }+ const mine = rows.filter((r) => r?.id === PLUGIN_ID);+ const others = rows.filter((r) => r?.id !== PLUGIN_ID && /openviking|claude-code-memory-plugin/.test(String(r?.id)));+ if (!mine.length) report.fail(`claude plugin list does not show ${PLUGIN_ID}`, others.length ? `shows: ${others.map((r) => r.id).join(", ")}` : "", `claude plugin install ${PLUGIN_ID}`);+ else {+ const row = mine[0];+ if (row.enabled === false) report.fail(`claude plugin list: ${PLUGIN_ID} is disabled`, "", `claude plugin enable ${PLUGIN_ID}`);+ else report.ok(`claude plugin list: ${PLUGIN_ID} ${row.version || ""} enabled`);+ }+ if (others.length) report.warn("claude plugin list shows extra openviking plugins", others.map((r) => `${r.id} (${r.enabled ? "enabled" : "disabled"})`).join(", "));+ } else {+ report.info(`claude plugin list --json failed (${list.error || list.stderr.split("\n")[0]})`);+ }+ }+ 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) {+ 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");+ 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)");+ }+ }++ // Enable verdict+ const enabled = isPluginEnabled();+ const envEnabled = envBoolValue("OPENVIKING_MEMORY_ENABLED");+ let reason;+ if (envEnabled === false) reason = "OPENVIKING_MEMORY_ENABLED is set to off";+ else if (envEnabled === true) reason = "OPENVIKING_MEMORY_ENABLED=1";+ else if (ovConf.ok && ovConf.data.claude_code?.enabled === false) reason = "ov.conf claude_code.enabled = false";+ else if (ovConf.ok || cliConf.ok) reason = `${ovConf.ok ? "ov.conf" : "ovcli.conf"} exists and parses`;+ else reason = "neither ovcli.conf nor ov.conf parses";+ if (enabled) report.ok(`plugin enabled (${reason})`);+ 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.source === "workspace" ? " (derived from cwd; changes when the directory moves)" : ""}`);+ report.info(`timeouts ${cfg.timeoutMs}ms request, ${cfg.captureTimeoutMs}ms capture; recall limit ${cfg.recallLimit}, threshold ${cfg.scoreThreshold}`);++ 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");+ 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() });+ report[hit ? "warn" : "info"](`bypass patterns: ${cfg.bypassSessionPatterns.join(", ")}${hit ? " — MATCH the current cwd" : ""}`, hit ? "recall/capture are skipped in this directory" : "", hit ? "narrow OPENVIKING_BYPASS_SESSION_PATTERNS" : "");+ }+ 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");+ 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");+ }+ } 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"));+ if (inject.exists) report.info(`last session-start injection ${fmtAge(inject.mtimeMs)}, ${fmtBytes(inject.size)} (~/.openviking/last_inject.md)`);+ else report.info("no session-start injection recorded yet");++ const state = readStateFiles(STATE_DIR, STATE_FILES);+ const recall = state["last-recall.json"];+ if (recall.exists && recall.data) {+ const d = recall.data;+ const line = `last auto-recall ${fmtAge(d.ts)} — ${d.count ?? 0} items, ${d.latency_ms ?? "?"}ms, reason=${d.reason || "?"} (server ${d.server_url || "?"})`;+ if (d.reason === "offline") report.warn(line, "the hook could not reach the server at that time");+ else if (d.reason === "bypass" || d.reason === "disabled") report.warn(line, "recall was switched off for that session");+ else report.info(line);+ if (d.server_url && d.server_url !== cfg.baseUrl) report.warn("last recall talked to a different server than the current config", `${d.server_url} vs ${cfg.baseUrl}`, "config changed since; restart Claude Code so the MCP proxy follows");+ if (typeof d.latency_ms === "number" && d.latency_ms > 45000) report.warn(`recall latency ${d.latency_ms}ms is close to the 60s hook budget`, "", "set OPENVIKING_RECALL_QUERY_EXPANSION=off and OPENVIKING_RECALL_COMPRESS=off, or raise the timeout");+ } else {+ report.info("no auto-recall recorded yet (UserPromptSubmit hook has not run, or state dir differs)");+ }+ const capture = state["last-capture.json"];+ if (capture.exists && capture.data) {+ const d = capture.data;+ const line = `last auto-capture ${fmtAge(d.ts)} — captured ${d.turns_captured ?? 0}, queued ${d.turns_queued ?? 0}, failed ${d.turns_failed ?? 0}, pending ${d.pending_tokens ?? 0}/${d.commit_threshold ?? "?"} tokens, ${d.commit_count ?? 0} commits (session ${d.ov_session_id || "?"})`;+ if ((d.turns_failed ?? 0) > 0) report.warn(line, "turns_failed > 0 means the server rejected writes with a non-retryable status (401/403/404) and those turns were dropped", "fix credentials, then set OPENVIKING_WRITE_PATH_ASYNC=0 temporarily to see the error on stderr");+ else if ((d.turns_queued ?? 0) > 0) report.warn(line, "turns are waiting in the offline queue; they replay at the next session start once /health passes");+ else report.info(line);+ } else {+ report.info("no auto-capture recorded yet (Stop hook has not run)");+ }+ const probe = state["server-probe.json"];+ if (probe.exists && probe.data && probe.data.healthy === false) report.info(`statusline probe last saw the server unhealthy ${fmtAge(probe.data.ts)} (${probe.data.error || "?"})`);+ const face = state["context-face.json"];+ if (face.exists && face.data?.legacyUntil > Date.now()) report.warn("recall is pinned to the legacy /search/recall endpoint", `context-face.json legacyUntil ${new Date(face.data.legacyUntil).toISOString()} — set after one 4xx that mentioned 'mode'`, `rm ${homeShort(face.path)} to re-probe the context endpoint`);+ const hostCli = state["host-cli-probe.json"];+ if (hostCli.exists && hostCli.data && hostCli.data.available === false && cfg.recallRewrite !== "off" && cfg.recallRewrite !== "server") report.info(`local compressor probe says '${hostCli.data.command}' is unavailable (cached 7 days) — rm ${homeShort(hostCli.path)} to re-check`);++ const pendingDir = process.env.OPENVIKING_PENDING_DIR || join(homedir(), ".openviking", "pending");+ const pending = countDirEntries(pendingDir, (n) => n.endsWith(".json") || n.endsWith(".processing"));+ if (pending) report.warn(`${pending} capture payload(s) waiting in ${homeShort(pendingDir)}`, "retryable failures are replayed at the next session start after /health passes", connection?.summary?.reachable ? "start a new Claude Code session to drain the queue" : "bring the server back first");+ else if (pending === 0) report.ok("offline queue empty");++ 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 session ran, hooks are not being spawned (node/PATH/plugin registration)" : ""}`);+ } else {+ report.info(`hook log ${homeShort(log.path)} — ${fmtBytes(log.size)}, last write ${fmtAge(log.mtimeMs)}, hooks seen: ${log.hooks.join(", ") || "(none)"}`);+ if (log.proxyStart?.data?.mcpUrl) {+ const want = `${cfg.baseUrl.replace(/\/+$/, "")}/mcp`;+ if (log.proxyStart.data.mcpUrl !== want) report.warn(`MCP proxy last started against ${log.proxyStart.data.mcpUrl} (${log.proxyStart.ts})`, `current config resolves to ${want}; a running proxy only re-reads credentials after a 401/403, never a new url`, "if that proxy is still running, restart Claude Code (or /mcp → reconnect); if the line is old, ignore it");+ else report.info(`MCP proxy last started against ${log.proxyStart.data.mcpUrl} (${log.proxyStart.ts})`);+ }+ const notable = log.recentErrors.filter((e) => !(e.hook === "subagent-stop" && e.stage === "transcript_read"));+ if (notable.length) report.warn(`hook errors in the last day of logging (${notable.length} shown)`, notable.map((e) => `${e.ts} ${e.hook}/${e.stage}: ${e.message}`).join("\n"));+ else if (log.recentErrors.length) report.info("only subagent-stop transcript_read ENOENT errors in the log (harmless: that subagent's transcript was already gone)");+ }+}++// ---------------------------------------------------------------------------++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 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,+ },+ server: connection?.summary || null,+ serverHealth,+ ...report.toJSON(),+ };+ console.log(JSON.stringify(out, null, 2));+ } else {+ console.log(report.render());+ }+ process.exitCode = report.exitCode();+}++main().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/shared/doctor-core.mjs b/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjsnew file mode 100644index 000000000..035e96b05--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs@@ -0,0 +1,901 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Harness-agnostic building blocks for the memory plugin doctor scripts.+ *+ * Each harness ships a thin `ov-memory-doctor.mjs` entrypoint that knows its+ * own install layout (where the plugin is registered, which hooks file, which+ * 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.+ *+ * Nothing here reads harness config; callers pass a resolved connection+ * `{ baseUrl, apiKey, account, user, peerId, userAgent }`.+ */++import { execFileSync } from "node:child_process";+import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";++// ---------------------------------------------------------------------------+// Formatting helpers+// ---------------------------------------------------------------------------++export function homeShort(path) {+ const home = homedir();+ if (!path) return path;+ return path.startsWith(home) ? `~${path.slice(home.length)}` : path;+}++export function fmtAge(ts) {+ if (!ts) return "never";+ const sec = Math.floor((Date.now() - ts) / 1000);+ if (sec < 0) return "just now";+ if (sec < 60) return `${sec}s ago`;+ if (sec < 3600) return `${Math.floor(sec / 60)}m ago`;+ if (sec < 86400) return `${Math.floor(sec / 3600)}h ago`;+ return `${Math.floor(sec / 86400)}d ago`;+}++export function fmtBytes(n) {+ if (n == null) return "?";+ if (n < 1024) return `${n} B`;+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;+ return `${(n / 1024 / 1024).toFixed(1)} MB`;+}++function str(value, fallback = "") {+ return typeof value === "string" && value.trim() ? value.trim() : fallback;+}++// ---------------------------------------------------------------------------+// Report+// ---------------------------------------------------------------------------++const LEVEL_ORDER = { fail: 0, warn: 1, info: 2, ok: 3 };+const LEVEL_MARK = { ok: "✓", info: "·", warn: "⚠", fail: "✗" };+const LEVEL_COLOR = { ok: "32", info: "2", warn: "33", fail: "31" };++export function createReport({ color = false } = {}) {+ const sections = [];+ let current = null;++ function paint(code, text) {+ return color ? `\x1b[${code}m${text}\x1b[0m` : text;+ }++ function section(title) {+ current = { title, findings: [] };+ sections.push(current);+ return current;+ }++ function add(level, title, detail, fix) {+ if (!current) section("General");+ const finding = { level, title };+ if (detail) finding.detail = String(detail);+ if (fix) finding.fix = String(fix);+ current.findings.push(finding);+ return finding;+ }++ const report = {+ sections,+ section,+ add,+ ok: (title, detail) => add("ok", title, detail),+ info: (title, detail) => add("info", title, detail),+ warn: (title, detail, fix) => add("warn", title, detail, fix),+ fail: (title, detail, fix) => add("fail", title, detail, fix),+ problems() {+ return sections.flatMap((s) => s.findings.filter((f) => f.level === "fail" || f.level === "warn"));+ },+ exitCode() {+ return sections.some((s) => s.findings.some((f) => f.level === "fail")) ? 1 : 0;+ },+ render() {+ const lines = [];+ for (const s of sections) {+ lines.push(paint("1", `== ${s.title} ==`));+ for (const f of s.findings) {+ lines.push(` ${paint(LEVEL_COLOR[f.level], LEVEL_MARK[f.level])} ${f.title}`);+ if (f.detail) for (const l of String(f.detail).split("\n")) lines.push(` ${l}`);+ if (f.fix && (f.level === "warn" || f.level === "fail")) lines.push(` ${paint("36", "fix:")} ${f.fix}`);+ }+ lines.push("");+ }+ const problems = report.problems().sort((a, b) => LEVEL_ORDER[a.level] - LEVEL_ORDER[b.level]);+ lines.push(paint("1", "== Summary =="));+ if (!problems.length) {+ lines.push(` ${paint("32", "✓")} no problems found`);+ } else {+ const fails = problems.filter((p) => p.level === "fail").length;+ lines.push(` ${fails} failure(s), ${problems.length - fails} warning(s)`);+ for (const p of problems) {+ lines.push(` ${paint(LEVEL_COLOR[p.level], LEVEL_MARK[p.level])} ${p.title}${p.fix ? ` → ${p.fix}` : ""}`);+ }+ }+ return lines.join("\n");+ },+ toJSON() {+ return { sections };+ },+ };+ return report;+}++// ---------------------------------------------------------------------------+// API key display+// ---------------------------------------------------------------------------++export function decodeBase64Url(segment) {+ if (typeof segment !== "string" || !segment || /[^A-Za-z0-9_-]/.test(segment)) return null;+ try {+ const padded = segment + "=".repeat((4 - (segment.length % 4)) % 4);+ const text = Buffer.from(padded, "base64url").toString("utf-8");+ // Reject decoded text that is not printable — a random string that happens+ // to be valid base64 decodes to binary garbage.+ if (!text || /[^\x20-\x7e]/.test(text)) return null;+ return text;+ } catch {+ return null;+ }+}++function headTail(value, keep = 4) {+ if (!value) return "";+ if (value.length <= keep * 2 + 2) return "*".repeat(Math.max(4, value.length));+ return `${value.slice(0, keep)}…${value.slice(-keep)}`;+}++/**+ * Describe an API key for display without revealing it.+ *+ * three-segment key → account=<decoded> user=<decoded> secret=abcd…wxyz+ * single-segment key → abcd…wxyz (64 chars, legacy format)+ *+ * The three-segment format is base64url(account).base64url(user).base64url(secret);+ * the first two segments carry no secret and are decoded so the operator can see+ * which identity the key claims. Also reports shape problems that commonly come+ * from copy/paste mistakes.+ */+export function describeApiKey(rawKey) {+ const info = { present: false, format: "none", display: "(none)", account: "", user: "", length: 0, problems: [] };+ if (typeof rawKey !== "string" || !rawKey) return info;++ info.present = true;+ info.length = rawKey.length;+ if (rawKey !== rawKey.trim()) info.problems.push("has leading/trailing whitespace");+ if (/[\r\n]/.test(rawKey)) info.problems.push("contains a line break");+ if (/^["']|["']$/.test(rawKey.trim())) info.problems.push("wrapped in quotes");+ if (/^bearer\s+/i.test(rawKey.trim())) info.problems.push("starts with 'Bearer ' — store only the key itself");++ const key = rawKey.trim().replace(/^bearer\s+/i, "").replace(/^["']|["']$/g, "");+ const parts = key.split(".");+ if (parts.length === 3) {+ info.format = "v2";+ const account = decodeBase64Url(parts[0]);+ const user = decodeBase64Url(parts[1]);+ info.account = account || "";+ info.user = user || "";+ const accountText = account ?? `${headTail(parts[0])} (not base64url)`;+ const userText = user ?? `${headTail(parts[1])} (not base64url)`;+ if (account === null || user === null) info.problems.push("account/user segment is not decodable base64url — key may be truncated or mangled");+ if (!parts[2]) info.problems.push("secret segment is empty");+ info.display = `account=${accountText} user=${userText} secret=${headTail(parts[2])}`;+ } else {+ info.format = "legacy";+ if (parts.length !== 1) info.problems.push(`unexpected shape: ${parts.length} dot-separated segments (expected 1 or 3)`);+ info.display = `${headTail(key)} (${key.length} chars, ${parts.length === 1 ? "legacy single-segment" : "unrecognised"} format)`;+ }+ return info;+}++/** Mask any secret-looking env value for display. */+export function maskSecret(value) {+ return headTail(String(value ?? ""), 4);+}++// ---------------------------------------------------------------------------+// Base URL lint+// ---------------------------------------------------------------------------++export function lintBaseUrl(url) {+ const problems = [];+ const value = String(url ?? "");+ if (!value.trim()) {+ problems.push({ level: "fail", message: "base URL is empty", fix: "set url in ovcli.conf or OPENVIKING_URL" });+ return problems;+ }+ if (value !== value.trim() || /\s/.test(value)) {+ problems.push({ level: "fail", message: "base URL contains whitespace", fix: "remove stray spaces/newlines around the url value" });+ }+ if (!/^https?:\/\//i.test(value.trim())) {+ problems.push({ level: "fail", message: "base URL has no http:// or https:// scheme — fetch() rejects it as 'Failed to parse URL'", fix: "prefix the url with http:// or https://" });+ return problems;+ }+ let parsed;+ try {+ parsed = new URL(value.trim());+ } catch {+ problems.push({ level: "fail", message: "base URL does not parse", fix: "check the url value for typos" });+ return problems;+ }+ const path = parsed.pathname.replace(/\/+$/, "");+ if (/\/api(\/v1)?$/i.test(path)) {+ problems.push({ level: "fail", message: `base URL ends with ${path} — every request becomes ${path}/api/v1/... and 404s`, fix: "drop the /api/v1 suffix; the plugin appends API paths itself" });+ }+ if (/\/mcp$/i.test(path)) {+ problems.push({ level: "fail", message: "base URL ends with /mcp — the plugin appends /mcp itself", fix: "use the server root URL, not the MCP endpoint" });+ }+ if (parsed.hostname === "0.0.0.0") {+ problems.push({ level: "warn", message: "host 0.0.0.0 is a bind address, not a destination", fix: "use 127.0.0.1 or the real hostname" });+ }+ if (parsed.search || parsed.hash) {+ problems.push({ level: "warn", message: "base URL carries a query string or fragment", fix: "remove everything after the path" });+ }+ return problems;+}++export function isLoopbackUrl(url) {+ try {+ const host = new URL(url).hostname;+ return host === "127.0.0.1" || host === "localhost" || host === "::1" || host === "[::1]";+ } catch {+ return false;+ }+}++// ---------------------------------------------------------------------------+// Files and environment+// ---------------------------------------------------------------------------++export function inspectJsonFile(path) {+ const out = { path, exists: false, ok: false, error: "", data: null, mode: "", size: 0, mtimeMs: 0 };+ if (!path) return out;+ let st;+ try {+ st = statSync(path);+ } catch {+ return out;+ }+ out.exists = true;+ out.size = st.size;+ out.mtimeMs = st.mtimeMs;+ out.mode = (st.mode & 0o777).toString(8);+ let raw;+ try {+ raw = readFileSync(path, "utf-8");+ } catch (err) {+ out.error = `unreadable: ${err?.message || err}`;+ return out;+ }+ try {+ out.data = JSON.parse(raw);+ out.ok = out.data !== null && typeof out.data === "object";+ if (!out.ok) out.error = "top level is not a JSON object";+ } catch (err) {+ out.error = `invalid JSON: ${err?.message || err}`;+ }+ return out;+}++const KNOWN_OVCLI_KEYS = new Set([+ "url", "api_key", "root_api_key", "account", "user", "account_id", "user_id",+ "actor_peer_id", "peer_id", "agent_id", "timeout", "output", "echo_command",+ "extra_headers", "gateway_token", "auth_mode", "ldap_username", "ldap_password", "plugin",+]);++/** Keys in ovcli.conf that neither the CLI nor the plugins read — usually typos. */+export function unknownOvcliKeys(data) {+ if (!data || typeof data !== "object") return [];+ return Object.keys(data).filter((k) => !KNOWN_OVCLI_KEYS.has(k));+}++const SECRET_ENV = /KEY|TOKEN|SECRET|PASSWORD/i;++export function collectEnv(env = process.env) {+ const openviking = [];+ for (const name of Object.keys(env).sort()) {+ if (!name.startsWith("OPENVIKING_")) continue;+ const value = env[name] ?? "";+ openviking.push({ name, value: SECRET_ENV.test(name) ? maskSecret(value) : value });+ }+ const proxy = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy"]+ .filter((name) => str(env[name]))+ .map((name) => ({ name, value: env[name] }));+ const node = ["NODE_EXTRA_CA_CERTS", "NODE_TLS_REJECT_UNAUTHORIZED", "NODE_USE_ENV_PROXY", "NODE_OPTIONS"]+ .filter((name) => str(env[name]))+ .map((name) => ({ name, value: env[name] }));+ return { openviking, proxy, node };+}++/** Legacy rc-file wrapper blocks written by pre-stdio-proxy installers. */+export function scanRcFiles(markers, home = homedir()) {+ const hits = [];+ for (const file of [".zshrc", ".bashrc", ".zprofile", ".bash_profile", ".profile"]) {+ const path = `${home}/${file}`;+ let text;+ try {+ text = readFileSync(path, "utf-8");+ } catch {+ continue;+ }+ for (const marker of markers) {+ if (text.includes(marker)) hits.push({ file: homeShort(path), kind: "block", detail: marker });+ }+ const exported = [...new Set([...text.matchAll(/^\s*export\s+(OPENVIKING_[A-Z0-9_]+)=/gm)].map((m) => m[1]))];+ if (exported.length) hits.push({ file: homeShort(path), kind: "export", detail: exported.join(", "), vars: exported });+ }+ return hits;+}++// ---------------------------------------------------------------------------+// Commands+// ---------------------------------------------------------------------------++export function runCommand(command, args = [], { timeoutMs = 10000, env = process.env } = {}) {+ try {+ const stdout = execFileSync(command, args, {+ encoding: "utf-8",+ timeout: timeoutMs,+ env,+ stdio: ["ignore", "pipe", "pipe"],+ });+ return { ok: true, stdout: String(stdout).trim(), stderr: "" };+ } catch (err) {+ return {+ ok: false,+ stdout: String(err?.stdout ?? "").trim(),+ stderr: String(err?.stderr ?? "").trim(),+ error: err?.code === "ENOENT" ? "not found" : (err?.killed ? `timed out after ${timeoutMs}ms` : (err?.message || String(err))),+ };+ }+}++export function whichCommand(name) {+ const result = runCommand(process.platform === "win32" ? "where" : "which", [name], { timeoutMs: 5000 });+ return result.ok ? result.stdout.split("\n")[0] : "";+}++export function parseNodeMajor(version) {+ const m = /^v?(\d+)/.exec(String(version || ""));+ return m ? Number(m[1]) : NaN;+}++// ---------------------------------------------------------------------------+// HTTP probes+// ---------------------------------------------------------------------------++export function classifyFetchError(err) {+ const cause = err?.cause || err;+ const code = cause?.code || "";+ const message = String(cause?.message || err?.message || err || "");+ if (err?.name === "AbortError" || /aborted/i.test(message)) {+ return { kind: "timeout", hint: "no response within the timeout — wrong host/port, firewall, or a very slow server" };+ }+ if (code === "ECONNREFUSED") return { kind: "refused", hint: "connection refused — nothing is listening on that host:port (server down or wrong port)" };+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") return { kind: "dns", hint: "hostname does not resolve — typo in the url, or DNS/VPN not available" };+ if (code === "ECONNRESET" || code === "EPIPE") return { kind: "reset", hint: "connection reset — a proxy or TLS terminator closed the connection" };+ if (/certificate|CERT_|SELF_SIGNED|UNABLE_TO_VERIFY|ssl|tls/i.test(`${code} ${message}`)) {+ return { kind: "tls", hint: "TLS verification failed — private CA or self-signed cert; Node ignores the OS keychain, set NODE_EXTRA_CA_CERTS for the harness process" };+ }+ if (/Failed to parse URL|Invalid URL/i.test(message)) return { kind: "url", hint: "the url does not parse — check scheme and host" };+ if (/wrong version number|EPROTO/i.test(`${code} ${message}`)) return { kind: "tls", hint: "protocol mismatch — https:// against a plain-HTTP port (or vice versa)" };+ return { kind: "other", hint: message };+}++export async function httpProbe({ url, method = "GET", headers = {}, body, timeoutMs = 5000 }) {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs);+ const t0 = Date.now();+ const out = { url, method, ok: false, status: 0, latencyMs: 0, text: "", json: null, headers: {}, error: "", errorKind: "", errorHint: "" };+ try {+ const res = await fetch(url, { method, headers, body, signal: controller.signal, redirect: "manual" });+ out.status = res.status;+ out.ok = res.ok;+ out.latencyMs = Date.now() - t0;+ for (const [k, v] of res.headers.entries()) out.headers[k.toLowerCase()] = v;+ const text = await res.text().catch(() => "");+ out.text = text.length > 4000 ? `${text.slice(0, 4000)}…` : text;+ const contentType = out.headers["content-type"] || "";+ if (contentType.includes("text/event-stream")) {+ // Streamable HTTP frames: take the first data: line.+ const line = text.split("\n").find((l) => l.startsWith("data:"));+ if (line) {+ try { out.json = JSON.parse(line.slice(5).trim()); } catch { /* keep text */ }+ }+ } else {+ try { out.json = JSON.parse(text); } catch { /* not JSON */ }+ }+ } catch (err) {+ out.latencyMs = Date.now() - t0;+ const cls = classifyFetchError(err);+ out.error = err?.cause?.message || err?.message || String(err);+ out.errorKind = cls.kind;+ out.errorHint = cls.hint;+ } finally {+ clearTimeout(timer);+ }+ return out;+}++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;+}++export function serverErrorMessage(probe) {+ const body = probe?.json;+ if (!body) return probe?.text ? probe.text.replace(/\s+/g, " ").slice(0, 200) : "";+ return body?.error?.message || body?.error?.code || body?.message || body?.detail || "";+}++/**+ * Run the standard probe ladder against an OpenViking server.+ *+ * health GET /health without credentials — reachability, version, auth_mode+ * healthAuth GET /health with credentials — identity echo (account/user/role)+ * systemStatus GET /api/v1/system/status — first authenticated call the hooks make; real 401/403+ * fsLs GET /api/v1/fs/ls?uri=viking://~/memories — tenant-data authorization + resolved user space+ * mcp POST /mcp tools/list — what the MCP proxy forwards+ */+export async function probeOpenViking(conn, { timeoutMs = 5000, mcp = true } = {}) {+ const base = String(conn.baseUrl || "").replace(/\/+$/, "");+ const out = {};+ out.health = await httpProbe({ url: `${base}/health`, timeoutMs, headers: conn.userAgent ? { "User-Agent": conn.userAgent } : {} });+ if (out.health.error && out.health.errorKind !== "other") {+ // Hard network failure: the rest of the ladder would fail identically.+ return out;+ }+ if (conn.apiKey || conn.account || conn.user) {+ out.healthAuth = await httpProbe({ url: `${base}/health`, timeoutMs, headers: authHeaders(conn) });+ }+ out.systemStatus = await httpProbe({ url: `${base}/api/v1/system/status`, timeoutMs, headers: authHeaders(conn) });+ out.fsLs = await httpProbe({+ url: `${base}/api/v1/fs/ls?uri=${encodeURIComponent("viking://~/memories")}&output=original`,+ timeoutMs,+ headers: authHeaders(conn),+ });+ if (mcp) {+ out.mcp = await httpProbe({+ url: `${base}/mcp`,+ method: "POST",+ timeoutMs: Math.max(timeoutMs, 8000),+ headers: { ...authHeaders(conn), Accept: "application/json, text/event-stream", "MCP-Protocol-Version": "2025-06-18" },+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }),+ });+ }+ return out;+}++/**+ * Turn probe results into findings. `keyInfo` is describeApiKey(conn.apiKey).+ * Returns { authMode, version, identity } for callers that want to cross-check.+ */+export function assessProbes(report, probes, conn, keyInfo) {+ const summary = { authMode: "", version: "", identity: null, reachable: false, authOk: false };+ const health = probes.health;+ if (!health) return summary;++ if (health.error) {+ report.fail(`server unreachable: ${conn.baseUrl}`, `${health.errorKind || "error"}: ${health.error}\n${health.errorHint}`,+ "check that the server is running and the url/port are right; compare with `curl -sS <url>/health`");+ return summary;+ }+ summary.reachable = true;+ if (health.status === 404) {+ report.fail(`GET /health → 404 at ${conn.baseUrl}`, "the url points at a web server, but not at an OpenViking API root",+ "check for a missing path prefix (OpenViking Cloud needs /openviking) or a reverse proxy that does not forward /health");+ return summary;+ }+ if (health.status >= 300 && health.status < 400) {+ report.fail(`GET /health → ${health.status} redirect`, `location: ${health.headers.location || "?"}`,+ "the url is being redirected (http→https, or an SSO/login gateway); use the final url");+ return summary;+ }+ if (health.status === 503 && health.json?.status === "pending_initialization") {+ const fixes = Array.isArray(health.json.fix) ? health.json.fix.map((f) => `- ${f}`).join("\n") : "";+ report.fail("the OpenViking docker container is up but has no ov.conf — every request answers 503 until it does",+ `${health.json.error || ""}${health.json.config_file ? ` (expected at ${health.json.config_file} inside the container)` : ""}${fixes ? `\n${fixes}` : ""}`,+ "mount ~/.openviking (holding ov.conf) at /app/.openviking, or run `docker exec -it openviking openviking-server init`");+ return summary;+ }+ if (!health.ok || !health.json) {+ report.fail(`GET /health → ${health.status}`, serverErrorMessage(health) || "(non-JSON body)",+ "the server answered but not like OpenViking — verify the url reaches the OpenViking API, not a proxy error page");+ return summary;+ }+ summary.authMode = String(health.json.auth_mode || "");+ summary.version = String(health.json.version || "");+ report.ok(`server reachable — ${health.latencyMs}ms, version ${summary.version || "?"}, auth_mode=${summary.authMode || "?"}`);+ if (health.latencyMs > 1000) {+ report.warn(`/health took ${health.latencyMs}ms`, "the statusline probe has a 1s budget and will flap between 'slow' and 'offline'",+ "check network latency to the server; raise OPENVIKING_TIMEOUT_MS if hooks time out");+ }++ const identity = probes.healthAuth?.json;+ if (identity && identity.role) {+ summary.identity = { account: identity.account_id, user: identity.user_id, role: identity.role };+ summary.authOk = true;+ report.ok(`credentials accepted — account=${identity.account_id} user=${identity.user_id} role=${identity.role}`);+ if (identity.role === "root") {+ report.warn("using the ROOT api key", "root keys are rejected on tenant-data APIs and /mcp in api_key mode (403 'ROOT API keys cannot access tenant-scoped data APIs')",+ "create a user key (POST /api/v1/admin/accounts/<account>/users with the root key) and put that in ovcli.conf");+ }+ if (summary.authMode === "api_key" && keyInfo?.format === "v2") {+ if (keyInfo.account && keyInfo.account !== identity.account_id) {+ report.warn(`key claims account=${keyInfo.account} but server resolved account=${identity.account_id}`);+ }+ }+ if (summary.authMode === "api_key" && (conn.account || conn.user)) {+ const mismatch = (conn.account && conn.account !== identity.account_id) || (conn.user && conn.user !== identity.user_id);+ if (mismatch) {+ report.warn(`configured account/user (${conn.account || "-"}/${conn.user || "-"}) differ from the key's identity (${identity.account_id}/${identity.user_id})`,+ "in api_key mode the server ignores X-OpenViking-Account/User headers; the key decides where data lands",+ "remove account/user from the config, or use a key issued for that account/user");+ } else {+ report.info("account/user in config are redundant in api_key mode (identity comes from the key)");+ }+ }+ } else if (summary.authMode === "dev") {+ summary.authOk = true;+ report.info("server runs in dev auth mode — any key is accepted; identity comes from X-OpenViking-Account/User headers (default 'default')");+ if (identity?.account_id) summary.identity = { account: identity.account_id, user: identity.user_id, role: identity.role };+ } else if (conn.apiKey) {+ report.fail("api key rejected", `/health answered 200 but returned no identity for the key (${keyInfo?.display || "?"}) — the key is invalid, revoked, or belongs to another deployment`,+ "check the key in ovcli.conf / OPENVIKING_API_KEY against the one issued by the server admin");+ } else if (summary.authMode === "api_key") {+ report.fail("no api key configured but the server requires one (auth_mode=api_key)", "",+ "set api_key in ~/.openviking/ovcli.conf or OPENVIKING_API_KEY");+ } else if (summary.authMode === "trusted") {+ if (!conn.account || !conn.user) {+ report.fail("server is in trusted mode and needs account + user", "requests without X-OpenViking-Account/User are rejected with HTTP 400",+ "set account and user in ovcli.conf (or OPENVIKING_ACCOUNT / OPENVIKING_USER)");+ } else {+ summary.authOk = true;+ report.ok(`trusted mode — identity from headers account=${conn.account} user=${conn.user}`);+ }+ }++ const status = probes.systemStatus;+ if (status) {+ if (status.ok) {+ const user = status.json?.result?.user;+ report.ok(`GET /api/v1/system/status → 200${user ? ` (user space: ${user})` : ""}`);+ } else if (status.error) {+ report.fail("GET /api/v1/system/status failed", `${status.errorKind}: ${status.error}`);+ } else {+ const msg = serverErrorMessage(status);+ const level = status.status === 401 || status.status === 403 ? "fail" : "warn";+ report[level](`GET /api/v1/system/status → ${status.status}`, msg,+ status.status === 401 ? "the server rejected the credentials — this is what every hook hits after the /health gate passes"+ : status.status === 403 ? "the key is valid but not allowed here — wrong role or root key" : "");+ }+ }++ const fs = probes.fsLs;+ if (fs) {+ if (fs.ok) {+ const first = Array.isArray(fs.json?.result) ? fs.json.result.find((e) => e?.uri) : null;+ const space = first?.uri ? String(first.uri).replace(/\/memories\/.*$/, "/memories") : "";+ report.ok(`GET /api/v1/fs/ls viking://~/memories → 200${space ? ` (${space})` : ""}`);+ } else if (!fs.error) {+ const msg = serverErrorMessage(fs);+ if (fs.status === 403 && /ROOT/i.test(msg)) {+ report.fail("tenant data API rejects this key (root key)", msg, "use a user/admin key, not server.root_api_key");+ } else if (fs.status === 400) {+ report.warn(`GET /api/v1/fs/ls viking://~/memories → 400`, msg,+ /Trusted mode/i.test(msg) ? "set account/user for trusted mode" : "the server may be too old for the viking://~ home alias — upgrade the server");+ } else if (fs.status === 404) {+ report.info("viking://~/memories does not exist yet (nothing captured for this user so far)");+ } else if (fs.status !== 401) {+ report.warn(`GET /api/v1/fs/ls viking://~/memories → ${fs.status}`, msg);+ }+ }+ }++ const mcp = probes.mcp;+ if (mcp) {+ if (mcp.ok && mcp.json?.result?.tools) {+ report.ok(`POST /mcp tools/list → ${mcp.json.result.tools.length} tools`);+ } else if (mcp.error) {+ report.fail("POST /mcp failed", `${mcp.errorKind}: ${mcp.error}`);+ } else {+ const msg = serverErrorMessage(mcp) || mcp.text.replace(/\s+/g, " ").slice(0, 160);+ const hints = {+ 401: "credentials rejected on /mcp",+ 403: "key valid but not allowed on /mcp (root key in api_key mode)",+ 404: "no MCP endpoint at <url>/mcp — missing path prefix, old server, or a reverse proxy that does not forward /mcp",+ 406: "server did not accept the Accept header — something between client and server rewrites headers",+ 502: "reverse proxy cannot reach the upstream",+ 504: "reverse proxy timed out (SSE needs proxy_buffering off)",+ };+ report.fail(`POST /mcp tools/list → ${mcp.status}`, msg, hints[mcp.status] || "");+ }+ }+ return summary;+}++// ---------------------------------------------------------------------------+// State and logs+// ---------------------------------------------------------------------------++export function readStateFiles(stateDir, names) {+ const out = {};+ for (const name of names) {+ const path = `${stateDir}/${name}`;+ const entry = { path, exists: false, ageMs: null, data: null, error: "" };+ try {+ const st = statSync(path);+ entry.exists = true;+ entry.mtimeMs = st.mtimeMs;+ const data = JSON.parse(readFileSync(path, "utf-8"));+ entry.data = data;+ entry.ageMs = typeof data?.ts === "number" ? Date.now() - data.ts : Date.now() - st.mtimeMs;+ } catch (err) {+ if (entry.exists) entry.error = err?.message || String(err);+ }+ out[name] = entry;+ }+ return out;+}++export function countDirEntries(dir, filter = () => true) {+ try {+ return readdirSync(dir).filter(filter).length;+ } catch {+ return null;+ }+}++export function fileInfo(path) {+ try {+ const st = statSync(path);+ return { exists: true, size: st.size, mtimeMs: st.mtimeMs };+ } catch {+ return { exists: false, size: 0, mtimeMs: 0 };+ }+}++/**+ * Scan a JSONL hook log. Returns the last `maxErrors` error entries, the last+ * mcp-proxy start record, and which hooks have written anything.+ */+export function scanDebugLog(path, { maxErrors = 5, maxBytes = 512 * 1024 } = {}) {+ const out = { path, exists: false, size: 0, mtimeMs: 0, lines: 0, errors: [], proxyStart: null, hooks: [] };+ const info = fileInfo(path);+ if (!info.exists) return out;+ Object.assign(out, { exists: true, size: info.size, mtimeMs: info.mtimeMs });+ let text;+ try {+ text = readFileSync(path, "utf-8");+ } catch {+ return out;+ }+ if (text.length > maxBytes) text = text.slice(-maxBytes);+ const hooks = new Set();+ const errors = [];+ for (const line of text.split("\n")) {+ if (!line.trim()) continue;+ out.lines += 1;+ let entry;+ try {+ entry = JSON.parse(line);+ } catch {+ continue;+ }+ if (entry.hook) hooks.add(entry.hook);+ if (entry.hook === "mcp-proxy" && entry.stage === "start") out.proxyStart = entry;+ if (entry.error) {+ errors.push({ ts: entry.ts, hook: entry.hook, stage: entry.stage, message: entry.error?.message || String(entry.error) });+ }+ }+ // Only errors from the last day of logging are "recent"; older ones are+ // history that predates whatever the user is debugging now.+ const cutoff = out.mtimeMs - 24 * 60 * 60 * 1000;+ out.errors = errors.slice(-maxErrors);+ out.recentErrors = errors.filter((e) => Date.parse(e.ts || "") >= cutoff).slice(-maxErrors);+ out.hooks = [...hooks].sort();+ return out;+}++export function existsPath(path) {+ return Boolean(path) && existsSync(path);+}++// ---------------------------------------------------------------------------+// Server health+//+// `GET /ready` is the server's own verdict on its subsystems and works+// against any deployment. The port and ov.conf checks only apply when the+// server runs on this machine (loopback url). Everything else server-side —+// config validation, live embedding probe, native engine, disk — is+// `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" };+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",+ vectordb: "the vector index is unhealthy — check <storage.workspace>/vectordb and the server log; stop duplicate servers on the same workspace",+ agfs: "the content filesystem failed — check <storage.workspace>/viking, free disk space and the server log",+ api_key_manager: "the api key store failed to load — check <storage.workspace>/viking/_system and the server log",+ ollama: "start Ollama (or fix its host/port in ov.conf) — the server cannot reach it",+};++function isObject(v) {+ return Boolean(v) && typeof v === "object" && !Array.isArray(v);+}++/**+ * ov.conf keys that only the plugins read. The server validates its config+ * strictly and refuses to start on them, which shows up as "the server is+ * gone since I edited ov.conf". Returns [{ level, message, detail, fix }].+ */+export function lintServerConf(data) {+ const out = [];+ if (!isObject(data)) return out;+ for (const [key, dest] of Object.entries(PLUGIN_ONLY_OV_CONF_KEYS)) {+ if (!(key in data)) continue;+ out.push({+ level: "warn",+ message: `ov.conf has a top-level '${key}' block, which the server rejects at startup ("Unknown config field '${key}'")`,+ detail: "the plugin reads it, openviking-server does not; a server that is already running is unaffected until its next restart",+ fix: `move those settings to ${dest} (or OPENVIKING_* env) and delete the block; if this ov.conf never starts a server, ignore`,+ });+ }+ if (isObject(data.server) && "url" in data.server) {+ out.push({+ level: "warn",+ message: "ov.conf server.url is rejected by the server at startup (\"Extra inputs are not permitted\")",+ detail: "only the plugin and the CLI read server.url; the server validates its section strictly",+ fix: "put the url in ovcli.conf (url) and remove server.url; if this ov.conf never starts a server, ignore",+ });+ }+ return out;+}++/** Who listens on a TCP port (lsof on macOS/Linux, ss on Linux). */+export function findPortListener(port) {+ const out = { tool: "", pid: null, command: "", error: "" };+ if (process.platform === "win32") {+ out.error = "not supported on Windows";+ return out;+ }+ if (whichCommand("lsof")) {+ out.tool = "lsof";+ const r = runCommand("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-F", "pc"], { timeoutMs: 8000 });+ for (const line of r.stdout.split("\n")) {+ if (line.startsWith("p") && out.pid === null) out.pid = Number(line.slice(1));+ else if (line.startsWith("c") && !out.command) out.command = line.slice(1);+ }+ return out;+ }+ if (whichCommand("ss")) {+ out.tool = "ss";+ const r = runCommand("ss", ["-ltnpH", `sport = :${port}`], { timeoutMs: 8000 });+ const m = r.stdout.match(/users:\(\("([^"]+)",pid=(\d+)/);+ if (m) {+ out.command = m[1];+ out.pid = Number(m[2]);+ } else if (r.stdout.trim()) {+ out.command = "(owner not visible without root)";+ }+ return out;+ }+ out.error = "neither lsof nor ss is available";+ return out;+}++export async function probeReady(baseUrl, { timeoutMs = 15000 } = {}) {+ const base = String(baseUrl || "").replace(/\/+$/, "");+ return httpProbe({ url: `${base}/ready`, timeoutMs: Math.max(timeoutMs, 15000) });+}++/** Flatten one `/ready` check (string or {status, checks}) into { ok, text }. */+export function readyCheckState(value) {+ if (isObject(value)) {+ const status = String(value.status ?? "");+ const nested = isObject(value.checks) ? Object.entries(value.checks).map(([k, v]) => [k, readyCheckState(v)]) : [];+ const failed = nested.filter(([, s]) => !s.ok);+ return {+ ok: READY_OK_VALUES.has(status) && failed.length === 0,+ text: failed.length ? `${status} (${failed.map(([k, s]) => `${k}: ${s.text}`).join(", ")})` : status,+ };+ }+ const text = String(value ?? "");+ return { ok: READY_OK_VALUES.has(text), text };+}++/** Turn the `/ready` probe into findings. Returns { ready, checks } (ready null when unknown). */+export function assessReady(report, probe) {+ const out = { ready: null, checks: {} };+ if (!probe) return out;+ if (probe.error) {+ if (probe.errorKind === "timeout") report.warn(`GET /ready timed out after ${probe.latencyMs}ms`, "the readiness check embeds one token with the configured provider (10s cap) — a timeout usually means that provider hangs", "run `openviking-server doctor` in the server's environment to see the provider's reply");+ else report.info(`GET /ready failed: ${probe.error}`);+ return out;+ }+ if (probe.status === 404) {+ report.info("server has no /ready endpoint (older version) — subsystem status unavailable over HTTP", "`openviking-server doctor` in the server's environment covers embedding/VLM/storage");+ return out;+ }+ const json = probe.json;+ if (!isObject(json)) {+ report.info(`GET /ready → ${probe.status} without a JSON body`);+ return out;+ }+ if (probe.status === 503 && json.status === "not_ready" && json.reason === "initializing" && !isObject(json.checks)) {+ out.ready = false;+ report.warn("server is still initializing (503 /ready)", "storage and the embedder are being set up; the first start of a local embedding model downloads it", "wait and rerun; if it never finishes, read the server log");+ return out;+ }+ if (!isObject(json.checks)) {+ report.info(`GET /ready → ${probe.status}: ${JSON.stringify(json).slice(0, 200)}`);+ return out;+ }+ const states = Object.entries(json.checks).map(([k, v]) => [k, readyCheckState(v)]);+ out.checks = Object.fromEntries(states.map(([k, s]) => [k, s.text]));+ const failed = states.filter(([, s]) => !s.ok);+ out.ready = failed.length === 0 && probe.ok;+ const summary = states.map(([k, s]) => `${k} ${s.text}`).join(", ");+ if (out.ready) {+ report.ok(`/ready: ${summary}`);+ } else {+ for (const [key, s] of failed) report.fail(`/ready: ${key} → ${s.text}`, "", READY_FIXES[key] || "see the server log");+ if (!failed.length) report.warn(`/ready → ${probe.status}: ${summary}`, "", "read the server log");+ }+ return out;+}++function urlHostPort(baseUrl) {+ try {+ const u = new URL(baseUrl);+ return { host: u.host, port: Number(u.port || (u.protocol === "https:" ? 443 : 80)) };+ } catch {+ return null;+ }+}++/**+ * The "Server health" section. `health` is the /health probe already taken+ * for the Connection section; `ovConf` is inspectJsonFile(<ov.conf path>).+ */+export async function checkServerHealth(report, { baseUrl, ovConf, health, offline = false, timeoutMs = 5000 } = {}) {+ report.section("Server health");+ const answered = Boolean(health && !health.error && health.ok && isObject(health.json));+ const summary = { local: isLoopbackUrl(baseUrl), reachable: answered, ready: null, listener: null };+ const target = urlHostPort(baseUrl);++ if (!summary.local) {+ report.info(`server at ${target?.host || baseUrl} is not on this machine — only /ready is probed; \`openviking-server doctor\` on the server host covers the rest`);+ } else {+ if (ovConf?.ok) {+ for (const f of lintServerConf(ovConf.data)) report[f.level](f.message, f.detail, f.fix);+ }+ const listener = findPortListener(target.port);+ if (listener.pid) {+ summary.listener = { pid: listener.pid, command: listener.command };+ report.info(`port ${target.port} is served by pid ${listener.pid} (${listener.command})`);+ } else if (listener.error) {+ report.info(`could not determine who listens on port ${target.port} (${listener.error})`);+ } else if (!answered) {+ report.fail(`nothing listens on port ${target.port} — the server is not running`, "",+ "start it: `openviking-server` (first time: `openviking-server init`), or `docker start openviking` for a container install; a startup error is printed right there");+ }+ report.info("provider-level checks (embedding probe, VLM key, native engine, disk): `openviking-server doctor` in the server's own environment");+ }++ if (offline) report.info("skipped /ready (--offline)");+ else if (health?.json?.status === "pending_initialization") report.info("skipped /ready — the container has no config yet");+ else if (!answered) report.info("skipped /ready — the server did not answer /health");+ else summary.ready = assessReady(report, await probeReady(baseUrl, { timeoutMs })).ready;+ return summary;+}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.mdnew file mode 100644index 000000000..4a79a9f7b--- /dev/null+++ b/examples/claude-code-memory-plugin/skills/ov-memory-doctor/SKILL.md@@ -0,0 +1,210 @@+---+name: ov-memory-doctor+description: >+ Diagnose and fix the OpenViking memory plugin on this machine: the plugin+ install (marketplace, enablement, hooks, MCP server), the client+ configuration (ovcli.conf / ov.conf / OPENVIKING_* env — which one wins, what+ the API key claims) and the connection to the OpenViking server+ (reachability, 401/403, /mcp). Use whenever memory "isn't working": no+ <openviking-context> block appears, recall is always empty, captures don't+ land, MCP memory tools are missing or fail, 401/403 errors, the statusline+ says offline, right after installing/updating the plugin or switching+ servers/keys, or when the user asks for the plugin's status. Trigger phrases+ include "memory not working", "check OpenViking", "plugin status", "记忆没生效",+ "插件状态", "连不上 OpenViking", "recall 为空", "401", "0 memories+ extracted". When the server runs on this machine (loopback url) it also+ checks the port, plugin-only keys in ov.conf that stop the server from+ starting, and `GET /ready`; everything else server-side stays with+ `openviking-server doctor`.+allowed-tools: Bash(node ${CLAUDE_PLUGIN_ROOT}/scripts/ov-memory-doctor.mjs *)+---++# OpenViking Memory Doctor++Client-side troubleshooting for the OpenViking memory plugin. The plugin has+three moving parts and each fails silently in its own way:++- **Install** — marketplace registration, plugin enablement, the nine hooks,+ the stdio MCP proxy. When these are wrong, hooks never run and nothing is+ logged anywhere.+- **Configuration** — `~/.openviking/ovcli.conf`, `~/.openviking/ov.conf`+ and `OPENVIKING_*` environment variables, resolved as env → ovcli.conf →+ ov.conf → defaults. A malformed file reads as "no config", which silently+ disables the plugin; a stray env var silently overrides the file.+- **Connection** — `/health` answers 200 even with a bad key, so the statusline+ can be green while every real request 401s.++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+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+`openviking-server doctor`, run in the server's Python environment.++## Step 1 — run the doctor++```bash+node ${CLAUDE_PLUGIN_ROOT}/scripts/ov-memory-doctor.mjs+```++Options: `--json` (machine-readable), `--offline` (skip network probes),+`--timeout <ms>` (per probe, default 5000), `--no-color`.++The report has six sections — Environment, Plugin install, Configuration,+Connection, Server health, Recent activity — and a Summary listing every ✗/⚠+with a fix.+Read the whole report before acting: a single root cause usually shows up in+several sections (for example a bad key → "api key rejected" + "system/status+→ 401" + `turns_failed > 0`).++If the report says "this script is not running from the registered install",+rerun it from the path it prints — Claude Code executes hooks from that copy.++The API key is never printed in full. Three-segment keys are shown as+`account=<a> user=<u> secret=abcd…wxyz` (the first two segments are just+base64url identity, decoded so the user can see which account/user the key+claims); legacy keys as `abcd…wxyz (64 chars)`. Keep it that way in anything+you show the user.++## Step 2 — map findings to causes++Work top-down; fix the first ✗ and rerun before chasing the next.++| Doctor finding | Meaning | Action |+|---|---|---|+| `plugin disabled — every hook exits immediately` | No parseable config, `OPENVIKING_MEMORY_ENABLED=0`, or `claude_code.enabled: false` in ov.conf | Fix the reason it names. Fresh machine: create `~/.openviking/ovcli.conf` with `url` + `api_key` (`chmod 600`). |+| `ovcli.conf cannot be parsed` | Trailing comma/comment; the plugin treats the file as absent | Fix the JSON. This is the most common "installed but nothing happens". |+| `not registered in installed_plugins.json` / `claude plugin list does not show …` | Plugin never installed, or installed under an old id | Re-run the one-line installer (`bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) --harness claude`; add `--dist tos` where GitHub is blocked). |+| `plugin is disabled in ~/.claude/settings.json` | Installed but `enabledPlugins` is false/missing | `claude plugin enable openviking-memory@openviking`, restart Claude Code. |+| `marketplace 'openviking' … missing directory` / registered as a file | The checkout/archive moved, or a file-type marketplace (fails `marketplace update` with EISDIR) | `claude plugin marketplace remove openviking` then re-run the installer. |+| `no skills/ directory in this plugin copy` / registered version behind the repo | Stale version-keyed cache; `claude plugin update` is a no-op when the version string did not change | `claude plugin marketplace update openviking && claude plugin uninstall openviking-memory@openviking && claude plugin install openviking-memory@openviking`. |+| `legacy openviking hooks … settings.json` / extra plugin ids / user-scope MCP `openviking` | Pre-2.0 install residue; every hook fires twice, MCP server registered twice | Remove the openviking entries from `.hooks` in `~/.claude/settings.json` (back it up), `claude plugin uninstall <stale id>`, `claude mcp remove openviking -s user`. |+| `node is not on PATH` / node < 18 | Hooks and `.mcp.json` run the bare command `node`; GUI/IDE launches often lack nvm/volta shims | Put node on PATH for the launching environment, or set `PATH` in the `env` block of `~/.claude/settings.json`. |+| `server unreachable` (refused / dns / timeout / tls) | Wrong url/port, server down, DNS/VPN, private CA | Compare with `curl -sS <url>/health`. curl OK + doctor fails ⇒ proxy or CA issue (see Step 3). |+| `base URL ends with /api/v1` or `/mcp`, no scheme, `GET /health → 404` | url shape wrong (paths are concatenated bare); Cloud needs the `/openviking` prefix | Fix `url` to the API root. |+| `api key rejected` (200 from /health with no identity) then `system/status → 401 Invalid API Key` | Key invalid/revoked/for another deployment. A 3-segment key for a non-existent account looks identical. | Get the key re-issued; check no env var shadows ovcli.conf ("← env" in the Configuration section). |+| `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". |+| `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`. |+| `turns_failed > 0` / `capture payload(s) waiting` | Writes rejected (401/403/404 are dropped, not queued) or server was down (queued, replayed at next SessionStart) | Fix credentials/connection; `OPENVIKING_WRITE_PATH_ASYNC=0` makes the error visible on stderr. |+| `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. |+| `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. |+| `server is still initializing (503 /ready)` | First start downloads a local embedding model, or init is slow | Wait and rerun; if it never finishes, the server log. |+| `docker container is up but has no ov.conf` | Official image started without a config mount (every request 503s) | Mount `~/.openviking` at `/app/.openviking`, or `docker exec -it openviking openviking-server init`. |++More symptoms, exact error strings and log stage names: [reference.md](reference.md).++## Step 3 — targeted checks (only when the report is not conclusive)++Prove hooks run at all. `OPENVIKING_DEBUG=1` must reach Claude Code's own+process — a shell export does not, the `env` block in `~/.claude/settings.json`+does. Then send one prompt in a new session and read+`~/.openviking/logs/cc-hooks.log` (JSONL; grep `"error"` and+`"hook":"mcp-proxy","stage":"start"`). A `subagent-stop transcript_read ENOENT`+line is harmless noise.++Prove the key and identity by hand (`Bearer` is case-sensitive with exactly one+space):++```bash+URL=<url>; KEY=<key>+curl -sS "$URL/health" # reachability, version, auth_mode+curl -sS -H "Authorization: Bearer $KEY" "$URL/health" # 200 without account_id/user_id/role ⇒ key invalid+curl -sS -w '\n%{http_code}\n' -H "Authorization: Bearer $KEY" "$URL/api/v1/system/status" # real 401/403+```++Prove `/mcp` directly (stateless — no initialize needed):++```bash+curl -sS -o /dev/null -w '%{http_code}\n' -X POST "$URL/mcp" \+ -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \+ -H "Authorization: Bearer $KEY" -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'+```++Prove Claude Code's MCP wiring: `claude mcp list` (slow, 30–60s) must show+`plugin:openviking-memory:openviking: node <installPath>/servers/mcp-proxy.mjs - ✔ Connected`;+`claude mcp get 'plugin:openviking-memory:openviking'` needs the full quoted+name. `/mcp` inside a session reconnects the proxy.++Prove a capture landed: take `ov_session_id` from+`~/.openviking/state/last-capture.json` and `GET $URL/api/v1/sessions/<id>`+(or `ov session get <id>`); `total_message_count` should be ≥ the captured+turns, `commit_count > 0` proves extraction ran.++Second opinion from the CLI: `ov health` and `ov config validate` read the+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+curl -sS "$URL/ready" # agfs / vectordb / api_key_manager / embedding (live probe, ≤10s) / ollama+openviking-server doctor # in the server's own environment: config, native engine, embedding probe, VLM key, disk+lsof -nP -iTCP:1933 -sTCP:LISTEN # who owns the port+docker logs --tail 100 openviking # container deployments+```++`log.output` defaults to stdout, so the server log is the terminal/tmux pane+it runs in, the nohup file, `journalctl -u openviking`, or `docker logs`;+with `"file"` it is `<storage.workspace>/log/openviking.log`. A server that+exits at startup prints the reason right there — running `openviking-server`+in the foreground is the quickest way to see it. It is the user's process:+ask before stopping or restarting it.++## Fixing++- Edit `~/.openviking/ovcli.conf` only with the user's agreement; show the+ change, keep unknown keys, keep mode 0600, never echo the key.+- Prefer env vars in the `env` block of `~/.claude/settings.json` for+ machine-wide overrides; a shell rc export only reaches sessions started from+ that shell and silently outranks the file everywhere.+- After changing `url`, installing or updating the plugin: restart Claude+ Code. Hooks re-read config per invocation, the MCP proxy does not.+- Updates: GitHub installs → `claude plugin marketplace update openviking && claude plugin update openviking-memory@openviking`;+ TOS/archive and dev-checkout installs → re-run the installer.+- Confirm the fix by rerunning the doctor, then by observing an+ `<openviking-context>` block on the next prompt.++## Documentation++- Source and issues: <https://github.com/volcengine/OpenViking> — plugin code lives under `examples/`, the shared installer under `examples/memory-plugin-shared/`.+- Documentation index (LLM-friendly): <https://docs.openviking.ai/llms.txt>; the harness integration pages under it cover install paths, configuration keys and known limitations.+- `https://api.vikingdb.cn-beijing.volces.com/openviking` is the Volcengine-hosted OpenViking Service (OpenViking Cloud): the path prefix is part of the base url, it accepts `Authorization: Bearer` only, and its keys are issued from the Volcengine console rather than by a self-hosted admin.++## Rules++- 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+ (early exit under `pipefail` reads as "not installed").+- `/health` returning 200 proves reachability only. Auth is proven by the+ identity fields with a key, or by `/api/v1/system/status`.+- `ov doctor` is `openviking-server doctor`: it validates the server's own+ config and providers in the server's Python environment, makes a live+ embedding call, and says nothing about this plugin. Run it for provider-level+ failures, not first.+- The doctor only reads. Never stop, restart or `kill` the user's server, or+ edit `ov.conf`, without asking.+- Older proxy versions say "check that 'ov serve' is running" — there is no+ such command; the server is started with `openviking-server`.+- `OPENVIKING_MEMORY_ENABLED=0` disables the hooks but not the MCP tools;+ `OPENVIKING_MCP_URL` has no effect on this plugin.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.mdnew file mode 100644index 000000000..4b5fb9260--- /dev/null+++ b/examples/claude-code-memory-plugin/skills/ov-memory-doctor/reference.md@@ -0,0 +1,190 @@+# OpenViking Memory Doctor — reference++Companion to SKILL.md: where things live, what the exact error strings mean,+and the symptom catalogue. Paths assume the defaults; `OPENVIKING_HOME`,+`OPENVIKING_CONFIG_FILE`, `OPENVIKING_CLI_CONFIG_FILE`, `OPENVIKING_DEBUG_LOG`+and `OPENVIKING_PENDING_DIR` relocate individual pieces.++## Where things live++| Path | What |+|---|---|+| `~/.openviking/ovcli.conf` | Client connection: `url`, `api_key`, `account`, `user`, optional `plugin.claude_code.*` tuning. Mode 0600. |+| `~/.openviking/ov.conf` | Server config. The plugin reads only `server.url/host/port`, `server.root_api_key` (last-resort key) and the legacy `claude_code` block. |+| `~/.openviking/ovcli.conf.<name>` | Saved CLI profiles (`ov config switch` copies one over `ovcli.conf`). `ovcli.conf.bak.<epoch>` are installer backups, not profiles. |+| `~/.claude/plugins/installed_plugins.json` | Install registry: `plugins["openviking-memory@openviking"][0].installPath/version/lastUpdated`. |+| `~/.claude/plugins/known_marketplaces.json` | Marketplace `openviking` → `source` (`directory` path or `github`), `installLocation`. |+| `~/.claude/plugins/cache/openviking/openviking-memory/<version>/` | The copy Claude Code actually runs. Keyed by `plugin.json` version. |+| `~/.claude/settings.json` | `enabledPlugins`, `statusLine`, optional `env`, legacy `hooks`. |+| `~/.openviking/marketplaces/openviking-claude/` | Installer-generated directory marketplace (GitHub dist) whose manifest points at `git-subdir` `examples/claude-code-memory-plugin`. |+| `~/.openviking/memory-plugin-marketplace/` | Unpacked TOS archive (TOS dist); cannot self-update. |+| `~/.openviking/state/` | `last-recall.json`, `last-capture.json`, `last-session-event.json`, `daily-stats.json`, `server-probe.json`, `host-cli-probe.json`, `context-face.json`, `recall-digest.json`, `ws-peer-<session>.json`. Anything else there is residue. |+| `~/.openviking/last_inject.md` | Full text of the last SessionStart injection. |+| `~/.openviking/logs/cc-hooks.log` | JSONL hook + proxy log; written only when `OPENVIKING_DEBUG=1` or `debug: true`. |+| `~/.openviking/pending/` | Offline write queue (retryable failures only); drained at SessionStart after `/health` passes. |+| `$TMPDIR/openviking-cc-capture-state/<session>.json` | Capture cursor (`capturedTurnCount`). macOS purges `$TMPDIR`, which forces a re-push. |++## Config resolution++| 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` → `claude_code.peerId` → derived from cwd (`/Users/x/proj` → `-Users-x-proj`) unless `OPENVIKING_WORKSPACE_PEER=0` |+| enabled | `OPENVIKING_MEMORY_ENABLED` → `ov.conf claude_code.enabled === false` → "ov.conf or ovcli.conf exists and parses" |+| tuning | env → `ovcli.conf plugin.claude_code.*` → `ovcli.conf plugin.*` → `ov.conf claude_code.*` → defaults |++Only trailing slashes are stripped from the url; no scheme check, no path+normalisation. `https://api.vikingdb.cn-beijing.volces.com/openviking` (the Volcengine-hosted OpenViking Service)+is a legitimate path prefix; `/api/v1` or `/mcp` suffixes are not.++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.++## Server auth modes (from `GET /health` → `auth_mode`)++| Mode | Credential | Identity |+|---|---|---|+| `dev` | none needed, any key accepted | `X-OpenViking-Account/User` headers, else `default`; role root |+| `api_key` | key required | from the key; account/user headers are silently stripped |+| `trusted` | root key optional | from the headers; missing → 400 `Trusted mode requests must include X-OpenViking-Account …` |++Key formats: `base64url(account).base64url(user).base64url(secret)` (three+segments, identity readable) or a bare 64-hex legacy key (identity only via+server lookup). Both fail identically as `401 Invalid API Key` when unknown —+there is no "wrong account" error.++`role: root` keys are allowed only on `/api/v1/system/status`, `/api/v1/admin/*`,+`/api/v1/observer/*`, `/api/v1/tasks/*` and a few system paths; everything the+plugin uses (`/api/v1/sessions`, `/api/v1/search`, `/api/v1/fs`, `/mcp`)+answers `403 ROOT API keys cannot access tenant-scoped data APIs in api_key mode`.++## Error strings++Server (REST): `{"status":"error","error":{"code":…,"message":…}}`++| HTTP | code | message | Meaning |+|---|---|---|---|+| 401 | UNAUTHENTICATED | `Missing API Key when resolving identity.` | No credential reached the server (gateway stripped `Authorization`, or `bearer` lowercase) |+| 401 | UNAUTHENTICATED | `Invalid API Key` | Unknown/revoked key, or a well-formed key for a non-existent account/user |+| 403 | PERMISSION_DENIED | `ROOT API keys cannot access tenant-scoped data APIs …` | Root key used as the plugin key |+| 403 | PERMISSION_DENIED | `Requires role: …` | Key valid, role too low for that route |+| 400 | INVALID_ARGUMENT | `Trusted mode requests must include X-OpenViking-Account …` | Trusted mode without account/user |+| 412 | FAILED_PRECONDITION | `User deletion is in progress` | The user is being deleted |++`/mcp` directly: `406 Not Acceptable: Client must accept both application/json and text/event-stream`;+`400` plain text `Invalid Content-Type header`; `401/403` as JSON-RPC `-32001`+with the server message; `404` → no MCP endpoint at that url.++Plugin MCP proxy (what Claude Code shows for a failing tool call):++| JSON-RPC | Message | Meaning |+|---|---|---|+| `-32001` | `OpenViking MCP authentication failed (HTTP 401\|403). Check ~/.openviking/ovcli.conf or OPENVIKING_API_KEY …` | Credentials; `data.serverMessage` carries the server text. `data.credentialPath` may name ov.conf even when the key came from ovcli.conf on older versions. |+| `-32001` | `OpenViking MCP request failed. Check the configured URL (<mcpUrl>) …` | Transport: `data.cause` = `fetch failed` (refused/DNS/TLS), `This operation was aborted` (timeout), a JSON `SyntaxError` (garbage SSE body). The url in the message is the one actually used. |+| `-32002` | `OpenViking MCP upstream returned HTTP <n>.` | Any other status; HTML in `data.serverMessage` means the url is not an OpenViking endpoint |+| `-32003` | `OpenViking MCP upstream returned an empty response` | 2xx with blank/non-JSON body — captive portal or proxy interstitial |++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),+`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`,+`skill-experience`, `mcp-proxy`. Ordinary failed proxy requests are not logged+— the JSON-RPC error on stdout is the artifact.++## State file fields++`last-recall.json`: `reason` ∈ `ok`, `no_results`, `filtered_out`, `short_query`,+`offline`, `bypass`, `disabled`, `bad_stdin`; plus `count`, `latency_ms`,+`server_url`, `cc_session_id`, `ts`.++`last-capture.json`: `turns_captured`, `turns_queued` (retryable, will replay),+`turns_failed` (non-retryable, dropped), `pending_tokens` / `commit_threshold`,+`commit_count`, `ov_session_id` (`cc-<claude session id>`), `ts`.++Statusline: `OV ✓` = `/health` 200 within 1s (says nothing about auth);+`OV ⚠ slow` = probe timed out; `OV ✗ offline` = refused/DNS/TLS/non-2xx;+`OV ⚡ bypass` = bypass matched; `✗ N dropped` = `turns_failed`. Segments+disappear after 30 minutes of inactivity — a bare `OV ✓` means idle, not broken.++## Local server (loopback url only)++| Path | What |+|---|---|+| `~/.openviking/ov.conf` (or `OPENVIKING_CONFIG_FILE`, then `/etc/openviking/ov.conf`) | The server's config. The doctor checks the copy the plugin resolves for plugin-only keys; a server started with another `--config` runs from that file instead. |+| `<storage.workspace>/` | Data: `viking/` (content), `vectordb/context/` (index), `_system/queue/queue.db`. `storage.workspace` defaults to `./data` relative to the server's cwd. |+| `<workspace>/log/openviking.log` | Only with `log.output: "file"`. Default is stdout (terminal / tmux / nohup file / `journalctl -u openviking` / `docker logs openviking`). Time-rotated as `openviking.log.YYYY-MM-DD`. |+| docker | Container `openviking`, image `ghcr.io/volcengine/openviking`, `~/.openviking` mounted at `/app/.openviking` (config, ovcli.conf and data). `docker exec openviking openviking-server doctor` works. |++Process: `<python> -E …/bin/openviking-server` — match `openviking-server` in+the command line, never the process name (`Python`). Default bind+`127.0.0.1:1933`; `--host`/`--port` override `server.host`/`server.port`. The+port is bound only after initialization finishes, so "connection refused"+during startup is normal; `/health` 200 says nothing about embedding or VLM.++`GET /ready` (no auth, 200 or 503):+`{"status":"ready"|"not_ready","checks":{"agfs":{"status":…,"checks":{"filesystem":…,"multiwrite_sync":…}},"vectordb":…,"api_key_manager":…,"embedding":…,"ollama":…}}`.+`ok`, `not_configured` and `not_supported` count as healthy; `embedding` is a+real embed call with a 10s cap. `503 {"status":"not_ready","reason":"initializing"}`+while booting; 404 on servers that predate the endpoint. The official docker+image answers every route with `503 {"status":"pending_initialization", "fix":[…]}`+until it has an ov.conf.++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 |+| `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.`) |+| `EmbeddingRebuildRequiredError` / `embedding dimension (…) does not match current configuration` | Embedding model changed on an existing workspace (exit 3) |+| `[Errno 48] / [Errno 98] Address already in use` | Port taken — `lsof -nP -iTCP:1933 -sTCP:LISTEN` |+| `FATAL: AUTHENTICATION HEALTH CHECK FAILED` | OIDC/LDAP backend unreachable |++Runtime signatures in the server log: `Dimension mismatch` (config), `Dense+vector dimension mismatch` (writes dropped), `Credential … failed with auth`+and `Backup VLM also failed` (VLM key), `Embedding circuit breaker is open`+(provider down, messages re-queued).++`openviking-server doctor` (same as `ov doctor`) checks Config, Python,+Native Engine, AGFS, Authentication, Embedding (live probe), VLM (key presence+only), Ollama, VikingBot and Disk. Text only, exit 1 on FAIL, needs the+server's Python environment; the bare Rust `ov` binary (npm / cargo install)+reports `unknown command`.++## Symptom catalogue++| Symptom | Likely cause | Detect | Fix |+|---|---|---|---|+| Plugin listed and enabled, but no `<openviking-context>` ever, no log | No parseable config → hooks exit at once | doctor "plugin disabled"; `/ov` prints `DISABLED` | Create/fix `ovcli.conf` |+| Worked until an edit to `ovcli.conf` | JSON broken by the edit | doctor "cannot be parsed" | Fix JSON |+| Edits to `ovcli.conf` have no effect | Env var or rc-file export wins | doctor "← env"; `env \| grep OPENVIKING_` | Remove the export |+| Recall empty on a healthy server | Wrong key (401 reads as no results), wrong user space, peer scope, threshold | `/health` with key; `/api/v1/system/status` → `result.user`; `last-recall.json.reason` | Fix key; `OPENVIKING_PEER_ID`; lower `OPENVIKING_SCORE_THRESHOLD` |+| Recall empty after moving/renaming the repo | Workspace peer derived from cwd changed (with `recallPeerScope: actor`) | log `auto-recall/start` → `peerSource: workspace` | Pin `OPENVIKING_PEER_ID` or `OPENVIKING_WORKSPACE_PEER=0` |+| Statusline green, MCP tools 401 | `/health` needs no auth | doctor "api key rejected" | Fix key |+| Statusline green, MCP tools missing | Plugin MCP not loaded, node missing for `.mcp.json`, or `/mcp` not proxied | `claude mcp list`; `/mcp` | Fix node/PATH; reverse proxy `/mcp` |+| Everything duplicated (two context blocks, doubled latency) | Legacy `settings.json` hooks + plugin; or two plugin ids enabled | doctor legacy/duplicate warnings | Remove legacy entries |+| `claude plugin update` says up to date but bug persists | Version-keyed cache, version string unchanged | doctor "no skills/ directory"; compare `installPath` version with repo | Uninstall + install |+| Statusline blank | `statusLine.command` path gone, `OPENVIKING_STATUSLINE=off`, or plugin disabled | doctor statusline check | Re-run installer / fix path |+| `UserPromptSubmit hook timed out` | Recall > 60s (server query expansion / rewrite) | `last-recall.json.latency_ms` | `OPENVIKING_RECALL_QUERY_EXPANSION=off`, `OPENVIKING_RECALL_COMPRESS=off` |+| Every prompt is slow by ~10–30s | Local compressor spawns `claude -p` (`recallCompress: auto`) | log `host_compressor_*`; `state/host-cli-probe.json` | `OPENVIKING_RECALL_COMPRESS=off` or `server` |+| `Stop` hook timeouts | Sync write path against a slow server | `writePathAsync` in doctor toggles | Keep `OPENVIKING_WRITE_PATH_ASYNC=1` |+| curl works, plugin says offline | Corporate proxy or private CA; Node ignores both | doctor proxy/TLS hints; `node -e "fetch('<url>/health')"` | `NODE_USE_ENV_PROXY=1` / `NODE_EXTRA_CA_CERTS` in the launching environment |+| Local `Write`/`Edit` denied with "viking:// URIs are OpenViking virtual paths" | Old uri-guard in a stale cache | `grep -c DEFAULT_CONTENT_KEYS <installPath>/scripts/shared/uri-guard.mjs` → 0 | Update the plugin |+| Installer exits silently | Pre-2026-07 installer | No `OpenViking installer stopped unexpectedly.` line | Re-fetch the installer |+| Installer: `Unsupported OS` | Windows | — | Manual marketplace install |+| `0 memories extracted` / commits never produce memories | VLM missing or failing, or embedding failing on the server | doctor `/ready: embedding`; ov.conf without a `vlm` section; server log `Backup VLM also failed` / `Credential … failed with auth` | Fix vlm/embedding in ov.conf, restart the server |+| "server unreachable" right after editing ov.conf | The server exited at its restart because of the edit | doctor Server health lint; the startup text in the server's terminal | Fix the finding, start it again |+| Recall empty and the index never grows after switching the embedding model | Dimension mismatch — every vector write is dropped | startup `EmbeddingRebuildRequiredError`, or log `Dense vector dimension mismatch` while it still runs | Original model, or a fresh workspace |++## Links++- Source: <https://github.com/volcengine/OpenViking>+- Docs index: <https://docs.openviking.ai/llms.txt>diff --git a/examples/codex-memory-plugin/.codex-plugin/plugin.json b/examples/codex-memory-plugin/.codex-plugin/plugin.jsonindex ac62b72e4..f0e06cae7 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.7.6",+ "version": "0.7.7","description": "Long-term semantic memory for Codex, powered by OpenViking. Recall on UserPromptSubmit, incremental add_message on Stop (per turn), commit on PreCompact, and active-window heuristic + idle-TTL sweep on SessionStart (source=startup|clear). Includes a local stdio MCP proxy that reads OpenViking credentials from env/ovcli.conf.","author": {"name": "OpenViking",@@ -18,6 +18,7 @@],"hooks": "./hooks/hooks.json","mcpServers": "./.mcp.json",+ "skills": "./skills/","interface": {"displayName": "OpenViking Memory","shortDescription": "Long-term semantic memory for Codex",diff --git a/examples/codex-memory-plugin/README.md b/examples/codex-memory-plugin/README.mdindex db2dd066d..f5bf2ca7e 100644--- a/examples/codex-memory-plugin/README.md+++ b/examples/codex-memory-plugin/README.md@@ -291,6 +291,16 @@ Codex's hook output schema differs from Claude Code's. Notably:Unlike Claude Code, **Codex does not support `decision: "approve"`**; only `decision: "block"`. A no-op is `{}` (which is what these scripts emit when there's nothing to add).+## Troubleshooting++Start with the bundled doctor — it checks the install (marketplace, `config.toml` enablement, hook trust records, MCP wiring), the resolved config (which file won, API key shown masked), the connection (reachability, auth, `/mcp`) and the session state left by the hooks, and prints a fix for every finding:++```bash+node "$(ls -d ~/.codex/plugins/cache/openviking/openviking-memory/*/ | sort -V | tail -1)scripts/ov-memory-doctor.mjs"+```++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`.+## Plugin Structure```@@ -301,8 +311,13 @@ codex-memory-plugin/│ └── hooks.json # SessionStart + UserPromptSubmit + Stop + PreCompact│ (uses Codex's native ${PLUGIN_ROOT} token; no│ rendering needed on modern Codex)+├── skills/+│ ├── openviking-memory/ # How to use the memory tools+│ ├── ov-experience-memory/+│ └── ov-memory-doctor/ # Install / config / connection / local-server troubleshooting├── scripts/│ ├── config.mjs # Shared config loader (ovcli.conf + env)+│ ├── ov-memory-doctor.mjs # Diagnostics script ($ov-memory-doctor skill)│ ├── capture-utils.mjs # Transcript text extraction, filtering, tool compression│ ├── debug-log.mjs # Structured JSONL logger│ ├── recall-compressor-profile.mjs # Compressor profile detection/cachediff --git a/examples/codex-memory-plugin/scripts/marketplace.test.mjs b/examples/codex-memory-plugin/scripts/marketplace.test.mjsindex 1f8ebcf4a..6a4105f08 100644--- a/examples/codex-memory-plugin/scripts/marketplace.test.mjs+++ b/examples/codex-memory-plugin/scripts/marketplace.test.mjs@@ -120,6 +120,11 @@ test("required plugin files are present", () => {".mcp.json","hooks/hooks.json","skills/ov-experience-memory/SKILL.md",+ "skills/openviking-memory/SKILL.md",+ "skills/ov-memory-doctor/SKILL.md",+ "skills/ov-memory-doctor/reference.md",+ "scripts/ov-memory-doctor.mjs",+ "scripts/shared/doctor-core.mjs",]) {assert.ok(existsSync(join(pluginDir, rel)), `missing required plugin file: ${rel}`);}@@ -184,3 +189,12 @@ test("canonical MCP tool list matches server registrations", () => {].map((match) => match[1].match(/(?:^|,\s*)name="([a-z_]+)"/)?.[1] || match[2]);assert.deepEqual(registered, REAL_MCP_TOOLS);});++test("plugin.json declares the skills directory so Codex loads bundled skills", () => {+ const manifest = readJson(manifestPath);+ assert.equal(manifest.skills, "./skills/");+});++test("memory doctor script parses", () => {+ execFileSync("node", ["--check", join(pluginDir, "scripts", "ov-memory-doctor.mjs")], { stdio: "pipe" });+});diff --git a/examples/codex-memory-plugin/scripts/ov-memory-doctor.mjs b/examples/codex-memory-plugin/scripts/ov-memory-doctor.mjsnew file mode 100644index 000000000..fa149ba86--- /dev/null+++ b/examples/codex-memory-plugin/scripts/ov-memory-doctor.mjs@@ -0,0 +1,454 @@+#!/usr/bin/env node++/**+ * Client-side diagnostics for the OpenViking Codex memory plugin.+ *+ * Covers the plugin install (marketplace, config.toml enablement, hook trust+ * state, MCP wiring), the client config (which file won, is the JSON valid,+ * what the key claims) and the connection to the server (reachability, auth,+ * tenant-data access, /mcp), plus the runtime evidence the hooks leave in+ * ~/.openviking/codex-plugin-state. When the server runs on this machine+ * (loopback url) it also checks+ * the port, plugin-only keys in ov.conf and `GET /ready`. Provider-level validation stays with `openviking-server doctor`.+ *+ * Usage:+ * node ov-memory-doctor.mjs [--json] [--offline] [--timeout <ms>] [--no-color]+ *+ * Exit code 1 when any check fails, 0 otherwise. Never prints a full api key.+ */++import { readFileSync, readdirSync, statSync } from "node:fs";+import { homedir } from "node:os";+import { dirname, join, resolve as resolvePath } from "node:path";+import { fileURLToPath } from "node:url";++import { loadConfig } from "./config.mjs";+import { getStateDir } from "./session-state.mjs";+import {+ assessProbes,+ checkServerHealth,+ collectEnv,+ createReport,+ describeApiKey,+ existsPath,+ fmtAge,+ fmtBytes,+ homeShort,+ inspectJsonFile,+ isLoopbackUrl,+ lintBaseUrl,+ parseNodeMajor,+ probeOpenViking,+ runCommand,+ scanDebugLog,+ scanRcFiles,+ unknownOvcliKeys,+ whichCommand,+} from "./shared/doctor-core.mjs";+import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs";++const PLUGIN_ROOT = resolvePath(dirname(fileURLToPath(import.meta.url)), "..");+const PLUGIN_ID = "openviking-memory@openviking";+const PLUGIN_NAME = "openviking-memory";+const MARKETPLACE = "openviking";+const LEGACY_MARKETPLACE = "openviking-plugins-local";+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", "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"];++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+ * text except strings (unquoted) and booleans.+ */+function readToml(path) {+ let text;+ try {+ text = readFileSync(path, "utf-8");+ } catch {+ return null;+ }+ const sections = { "": {} };+ let current = sections[""];+ for (const rawLine of text.split("\n")) {+ const line = rawLine.trim();+ if (!line || line.startsWith("#")) continue;+ const header = /^\[\[?(.+?)\]\]?$/.exec(line);+ if (header) {+ const name = header[1].trim();+ sections[name] = sections[name] || {};+ current = sections[name];+ continue;+ }+ const kv = /^([A-Za-z0-9_."'-]+)\s*=\s*(.*)$/.exec(line);+ if (!kv) continue;+ const key = kv[1].replace(/^["']|["']$/g, "");+ let value = kv[2].trim();+ if (/^"(.*)"$/.test(value)) value = value.slice(1, -1);+ else if (value === "true") value = true;+ else if (value === "false") value = false;+ current[key] = value;+ }+ return sections;+}++// ---------------------------------------------------------------------------+// 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 };+}++function checkInstall(report, { codexOnPath }) {+ report.section("Plugin install");+ const manifest = tryJson(join(PLUGIN_ROOT, ".codex-plugin", "plugin.json"));+ const version = manifest?.version || "?";+ const inCache = PLUGIN_ROOT.startsWith(CACHE_DIR);+ report.info(`running from ${homeShort(PLUGIN_ROOT)} (version ${version}, ${inCache ? "plugin cache" : "marketplace checkout / dev directory"})`);+ const missing = REQUIRED_PLUGIN_FILES.filter((rel) => !existsPath(join(PLUGIN_ROOT, rel)));+ if (missing.length) report.fail("plugin files missing", missing.join(", "), `codex plugin remove ${PLUGIN_ID} && codex plugin add ${PLUGIN_ID}`);+ else report.ok("plugin files present (hooks, MCP proxy, scripts)");+ if (manifest && !manifest.skills) report.warn("plugin.json does not declare skills", "Codex only loads skills/ when the manifest has \"skills\": \"./skills/\"; this copy predates that", "update the plugin");++ let cacheVersions = [];+ try {+ cacheVersions = readdirSync(CACHE_DIR).filter((n) => existsPath(join(CACHE_DIR, n, ".codex-plugin", "plugin.json"))).sort();+ } catch { /* no cache */ }+ if (cacheVersions.length) {+ report.info(`plugin cache ${homeShort(CACHE_DIR)}: ${cacheVersions.join(", ")}`);+ const newest = cacheVersions[cacheVersions.length - 1];+ if (!inCache && newest !== version) report.warn(`cached plugin ${newest} differs from this copy (${version})`, "Codex runs hooks from the cache", "re-run the installer or `codex plugin marketplace upgrade openviking` and restart Codex");+ }++ // codex CLI view+ let listed = null;+ if (codexOnPath) {+ const list = runCommand("codex", ["plugin", "list", "--json"], { timeoutMs: 30000 });+ if (list.ok) {+ const rows = tryJsonText(list.stdout)?.installed || [];+ const mine = rows.filter((r) => r?.pluginId === PLUGIN_ID);+ const others = rows.filter((r) => r?.pluginId !== PLUGIN_ID && r?.name === PLUGIN_NAME && r?.installed);+ if (!mine.length) report.fail(`codex plugin list does not show ${PLUGIN_ID}`, others.length ? `found: ${others.map((r) => r.pluginId).join(", ")}` : "",+ "bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) --harness codex");+ else {+ listed = mine[0];+ const path = listed.source?.path || "";+ if (listed.installed === false) report.fail(`${PLUGIN_ID} is known to the marketplace but not installed`, "", `codex plugin add ${PLUGIN_ID}`);+ else if (listed.enabled === false) report.fail(`${PLUGIN_ID} is installed but disabled`, "", `set [plugins."${PLUGIN_ID}"] enabled = true in ${homeShort(CODEX_CONFIG)}`);+ else report.ok(`codex plugin list: ${PLUGIN_ID} ${listed.version || ""} installed, enabled`);+ if (path) {+ report.info(`marketplace copy: ${homeShort(path)}`);+ if (!existsPath(join(path, ".codex-plugin", "plugin.json"))) report.fail("marketplace copy no longer exists on disk", homeShort(path), "re-run the installer");+ }+ if (listed.version && listed.version !== version && inCache) report.info(`marketplace lists ${listed.version}; this cache copy is ${version}`);+ }+ if (others.length) report.warn("more than one copy of openviking-memory is installed", others.map((r) => `${r.pluginId} (${r.enabled ? "enabled" : "disabled"})`).join(", "), "remove the stale one or hooks fire twice");+ } else {+ report.info(`codex plugin list --json failed (${list.error || list.stderr.split("\n")[0]})`);+ }+ const mkt = runCommand("codex", ["plugin", "marketplace", "list", "--json"], { timeoutMs: 30000 });+ if (mkt.ok) {+ const rows = tryJsonText(mkt.stdout)?.marketplaces || [];+ const entry = rows.find((m) => m?.name === MARKETPLACE);+ if (!entry) report.fail(`marketplace '${MARKETPLACE}' is not registered`, `known: ${rows.map((m) => m.name).join(", ") || "(none)"}`, "re-run the installer");+ else {+ const src = entry.marketplaceSource || {};+ report.ok(`marketplace '${MARKETPLACE}' → ${src.sourceType || "?"} ${src.source || ""}`.trim());+ if (entry.root && !existsPath(entry.root)) report.fail("marketplace root is missing on disk", homeShort(entry.root), "re-run the installer");+ if (src.sourceType === "git") report.info("update: codex plugin marketplace upgrade openviking (keeps the pinned ref); the installer re-registers with the current ref");+ else report.info("local directory marketplace: re-run the installer to update");+ }+ if (rows.some((m) => m?.name === LEGACY_MARKETPLACE)) report.warn(`legacy marketplace '${LEGACY_MARKETPLACE}' is still registered`, "", `codex plugin marketplace remove ${LEGACY_MARKETPLACE}`);+ }+ }++ // config.toml+ const toml = readToml(CODEX_CONFIG);+ if (!toml) {+ report.warn(`${homeShort(CODEX_CONFIG)} not found`, "Codex has never been configured on this machine");+ } else {+ const hooksOn = toml.features?.plugin_hooks;+ if (hooksOn === true) report.ok("[features] plugin_hooks = true");+ else report.fail(`[features] plugin_hooks is ${hooksOn === undefined ? "not set" : hooksOn}`, "no plugin hook fires at all", `add plugin_hooks = true under [features] in ${homeShort(CODEX_CONFIG)}`);+ const pluginSection = toml[`plugins."${PLUGIN_ID}"`];+ if (!pluginSection) report.warn(`no [plugins."${PLUGIN_ID}"] section`, "the installer normally writes enabled = true here");+ else if (pluginSection.enabled === false) report.fail(`[plugins."${PLUGIN_ID}"] enabled = false`, "", "set enabled = true");+ else report.ok(`[plugins."${PLUGIN_ID}"] enabled = ${pluginSection.enabled ?? "(unset)"}`);+ const mktSection = toml[`marketplaces.${MARKETPLACE}`];+ if (mktSection?.source) report.info(`[marketplaces.${MARKETPLACE}] ${mktSection.source_type || ""} ${mktSection.source} ref=${mktSection.ref || "?"}`);++ const trusted = [];+ const untrusted = [];+ const disabled = [];+ for (const event of HOOK_EVENTS) {+ const section = toml[`hooks.state."${PLUGIN_ID}:hooks/hooks.json:${event}:0:0"`];+ if (!section) untrusted.push(event);+ else if (section.enabled === false) disabled.push(event);+ else trusted.push(event);+ }+ if (disabled.length) report.fail(`hooks disabled in [hooks.state]: ${disabled.join(", ")}`, "", `remove enabled = false from those [hooks.state] sections in ${homeShort(CODEX_CONFIG)}`);+ if (untrusted.length) report.info(`hooks without a trust record yet: ${untrusted.join(", ")} (Codex records trusted_hash the first time a hook is approved; a changed hooks.json needs re-approval)`);+ if (trusted.length === HOOK_EVENTS.length) report.ok("all four hooks have trust records in config.toml");+ const legacyKeys = Object.keys(toml).filter((k) => k.includes(LEGACY_MARKETPLACE));+ if (legacyKeys.length) report.info(`config.toml still has ${legacyKeys.length} section(s) for the legacy id ${LEGACY_MARKETPLACE} (harmless)`);+ }++ // 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 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));+ if (conn.length) report.warn(`${h.file} exports ${conn.join(", ")}`, "shell exports override ovcli.conf in every session started from that shell", "remove the export or keep ovcli.conf in sync with it");+ else report.info(`${h.file} exports ${h.detail}`);+ }+ if (existsPath(join(homedir(), ".openviking", "codex-memory-plugin", "runtime"))) report.info("~/.openviking/codex-memory-plugin/runtime is a leftover from the pre-marketplace installer (safe to delete)");+ return { listed };+}++function tryJsonText(text) {+ try {+ return JSON.parse(text);+ } catch {+ return null;+ }+}++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) {+ 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");+ 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)");+ }+ }+ 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 modeEnv = process.env.OPENVIKING_CREDENTIAL_SOURCE || process.env.OPENVIKING_CREDENTIALS_SOURCE;+ const modeText = cfg.credentialSource === "ovcli" ? "ovcli.conf only (env and ov.conf ignored)" : cfg.credentialSource === "env" ? "environment variables win" : "fell through to ov.conf / defaults";+ 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");+ }+ 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.source === "workspace" ? " (derived from cwd; changes when the directory moves)" : ""}`);++ 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 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");+ 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();+ let states = [];+ try {+ states = readdirSync(stateDir).filter((n) => n.endsWith(".json") && n !== "recall-compressor-profile.json").map((n) => {+ const path = join(stateDir, n);+ const st = statSync(path);+ return { name: n, mtimeMs: st.mtimeMs, data: tryJson(path) };+ }).sort((a, b) => b.mtimeMs - a.mtimeMs);+ } catch {+ report.info(`no session state dir at ${homeShort(stateDir)} yet — no Codex hook has run (or OPENVIKING_CODEX_STATE_DIR points elsewhere)`);+ }+ if (states.length) {+ const newest = states[0];+ const d = newest.data || {};+ report.info(`${states.length} session state file(s) in ${homeShort(stateDir)}; newest ${fmtAge(newest.mtimeMs)}: ${d.ovSessionId || "(committed)"} captured ${d.capturedTurnCount ?? "?"} turns`);+ if (states.length > 3 && states.every((s) => (s.data?.capturedTurnCount ?? 0) === 0)) report.warn("no session has ever captured a turn", "the Stop hook runs but never appends messages", "check the Connection section; enable OPENVIKING_DEBUG=1 and read the hook log");+ const idleTtl = Number(process.env.OPENVIKING_CODEX_IDLE_TTL_MS) || 30 * 60 * 1000;+ const orphans = states.filter((s) => s.data?.ovSessionId && Date.now() - (s.data.lastUpdatedAt || s.mtimeMs) > idleTtl);+ if (orphans.length > 10) report.warn(`${orphans.length} idle sessions still uncommitted`, "the idle sweep at SessionStart commits them; a growing pile usually means commits are failing", "check the Connection section, then start a new Codex session to trigger the sweep");+ else if (orphans.length) report.info(`${orphans.length} idle session(s) waiting for the SessionStart sweep`);+ }+ const profile = tryJson(join(stateDir, "recall-compressor-profile.json"));+ if (profile?.profile) {+ const p = profile.profile;+ if (p.enabled === false && p.source === "runtime_failed") report.info(`local recall compressor disabled after a runtime failure (${p.failedModel || "?"}); re-detected at the next SessionStart`);+ else report.info(`recall compressor: ${p.enabled ? `${p.model || "?"} (${p.source || "?"})` : `off (${p.source || "?"})`}`);+ }++ 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 Codex turn ran, hooks are not being spawned (plugin_hooks, trust, node)" : ""}`);+ } else {+ report.info(`hook log ${homeShort(log.path)} — ${fmtBytes(log.size)}, last write ${fmtAge(log.mtimeMs)}, hooks seen: ${log.hooks.join(", ") || "(none)"}`);+ if (log.proxyStart?.data?.mcpUrl) {+ const want = `${cfg.baseUrl.replace(/\/+$/, "")}/mcp`;+ if (log.proxyStart.data.mcpUrl !== want) report.warn(`MCP proxy last started against ${log.proxyStart.data.mcpUrl} (${log.proxyStart.ts})`, `current config resolves to ${want}; a running proxy only re-reads credentials after a 401/403, never a new url`, "if that proxy is still running, restart Codex; if the line is old, ignore it");+ else report.info(`MCP proxy last started against ${log.proxyStart.data.mcpUrl} (${log.proxyStart.ts})`);+ }+ 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"));+ }+ const ccLog = join(homedir(), ".openviking", "logs", "cc-hooks.log");+ if (existsPath(ccLog) && !log.exists) report.info("~/.openviking/logs/cc-hooks.log belongs to the Claude Code plugin, not Codex");+ if (connection?.summary?.reachable === false) report.info("state files are kept when commits fail, so they replay once the server is back");+}++// ---------------------------------------------------------------------------++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 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,+ },+ server: connection?.summary || null,+ serverHealth,+ ...report.toJSON(),+ }, null, 2));+ } else {+ console.log(report.render());+ }+ process.exitCode = report.exitCode();+}++main().catch((err) => {+ console.error("ov-memory-doctor failed:", err?.stack || err?.message || err);+ process.exit(2);+});diff --git a/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs b/examples/codex-memory-plugin/scripts/shared/doctor-core.mjsnew file mode 100644index 000000000..035e96b05--- /dev/null+++ b/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs@@ -0,0 +1,901 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+/**+ * Harness-agnostic building blocks for the memory plugin doctor scripts.+ *+ * Each harness ships a thin `ov-memory-doctor.mjs` entrypoint that knows its+ * own install layout (where the plugin is registered, which hooks file, which+ * 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.+ *+ * Nothing here reads harness config; callers pass a resolved connection+ * `{ baseUrl, apiKey, account, user, peerId, userAgent }`.+ */++import { execFileSync } from "node:child_process";+import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";++// ---------------------------------------------------------------------------+// Formatting helpers+// ---------------------------------------------------------------------------++export function homeShort(path) {+ const home = homedir();+ if (!path) return path;+ return path.startsWith(home) ? `~${path.slice(home.length)}` : path;+}++export function fmtAge(ts) {+ if (!ts) return "never";+ const sec = Math.floor((Date.now() - ts) / 1000);+ if (sec < 0) return "just now";+ if (sec < 60) return `${sec}s ago`;+ if (sec < 3600) return `${Math.floor(sec / 60)}m ago`;+ if (sec < 86400) return `${Math.floor(sec / 3600)}h ago`;+ return `${Math.floor(sec / 86400)}d ago`;+}++export function fmtBytes(n) {+ if (n == null) return "?";+ if (n < 1024) return `${n} B`;+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;+ return `${(n / 1024 / 1024).toFixed(1)} MB`;+}++function str(value, fallback = "") {+ return typeof value === "string" && value.trim() ? value.trim() : fallback;+}++// ---------------------------------------------------------------------------+// Report+// ---------------------------------------------------------------------------++const LEVEL_ORDER = { fail: 0, warn: 1, info: 2, ok: 3 };+const LEVEL_MARK = { ok: "✓", info: "·", warn: "⚠", fail: "✗" };+const LEVEL_COLOR = { ok: "32", info: "2", warn: "33", fail: "31" };++export function createReport({ color = false } = {}) {+ const sections = [];+ let current = null;++ function paint(code, text) {+ return color ? `\x1b[${code}m${text}\x1b[0m` : text;+ }++ function section(title) {+ current = { title, findings: [] };+ sections.push(current);+ return current;+ }++ function add(level, title, detail, fix) {+ if (!current) section("General");+ const finding = { level, title };+ if (detail) finding.detail = String(detail);+ if (fix) finding.fix = String(fix);+ current.findings.push(finding);+ return finding;+ }++ const report = {+ sections,+ section,+ add,+ ok: (title, detail) => add("ok", title, detail),+ info: (title, detail) => add("info", title, detail),+ warn: (title, detail, fix) => add("warn", title, detail, fix),+ fail: (title, detail, fix) => add("fail", title, detail, fix),+ problems() {+ return sections.flatMap((s) => s.findings.filter((f) => f.level === "fail" || f.level === "warn"));+ },+ exitCode() {+ return sections.some((s) => s.findings.some((f) => f.level === "fail")) ? 1 : 0;+ },+ render() {+ const lines = [];+ for (const s of sections) {+ lines.push(paint("1", `== ${s.title} ==`));+ for (const f of s.findings) {+ lines.push(` ${paint(LEVEL_COLOR[f.level], LEVEL_MARK[f.level])} ${f.title}`);+ if (f.detail) for (const l of String(f.detail).split("\n")) lines.push(` ${l}`);+ if (f.fix && (f.level === "warn" || f.level === "fail")) lines.push(` ${paint("36", "fix:")} ${f.fix}`);+ }+ lines.push("");+ }+ const problems = report.problems().sort((a, b) => LEVEL_ORDER[a.level] - LEVEL_ORDER[b.level]);+ lines.push(paint("1", "== Summary =="));+ if (!problems.length) {+ lines.push(` ${paint("32", "✓")} no problems found`);+ } else {+ const fails = problems.filter((p) => p.level === "fail").length;+ lines.push(` ${fails} failure(s), ${problems.length - fails} warning(s)`);+ for (const p of problems) {+ lines.push(` ${paint(LEVEL_COLOR[p.level], LEVEL_MARK[p.level])} ${p.title}${p.fix ? ` → ${p.fix}` : ""}`);+ }+ }+ return lines.join("\n");+ },+ toJSON() {+ return { sections };+ },+ };+ return report;+}++// ---------------------------------------------------------------------------+// API key display+// ---------------------------------------------------------------------------++export function decodeBase64Url(segment) {+ if (typeof segment !== "string" || !segment || /[^A-Za-z0-9_-]/.test(segment)) return null;+ try {+ const padded = segment + "=".repeat((4 - (segment.length % 4)) % 4);+ const text = Buffer.from(padded, "base64url").toString("utf-8");+ // Reject decoded text that is not printable — a random string that happens+ // to be valid base64 decodes to binary garbage.+ if (!text || /[^\x20-\x7e]/.test(text)) return null;+ return text;+ } catch {+ return null;+ }+}++function headTail(value, keep = 4) {+ if (!value) return "";+ if (value.length <= keep * 2 + 2) return "*".repeat(Math.max(4, value.length));+ return `${value.slice(0, keep)}…${value.slice(-keep)}`;+}++/**+ * Describe an API key for display without revealing it.+ *+ * three-segment key → account=<decoded> user=<decoded> secret=abcd…wxyz+ * single-segment key → abcd…wxyz (64 chars, legacy format)+ *+ * The three-segment format is base64url(account).base64url(user).base64url(secret);+ * the first two segments carry no secret and are decoded so the operator can see+ * which identity the key claims. Also reports shape problems that commonly come+ * from copy/paste mistakes.+ */+export function describeApiKey(rawKey) {+ const info = { present: false, format: "none", display: "(none)", account: "", user: "", length: 0, problems: [] };+ if (typeof rawKey !== "string" || !rawKey) return info;++ info.present = true;+ info.length = rawKey.length;+ if (rawKey !== rawKey.trim()) info.problems.push("has leading/trailing whitespace");+ if (/[\r\n]/.test(rawKey)) info.problems.push("contains a line break");+ if (/^["']|["']$/.test(rawKey.trim())) info.problems.push("wrapped in quotes");+ if (/^bearer\s+/i.test(rawKey.trim())) info.problems.push("starts with 'Bearer ' — store only the key itself");++ const key = rawKey.trim().replace(/^bearer\s+/i, "").replace(/^["']|["']$/g, "");+ const parts = key.split(".");+ if (parts.length === 3) {+ info.format = "v2";+ const account = decodeBase64Url(parts[0]);+ const user = decodeBase64Url(parts[1]);+ info.account = account || "";+ info.user = user || "";+ const accountText = account ?? `${headTail(parts[0])} (not base64url)`;+ const userText = user ?? `${headTail(parts[1])} (not base64url)`;+ if (account === null || user === null) info.problems.push("account/user segment is not decodable base64url — key may be truncated or mangled");+ if (!parts[2]) info.problems.push("secret segment is empty");+ info.display = `account=${accountText} user=${userText} secret=${headTail(parts[2])}`;+ } else {+ info.format = "legacy";+ if (parts.length !== 1) info.problems.push(`unexpected shape: ${parts.length} dot-separated segments (expected 1 or 3)`);+ info.display = `${headTail(key)} (${key.length} chars, ${parts.length === 1 ? "legacy single-segment" : "unrecognised"} format)`;+ }+ return info;+}++/** Mask any secret-looking env value for display. */+export function maskSecret(value) {+ return headTail(String(value ?? ""), 4);+}++// ---------------------------------------------------------------------------+// Base URL lint+// ---------------------------------------------------------------------------++export function lintBaseUrl(url) {+ const problems = [];+ const value = String(url ?? "");+ if (!value.trim()) {+ problems.push({ level: "fail", message: "base URL is empty", fix: "set url in ovcli.conf or OPENVIKING_URL" });+ return problems;+ }+ if (value !== value.trim() || /\s/.test(value)) {+ problems.push({ level: "fail", message: "base URL contains whitespace", fix: "remove stray spaces/newlines around the url value" });+ }+ if (!/^https?:\/\//i.test(value.trim())) {+ problems.push({ level: "fail", message: "base URL has no http:// or https:// scheme — fetch() rejects it as 'Failed to parse URL'", fix: "prefix the url with http:// or https://" });+ return problems;+ }+ let parsed;+ try {+ parsed = new URL(value.trim());+ } catch {+ problems.push({ level: "fail", message: "base URL does not parse", fix: "check the url value for typos" });+ return problems;+ }+ const path = parsed.pathname.replace(/\/+$/, "");+ if (/\/api(\/v1)?$/i.test(path)) {+ problems.push({ level: "fail", message: `base URL ends with ${path} — every request becomes ${path}/api/v1/... and 404s`, fix: "drop the /api/v1 suffix; the plugin appends API paths itself" });+ }+ if (/\/mcp$/i.test(path)) {+ problems.push({ level: "fail", message: "base URL ends with /mcp — the plugin appends /mcp itself", fix: "use the server root URL, not the MCP endpoint" });+ }+ if (parsed.hostname === "0.0.0.0") {+ problems.push({ level: "warn", message: "host 0.0.0.0 is a bind address, not a destination", fix: "use 127.0.0.1 or the real hostname" });+ }+ if (parsed.search || parsed.hash) {+ problems.push({ level: "warn", message: "base URL carries a query string or fragment", fix: "remove everything after the path" });+ }+ return problems;+}++export function isLoopbackUrl(url) {+ try {+ const host = new URL(url).hostname;+ return host === "127.0.0.1" || host === "localhost" || host === "::1" || host === "[::1]";+ } catch {+ return false;+ }+}++// ---------------------------------------------------------------------------+// Files and environment+// ---------------------------------------------------------------------------++export function inspectJsonFile(path) {+ const out = { path, exists: false, ok: false, error: "", data: null, mode: "", size: 0, mtimeMs: 0 };+ if (!path) return out;+ let st;+ try {+ st = statSync(path);+ } catch {+ return out;+ }+ out.exists = true;+ out.size = st.size;+ out.mtimeMs = st.mtimeMs;+ out.mode = (st.mode & 0o777).toString(8);+ let raw;+ try {+ raw = readFileSync(path, "utf-8");+ } catch (err) {+ out.error = `unreadable: ${err?.message || err}`;+ return out;+ }+ try {+ out.data = JSON.parse(raw);+ out.ok = out.data !== null && typeof out.data === "object";+ if (!out.ok) out.error = "top level is not a JSON object";+ } catch (err) {+ out.error = `invalid JSON: ${err?.message || err}`;+ }+ return out;+}++const KNOWN_OVCLI_KEYS = new Set([+ "url", "api_key", "root_api_key", "account", "user", "account_id", "user_id",+ "actor_peer_id", "peer_id", "agent_id", "timeout", "output", "echo_command",+ "extra_headers", "gateway_token", "auth_mode", "ldap_username", "ldap_password", "plugin",+]);++/** Keys in ovcli.conf that neither the CLI nor the plugins read — usually typos. */+export function unknownOvcliKeys(data) {+ if (!data || typeof data !== "object") return [];+ return Object.keys(data).filter((k) => !KNOWN_OVCLI_KEYS.has(k));+}++const SECRET_ENV = /KEY|TOKEN|SECRET|PASSWORD/i;++export function collectEnv(env = process.env) {+ const openviking = [];+ for (const name of Object.keys(env).sort()) {+ if (!name.startsWith("OPENVIKING_")) continue;+ const value = env[name] ?? "";+ openviking.push({ name, value: SECRET_ENV.test(name) ? maskSecret(value) : value });+ }+ const proxy = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy"]+ .filter((name) => str(env[name]))+ .map((name) => ({ name, value: env[name] }));+ const node = ["NODE_EXTRA_CA_CERTS", "NODE_TLS_REJECT_UNAUTHORIZED", "NODE_USE_ENV_PROXY", "NODE_OPTIONS"]+ .filter((name) => str(env[name]))+ .map((name) => ({ name, value: env[name] }));+ return { openviking, proxy, node };+}++/** Legacy rc-file wrapper blocks written by pre-stdio-proxy installers. */+export function scanRcFiles(markers, home = homedir()) {+ const hits = [];+ for (const file of [".zshrc", ".bashrc", ".zprofile", ".bash_profile", ".profile"]) {+ const path = `${home}/${file}`;+ let text;+ try {+ text = readFileSync(path, "utf-8");+ } catch {+ continue;+ }+ for (const marker of markers) {+ if (text.includes(marker)) hits.push({ file: homeShort(path), kind: "block", detail: marker });+ }+ const exported = [...new Set([...text.matchAll(/^\s*export\s+(OPENVIKING_[A-Z0-9_]+)=/gm)].map((m) => m[1]))];+ if (exported.length) hits.push({ file: homeShort(path), kind: "export", detail: exported.join(", "), vars: exported });+ }+ return hits;+}++// ---------------------------------------------------------------------------+// Commands+// ---------------------------------------------------------------------------++export function runCommand(command, args = [], { timeoutMs = 10000, env = process.env } = {}) {+ try {+ const stdout = execFileSync(command, args, {+ encoding: "utf-8",+ timeout: timeoutMs,+ env,+ stdio: ["ignore", "pipe", "pipe"],+ });+ return { ok: true, stdout: String(stdout).trim(), stderr: "" };+ } catch (err) {+ return {+ ok: false,+ stdout: String(err?.stdout ?? "").trim(),+ stderr: String(err?.stderr ?? "").trim(),+ error: err?.code === "ENOENT" ? "not found" : (err?.killed ? `timed out after ${timeoutMs}ms` : (err?.message || String(err))),+ };+ }+}++export function whichCommand(name) {+ const result = runCommand(process.platform === "win32" ? "where" : "which", [name], { timeoutMs: 5000 });+ return result.ok ? result.stdout.split("\n")[0] : "";+}++export function parseNodeMajor(version) {+ const m = /^v?(\d+)/.exec(String(version || ""));+ return m ? Number(m[1]) : NaN;+}++// ---------------------------------------------------------------------------+// HTTP probes+// ---------------------------------------------------------------------------++export function classifyFetchError(err) {+ const cause = err?.cause || err;+ const code = cause?.code || "";+ const message = String(cause?.message || err?.message || err || "");+ if (err?.name === "AbortError" || /aborted/i.test(message)) {+ return { kind: "timeout", hint: "no response within the timeout — wrong host/port, firewall, or a very slow server" };+ }+ if (code === "ECONNREFUSED") return { kind: "refused", hint: "connection refused — nothing is listening on that host:port (server down or wrong port)" };+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") return { kind: "dns", hint: "hostname does not resolve — typo in the url, or DNS/VPN not available" };+ if (code === "ECONNRESET" || code === "EPIPE") return { kind: "reset", hint: "connection reset — a proxy or TLS terminator closed the connection" };+ if (/certificate|CERT_|SELF_SIGNED|UNABLE_TO_VERIFY|ssl|tls/i.test(`${code} ${message}`)) {+ return { kind: "tls", hint: "TLS verification failed — private CA or self-signed cert; Node ignores the OS keychain, set NODE_EXTRA_CA_CERTS for the harness process" };+ }+ if (/Failed to parse URL|Invalid URL/i.test(message)) return { kind: "url", hint: "the url does not parse — check scheme and host" };+ if (/wrong version number|EPROTO/i.test(`${code} ${message}`)) return { kind: "tls", hint: "protocol mismatch — https:// against a plain-HTTP port (or vice versa)" };+ return { kind: "other", hint: message };+}++export async function httpProbe({ url, method = "GET", headers = {}, body, timeoutMs = 5000 }) {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs);+ const t0 = Date.now();+ const out = { url, method, ok: false, status: 0, latencyMs: 0, text: "", json: null, headers: {}, error: "", errorKind: "", errorHint: "" };+ try {+ const res = await fetch(url, { method, headers, body, signal: controller.signal, redirect: "manual" });+ out.status = res.status;+ out.ok = res.ok;+ out.latencyMs = Date.now() - t0;+ for (const [k, v] of res.headers.entries()) out.headers[k.toLowerCase()] = v;+ const text = await res.text().catch(() => "");+ out.text = text.length > 4000 ? `${text.slice(0, 4000)}…` : text;+ const contentType = out.headers["content-type"] || "";+ if (contentType.includes("text/event-stream")) {+ // Streamable HTTP frames: take the first data: line.+ const line = text.split("\n").find((l) => l.startsWith("data:"));+ if (line) {+ try { out.json = JSON.parse(line.slice(5).trim()); } catch { /* keep text */ }+ }+ } else {+ try { out.json = JSON.parse(text); } catch { /* not JSON */ }+ }+ } catch (err) {+ out.latencyMs = Date.now() - t0;+ const cls = classifyFetchError(err);+ out.error = err?.cause?.message || err?.message || String(err);+ out.errorKind = cls.kind;+ out.errorHint = cls.hint;+ } finally {+ clearTimeout(timer);+ }+ return out;+}++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;+}++export function serverErrorMessage(probe) {+ const body = probe?.json;+ if (!body) return probe?.text ? probe.text.replace(/\s+/g, " ").slice(0, 200) : "";+ return body?.error?.message || body?.error?.code || body?.message || body?.detail || "";+}++/**+ * Run the standard probe ladder against an OpenViking server.+ *+ * health GET /health without credentials — reachability, version, auth_mode+ * healthAuth GET /health with credentials — identity echo (account/user/role)+ * systemStatus GET /api/v1/system/status — first authenticated call the hooks make; real 401/403+ * fsLs GET /api/v1/fs/ls?uri=viking://~/memories — tenant-data authorization + resolved user space+ * mcp POST /mcp tools/list — what the MCP proxy forwards+ */+export async function probeOpenViking(conn, { timeoutMs = 5000, mcp = true } = {}) {+ const base = String(conn.baseUrl || "").replace(/\/+$/, "");+ const out = {};+ out.health = await httpProbe({ url: `${base}/health`, timeoutMs, headers: conn.userAgent ? { "User-Agent": conn.userAgent } : {} });+ if (out.health.error && out.health.errorKind !== "other") {+ // Hard network failure: the rest of the ladder would fail identically.+ return out;+ }+ if (conn.apiKey || conn.account || conn.user) {+ out.healthAuth = await httpProbe({ url: `${base}/health`, timeoutMs, headers: authHeaders(conn) });+ }+ out.systemStatus = await httpProbe({ url: `${base}/api/v1/system/status`, timeoutMs, headers: authHeaders(conn) });+ out.fsLs = await httpProbe({+ url: `${base}/api/v1/fs/ls?uri=${encodeURIComponent("viking://~/memories")}&output=original`,+ timeoutMs,+ headers: authHeaders(conn),+ });+ if (mcp) {+ out.mcp = await httpProbe({+ url: `${base}/mcp`,+ method: "POST",+ timeoutMs: Math.max(timeoutMs, 8000),+ headers: { ...authHeaders(conn), Accept: "application/json, text/event-stream", "MCP-Protocol-Version": "2025-06-18" },+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }),+ });+ }+ return out;+}++/**+ * Turn probe results into findings. `keyInfo` is describeApiKey(conn.apiKey).+ * Returns { authMode, version, identity } for callers that want to cross-check.+ */+export function assessProbes(report, probes, conn, keyInfo) {+ const summary = { authMode: "", version: "", identity: null, reachable: false, authOk: false };+ const health = probes.health;+ if (!health) return summary;++ if (health.error) {+ report.fail(`server unreachable: ${conn.baseUrl}`, `${health.errorKind || "error"}: ${health.error}\n${health.errorHint}`,+ "check that the server is running and the url/port are right; compare with `curl -sS <url>/health`");+ return summary;+ }+ summary.reachable = true;+ if (health.status === 404) {+ report.fail(`GET /health → 404 at ${conn.baseUrl}`, "the url points at a web server, but not at an OpenViking API root",+ "check for a missing path prefix (OpenViking Cloud needs /openviking) or a reverse proxy that does not forward /health");+ return summary;+ }+ if (health.status >= 300 && health.status < 400) {+ report.fail(`GET /health → ${health.status} redirect`, `location: ${health.headers.location || "?"}`,+ "the url is being redirected (http→https, or an SSO/login gateway); use the final url");+ return summary;+ }+ if (health.status === 503 && health.json?.status === "pending_initialization") {+ const fixes = Array.isArray(health.json.fix) ? health.json.fix.map((f) => `- ${f}`).join("\n") : "";+ report.fail("the OpenViking docker container is up but has no ov.conf — every request answers 503 until it does",+ `${health.json.error || ""}${health.json.config_file ? ` (expected at ${health.json.config_file} inside the container)` : ""}${fixes ? `\n${fixes}` : ""}`,+ "mount ~/.openviking (holding ov.conf) at /app/.openviking, or run `docker exec -it openviking openviking-server init`");+ return summary;+ }+ if (!health.ok || !health.json) {+ report.fail(`GET /health → ${health.status}`, serverErrorMessage(health) || "(non-JSON body)",+ "the server answered but not like OpenViking — verify the url reaches the OpenViking API, not a proxy error page");+ return summary;+ }+ summary.authMode = String(health.json.auth_mode || "");+ summary.version = String(health.json.version || "");+ report.ok(`server reachable — ${health.latencyMs}ms, version ${summary.version || "?"}, auth_mode=${summary.authMode || "?"}`);+ if (health.latencyMs > 1000) {+ report.warn(`/health took ${health.latencyMs}ms`, "the statusline probe has a 1s budget and will flap between 'slow' and 'offline'",+ "check network latency to the server; raise OPENVIKING_TIMEOUT_MS if hooks time out");+ }++ const identity = probes.healthAuth?.json;+ if (identity && identity.role) {+ summary.identity = { account: identity.account_id, user: identity.user_id, role: identity.role };+ summary.authOk = true;+ report.ok(`credentials accepted — account=${identity.account_id} user=${identity.user_id} role=${identity.role}`);+ if (identity.role === "root") {+ report.warn("using the ROOT api key", "root keys are rejected on tenant-data APIs and /mcp in api_key mode (403 'ROOT API keys cannot access tenant-scoped data APIs')",+ "create a user key (POST /api/v1/admin/accounts/<account>/users with the root key) and put that in ovcli.conf");+ }+ if (summary.authMode === "api_key" && keyInfo?.format === "v2") {+ if (keyInfo.account && keyInfo.account !== identity.account_id) {+ report.warn(`key claims account=${keyInfo.account} but server resolved account=${identity.account_id}`);+ }+ }+ if (summary.authMode === "api_key" && (conn.account || conn.user)) {+ const mismatch = (conn.account && conn.account !== identity.account_id) || (conn.user && conn.user !== identity.user_id);+ if (mismatch) {+ report.warn(`configured account/user (${conn.account || "-"}/${conn.user || "-"}) differ from the key's identity (${identity.account_id}/${identity.user_id})`,+ "in api_key mode the server ignores X-OpenViking-Account/User headers; the key decides where data lands",+ "remove account/user from the config, or use a key issued for that account/user");+ } else {+ report.info("account/user in config are redundant in api_key mode (identity comes from the key)");+ }+ }+ } else if (summary.authMode === "dev") {+ summary.authOk = true;+ report.info("server runs in dev auth mode — any key is accepted; identity comes from X-OpenViking-Account/User headers (default 'default')");+ if (identity?.account_id) summary.identity = { account: identity.account_id, user: identity.user_id, role: identity.role };+ } else if (conn.apiKey) {+ report.fail("api key rejected", `/health answered 200 but returned no identity for the key (${keyInfo?.display || "?"}) — the key is invalid, revoked, or belongs to another deployment`,+ "check the key in ovcli.conf / OPENVIKING_API_KEY against the one issued by the server admin");+ } else if (summary.authMode === "api_key") {+ report.fail("no api key configured but the server requires one (auth_mode=api_key)", "",+ "set api_key in ~/.openviking/ovcli.conf or OPENVIKING_API_KEY");+ } else if (summary.authMode === "trusted") {+ if (!conn.account || !conn.user) {+ report.fail("server is in trusted mode and needs account + user", "requests without X-OpenViking-Account/User are rejected with HTTP 400",+ "set account and user in ovcli.conf (or OPENVIKING_ACCOUNT / OPENVIKING_USER)");+ } else {+ summary.authOk = true;+ report.ok(`trusted mode — identity from headers account=${conn.account} user=${conn.user}`);+ }+ }++ const status = probes.systemStatus;+ if (status) {+ if (status.ok) {+ const user = status.json?.result?.user;+ report.ok(`GET /api/v1/system/status → 200${user ? ` (user space: ${user})` : ""}`);+ } else if (status.error) {+ report.fail("GET /api/v1/system/status failed", `${status.errorKind}: ${status.error}`);+ } else {+ const msg = serverErrorMessage(status);+ const level = status.status === 401 || status.status === 403 ? "fail" : "warn";+ report[level](`GET /api/v1/system/status → ${status.status}`, msg,+ status.status === 401 ? "the server rejected the credentials — this is what every hook hits after the /health gate passes"+ : status.status === 403 ? "the key is valid but not allowed here — wrong role or root key" : "");+ }+ }++ const fs = probes.fsLs;+ if (fs) {+ if (fs.ok) {+ const first = Array.isArray(fs.json?.result) ? fs.json.result.find((e) => e?.uri) : null;+ const space = first?.uri ? String(first.uri).replace(/\/memories\/.*$/, "/memories") : "";+ report.ok(`GET /api/v1/fs/ls viking://~/memories → 200${space ? ` (${space})` : ""}`);+ } else if (!fs.error) {+ const msg = serverErrorMessage(fs);+ if (fs.status === 403 && /ROOT/i.test(msg)) {+ report.fail("tenant data API rejects this key (root key)", msg, "use a user/admin key, not server.root_api_key");+ } else if (fs.status === 400) {+ report.warn(`GET /api/v1/fs/ls viking://~/memories → 400`, msg,+ /Trusted mode/i.test(msg) ? "set account/user for trusted mode" : "the server may be too old for the viking://~ home alias — upgrade the server");+ } else if (fs.status === 404) {+ report.info("viking://~/memories does not exist yet (nothing captured for this user so far)");+ } else if (fs.status !== 401) {+ report.warn(`GET /api/v1/fs/ls viking://~/memories → ${fs.status}`, msg);+ }+ }+ }++ const mcp = probes.mcp;+ if (mcp) {+ if (mcp.ok && mcp.json?.result?.tools) {+ report.ok(`POST /mcp tools/list → ${mcp.json.result.tools.length} tools`);+ } else if (mcp.error) {+ report.fail("POST /mcp failed", `${mcp.errorKind}: ${mcp.error}`);+ } else {+ const msg = serverErrorMessage(mcp) || mcp.text.replace(/\s+/g, " ").slice(0, 160);+ const hints = {+ 401: "credentials rejected on /mcp",+ 403: "key valid but not allowed on /mcp (root key in api_key mode)",+ 404: "no MCP endpoint at <url>/mcp — missing path prefix, old server, or a reverse proxy that does not forward /mcp",+ 406: "server did not accept the Accept header — something between client and server rewrites headers",+ 502: "reverse proxy cannot reach the upstream",+ 504: "reverse proxy timed out (SSE needs proxy_buffering off)",+ };+ report.fail(`POST /mcp tools/list → ${mcp.status}`, msg, hints[mcp.status] || "");+ }+ }+ return summary;+}++// ---------------------------------------------------------------------------+// State and logs+// ---------------------------------------------------------------------------++export function readStateFiles(stateDir, names) {+ const out = {};+ for (const name of names) {+ const path = `${stateDir}/${name}`;+ const entry = { path, exists: false, ageMs: null, data: null, error: "" };+ try {+ const st = statSync(path);+ entry.exists = true;+ entry.mtimeMs = st.mtimeMs;+ const data = JSON.parse(readFileSync(path, "utf-8"));+ entry.data = data;+ entry.ageMs = typeof data?.ts === "number" ? Date.now() - data.ts : Date.now() - st.mtimeMs;+ } catch (err) {+ if (entry.exists) entry.error = err?.message || String(err);+ }+ out[name] = entry;+ }+ return out;+}++export function countDirEntries(dir, filter = () => true) {+ try {+ return readdirSync(dir).filter(filter).length;+ } catch {+ return null;+ }+}++export function fileInfo(path) {+ try {+ const st = statSync(path);+ return { exists: true, size: st.size, mtimeMs: st.mtimeMs };+ } catch {+ return { exists: false, size: 0, mtimeMs: 0 };+ }+}++/**+ * Scan a JSONL hook log. Returns the last `maxErrors` error entries, the last+ * mcp-proxy start record, and which hooks have written anything.+ */+export function scanDebugLog(path, { maxErrors = 5, maxBytes = 512 * 1024 } = {}) {+ const out = { path, exists: false, size: 0, mtimeMs: 0, lines: 0, errors: [], proxyStart: null, hooks: [] };+ const info = fileInfo(path);+ if (!info.exists) return out;+ Object.assign(out, { exists: true, size: info.size, mtimeMs: info.mtimeMs });+ let text;+ try {+ text = readFileSync(path, "utf-8");+ } catch {+ return out;+ }+ if (text.length > maxBytes) text = text.slice(-maxBytes);+ const hooks = new Set();+ const errors = [];+ for (const line of text.split("\n")) {+ if (!line.trim()) continue;+ out.lines += 1;+ let entry;+ try {+ entry = JSON.parse(line);+ } catch {+ continue;+ }+ if (entry.hook) hooks.add(entry.hook);+ if (entry.hook === "mcp-proxy" && entry.stage === "start") out.proxyStart = entry;+ if (entry.error) {+ errors.push({ ts: entry.ts, hook: entry.hook, stage: entry.stage, message: entry.error?.message || String(entry.error) });+ }+ }+ // Only errors from the last day of logging are "recent"; older ones are+ // history that predates whatever the user is debugging now.+ const cutoff = out.mtimeMs - 24 * 60 * 60 * 1000;+ out.errors = errors.slice(-maxErrors);+ out.recentErrors = errors.filter((e) => Date.parse(e.ts || "") >= cutoff).slice(-maxErrors);+ out.hooks = [...hooks].sort();+ return out;+}++export function existsPath(path) {+ return Boolean(path) && existsSync(path);+}++// ---------------------------------------------------------------------------+// Server health+//+// `GET /ready` is the server's own verdict on its subsystems and works+// against any deployment. The port and ov.conf checks only apply when the+// server runs on this machine (loopback url). Everything else server-side —+// config validation, live embedding probe, native engine, disk — is+// `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" };+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",+ vectordb: "the vector index is unhealthy — check <storage.workspace>/vectordb and the server log; stop duplicate servers on the same workspace",+ agfs: "the content filesystem failed — check <storage.workspace>/viking, free disk space and the server log",+ api_key_manager: "the api key store failed to load — check <storage.workspace>/viking/_system and the server log",+ ollama: "start Ollama (or fix its host/port in ov.conf) — the server cannot reach it",+};++function isObject(v) {+ return Boolean(v) && typeof v === "object" && !Array.isArray(v);+}++/**+ * ov.conf keys that only the plugins read. The server validates its config+ * strictly and refuses to start on them, which shows up as "the server is+ * gone since I edited ov.conf". Returns [{ level, message, detail, fix }].+ */+export function lintServerConf(data) {+ const out = [];+ if (!isObject(data)) return out;+ for (const [key, dest] of Object.entries(PLUGIN_ONLY_OV_CONF_KEYS)) {+ if (!(key in data)) continue;+ out.push({+ level: "warn",+ message: `ov.conf has a top-level '${key}' block, which the server rejects at startup ("Unknown config field '${key}'")`,+ detail: "the plugin reads it, openviking-server does not; a server that is already running is unaffected until its next restart",+ fix: `move those settings to ${dest} (or OPENVIKING_* env) and delete the block; if this ov.conf never starts a server, ignore`,+ });+ }+ if (isObject(data.server) && "url" in data.server) {+ out.push({+ level: "warn",+ message: "ov.conf server.url is rejected by the server at startup (\"Extra inputs are not permitted\")",+ detail: "only the plugin and the CLI read server.url; the server validates its section strictly",+ fix: "put the url in ovcli.conf (url) and remove server.url; if this ov.conf never starts a server, ignore",+ });+ }+ return out;+}++/** Who listens on a TCP port (lsof on macOS/Linux, ss on Linux). */+export function findPortListener(port) {+ const out = { tool: "", pid: null, command: "", error: "" };+ if (process.platform === "win32") {+ out.error = "not supported on Windows";+ return out;+ }+ if (whichCommand("lsof")) {+ out.tool = "lsof";+ const r = runCommand("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-F", "pc"], { timeoutMs: 8000 });+ for (const line of r.stdout.split("\n")) {+ if (line.startsWith("p") && out.pid === null) out.pid = Number(line.slice(1));+ else if (line.startsWith("c") && !out.command) out.command = line.slice(1);+ }+ return out;+ }+ if (whichCommand("ss")) {+ out.tool = "ss";+ const r = runCommand("ss", ["-ltnpH", `sport = :${port}`], { timeoutMs: 8000 });+ const m = r.stdout.match(/users:\(\("([^"]+)",pid=(\d+)/);+ if (m) {+ out.command = m[1];+ out.pid = Number(m[2]);+ } else if (r.stdout.trim()) {+ out.command = "(owner not visible without root)";+ }+ return out;+ }+ out.error = "neither lsof nor ss is available";+ return out;+}++export async function probeReady(baseUrl, { timeoutMs = 15000 } = {}) {+ const base = String(baseUrl || "").replace(/\/+$/, "");+ return httpProbe({ url: `${base}/ready`, timeoutMs: Math.max(timeoutMs, 15000) });+}++/** Flatten one `/ready` check (string or {status, checks}) into { ok, text }. */+export function readyCheckState(value) {+ if (isObject(value)) {+ const status = String(value.status ?? "");+ const nested = isObject(value.checks) ? Object.entries(value.checks).map(([k, v]) => [k, readyCheckState(v)]) : [];+ const failed = nested.filter(([, s]) => !s.ok);+ return {+ ok: READY_OK_VALUES.has(status) && failed.length === 0,+ text: failed.length ? `${status} (${failed.map(([k, s]) => `${k}: ${s.text}`).join(", ")})` : status,+ };+ }+ const text = String(value ?? "");+ return { ok: READY_OK_VALUES.has(text), text };+}++/** Turn the `/ready` probe into findings. Returns { ready, checks } (ready null when unknown). */+export function assessReady(report, probe) {+ const out = { ready: null, checks: {} };+ if (!probe) return out;+ if (probe.error) {+ if (probe.errorKind === "timeout") report.warn(`GET /ready timed out after ${probe.latencyMs}ms`, "the readiness check embeds one token with the configured provider (10s cap) — a timeout usually means that provider hangs", "run `openviking-server doctor` in the server's environment to see the provider's reply");+ else report.info(`GET /ready failed: ${probe.error}`);+ return out;+ }+ if (probe.status === 404) {+ report.info("server has no /ready endpoint (older version) — subsystem status unavailable over HTTP", "`openviking-server doctor` in the server's environment covers embedding/VLM/storage");+ return out;+ }+ const json = probe.json;+ if (!isObject(json)) {+ report.info(`GET /ready → ${probe.status} without a JSON body`);+ return out;+ }+ if (probe.status === 503 && json.status === "not_ready" && json.reason === "initializing" && !isObject(json.checks)) {+ out.ready = false;+ report.warn("server is still initializing (503 /ready)", "storage and the embedder are being set up; the first start of a local embedding model downloads it", "wait and rerun; if it never finishes, read the server log");+ return out;+ }+ if (!isObject(json.checks)) {+ report.info(`GET /ready → ${probe.status}: ${JSON.stringify(json).slice(0, 200)}`);+ return out;+ }+ const states = Object.entries(json.checks).map(([k, v]) => [k, readyCheckState(v)]);+ out.checks = Object.fromEntries(states.map(([k, s]) => [k, s.text]));+ const failed = states.filter(([, s]) => !s.ok);+ out.ready = failed.length === 0 && probe.ok;+ const summary = states.map(([k, s]) => `${k} ${s.text}`).join(", ");+ if (out.ready) {+ report.ok(`/ready: ${summary}`);+ } else {+ for (const [key, s] of failed) report.fail(`/ready: ${key} → ${s.text}`, "", READY_FIXES[key] || "see the server log");+ if (!failed.length) report.warn(`/ready → ${probe.status}: ${summary}`, "", "read the server log");+ }+ return out;+}++function urlHostPort(baseUrl) {+ try {+ const u = new URL(baseUrl);+ return { host: u.host, port: Number(u.port || (u.protocol === "https:" ? 443 : 80)) };+ } catch {+ return null;+ }+}++/**+ * The "Server health" section. `health` is the /health probe already taken+ * for the Connection section; `ovConf` is inspectJsonFile(<ov.conf path>).+ */+export async function checkServerHealth(report, { baseUrl, ovConf, health, offline = false, timeoutMs = 5000 } = {}) {+ report.section("Server health");+ const answered = Boolean(health && !health.error && health.ok && isObject(health.json));+ const summary = { local: isLoopbackUrl(baseUrl), reachable: answered, ready: null, listener: null };+ const target = urlHostPort(baseUrl);++ if (!summary.local) {+ report.info(`server at ${target?.host || baseUrl} is not on this machine — only /ready is probed; \`openviking-server doctor\` on the server host covers the rest`);+ } else {+ if (ovConf?.ok) {+ for (const f of lintServerConf(ovConf.data)) report[f.level](f.message, f.detail, f.fix);+ }+ const listener = findPortListener(target.port);+ if (listener.pid) {+ summary.listener = { pid: listener.pid, command: listener.command };+ report.info(`port ${target.port} is served by pid ${listener.pid} (${listener.command})`);+ } else if (listener.error) {+ report.info(`could not determine who listens on port ${target.port} (${listener.error})`);+ } else if (!answered) {+ report.fail(`nothing listens on port ${target.port} — the server is not running`, "",+ "start it: `openviking-server` (first time: `openviking-server init`), or `docker start openviking` for a container install; a startup error is printed right there");+ }+ report.info("provider-level checks (embedding probe, VLM key, native engine, disk): `openviking-server doctor` in the server's own environment");+ }++ if (offline) report.info("skipped /ready (--offline)");+ else if (health?.json?.status === "pending_initialization") report.info("skipped /ready — the container has no config yet");+ else if (!answered) report.info("skipped /ready — the server did not answer /health");+ else summary.ready = assessReady(report, await probeReady(baseUrl, { timeoutMs })).ready;+ return summary;+}diff --git a/examples/codex-memory-plugin/skills/ov-memory-doctor/SKILL.md b/examples/codex-memory-plugin/skills/ov-memory-doctor/SKILL.mdnew file mode 100644index 000000000..68739d55e--- /dev/null+++ b/examples/codex-memory-plugin/skills/ov-memory-doctor/SKILL.md@@ -0,0 +1,202 @@+---+name: ov-memory-doctor+description: >+ Diagnose and fix the OpenViking memory plugin for Codex on this machine: the+ plugin install (marketplace, config.toml enablement, hook trust records, MCP+ server), the client configuration (ovcli.conf / ov.conf / OPENVIKING_* env —+ which one wins, what the API key claims) and the connection to the OpenViking+ server (reachability, 401/403, /mcp). Use whenever memory "isn't working":+ no <openviking-context> block appears, recall is always empty, turns are not+ captured, MCP memory tools are missing or fail, 401/403 errors, right after+ installing/updating the plugin or switching servers/keys, or when the user+ asks for the plugin's status. Trigger phrases include "memory not working",+ "check OpenViking", "plugin status", "记忆没生效", "插件状态", "连不上+ OpenViking", "recall 为空", "401", "0 memories+ extracted". When the server runs on this machine (loopback url) it also+ checks the port, plugin-only keys in ov.conf that stop the server from+ starting, and `GET /ready`; everything else server-side stays with+ `openviking-server doctor`.+---++# OpenViking Memory Doctor (Codex)++Troubleshooting for the OpenViking memory plugin. Three things go+wrong on a user's machine, each silently:++- **Install** — marketplace registration, `[plugins."openviking-memory@openviking"]`+ and `[features] plugin_hooks` in `~/.codex/config.toml`, per-hook trust+ records, the stdio MCP proxy. When these are wrong, hooks never run and+ nothing is logged anywhere.+- **Configuration** — `~/.openviking/ovcli.conf`, `~/.openviking/ov.conf` and+ `OPENVIKING_*` environment variables. A malformed file reads as "no config"+ and the plugin silently falls back to `http://127.0.0.1:1933` with no key; a+ stray env var silently overrides the file.+- **Connection** — `/health` answers 200 even with a bad key, so everything+ can look reachable while every real request 401s.++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+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+`openviking-server doctor`, run in the server's Python environment.++## Step 1 — run the doctor++The script ships inside the plugin. Codex runs hooks from the plugin cache,+so run the doctor from there (newest version directory):++```bash+PLUGIN_DIR=$(ls -d ~/.codex/plugins/cache/openviking/openviking-memory/*/ | sort -V | tail -1)+node "$PLUGIN_DIR/scripts/ov-memory-doctor.mjs"+```++If that directory does not exist, fall back to the marketplace copy reported by+`codex plugin list --json` (`.installed[] | select(.pluginId == "openviking-memory@openviking") | .source.path`),+or to a source checkout's `examples/codex-memory-plugin`.++Options: `--json` (machine-readable), `--offline` (skip network probes),+`--timeout <ms>` (per probe, default 5000), `--no-color`.++The report has six sections — Environment, Plugin install, Configuration,+Connection, Server health, Recent activity — and a Summary listing every ✗/⚠+with a fix.+Read the whole report before acting: one root cause usually shows up in+several sections (a bad key → "api key rejected" + "system/status → 401").++The API key is never printed in full. Three-segment keys are shown as+`account=<a> user=<u> secret=abcd…wxyz` (the first two segments are base64url+identity, decoded so the user can see which account/user the key claims);+legacy keys as `abcd…wxyz (64 chars)`. Keep it that way in anything you show+the user.++## Step 2 — map findings to causes++Work top-down; fix the first ✗ and rerun before chasing the next.++| Doctor finding | Meaning | Action |+|---|---|---|+| `ovcli.conf cannot be parsed` / `no usable config` | Trailing comma/comment; the plugin treats the file as absent and uses the localhost default | Fix the JSON. Fresh machine: create `~/.openviking/ovcli.conf` with `url` + `api_key`, `chmod 600`. |+| `codex plugin list does not show …` | Plugin never installed, or installed under an old id | Re-run the one-line installer (`bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) --harness codex`; add `--dist tos` where GitHub is blocked). |+| `[features] plugin_hooks is not set/false` | Codex never runs plugin hooks | Add `plugin_hooks = true` under `[features]` in `~/.codex/config.toml`, restart Codex. |+| `[plugins."…"] enabled = false` / `installed but disabled` | Plugin switched off in config.toml | Set `enabled = true`, restart Codex. |+| `hooks disabled in [hooks.state]` | A hook was declined at the trust prompt | Remove `enabled = false` from that `[hooks.state."openviking-memory@openviking:hooks/hooks.json:<event>:0:0"]` section; approve the hook again. |+| `hooks without a trust record yet` | Codex has not yet approved those hooks (fresh install or `hooks.json` changed on update) | Start a Codex session and accept the hook prompt; nothing is wrong. |+| `marketplace 'openviking' is not registered` / root missing | Marketplace removed or its clone deleted | Re-run the installer. |+| `plugin.json does not declare skills` | Old plugin copy; `$ov-memory-doctor` and the other bundled skills are not loaded | Update the plugin. |+| `cached plugin X differs from this copy` | The doctor was run from a checkout while Codex runs another version | Rerun from the cache path (Step 1). |+| `node is not on PATH` / node < 18 | Hooks and `.mcp.json` run the bare command `node` | Put node on PATH for the environment that launches Codex. |+| `credential source: env` unexpectedly | A stray `OPENVIKING_*` var forces env mode; `ov config switch` and ovcli.conf edits do nothing | Unset the var (check shell rc files and `~/.openviking/codex-plugin.rc.sh` residue). |+| `OPENVIKING_MEMORY_ENABLED has no effect` | That switch is Claude Code only | `OPENVIKING_AUTO_RECALL=0` / `OPENVIKING_AUTO_CAPTURE=0`, or `codex plugin remove`. |+| `server unreachable` (refused / dns / timeout / tls) | Wrong url/port, server down, DNS/VPN, private CA | Compare with `curl -sS <url>/health`; curl OK + doctor fails ⇒ proxy or CA issue (Step 3). |+| `base URL ends with /api/v1` or `/mcp`, no scheme, `GET /health → 404` | url shape wrong; Cloud needs the `/openviking` prefix | Fix `url` to the API root. |+| `api key rejected` then `system/status → 401 Invalid API Key` | Key invalid/revoked/for another deployment | Get the key re-issued; check nothing overrides ovcli.conf ("← env"). |+| `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 root key was pasted | Use a user/admin key. |+| `plugin auth mode 'trusted' differs from the server's 'api_key'` | account/user set in ovcli.conf ⇒ the plugin sends identity headers, which an `api_key` server ignores; data lands under the key's identity | Remove account/user (or set `OPENVIKING_AUTH_MODE=api_key`), or use a key for that identity. |+| `server is in trusted mode and needs account + user` | Server identity comes from headers | Set `account` and `user` in ovcli.conf. |+| `recall/capture timeout exceeds the hook budget` | Codex kills the hook before the request finishes | Lower `OPENVIKING_RECALL_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 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. |+| `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. |+| `server is still initializing (503 /ready)` | First start downloads a local embedding model, or init is slow | Wait and rerun; if it never finishes, the server log. |+| `docker container is up but has no ov.conf` | Official image started without a config mount (every request 503s) | Mount `~/.openviking` at `/app/.openviking`, or `docker exec -it openviking openviking-server init`. |++More symptoms, exact error strings and log stage names: [reference.md](reference.md).++## Step 3 — targeted checks (only when the report is not conclusive)++Prove hooks run at all: put `OPENVIKING_DEBUG=1` in the environment that+launches Codex, run one turn, then read `~/.openviking/logs/codex-hooks.log`+(JSONL; grep `"error"`). An absent or unchanged log after a full turn means the+hooks were not spawned — a `plugin_hooks` / trust / node problem, not a server+problem. `~/.openviking/logs/cc-hooks.log` belongs to the Claude Code plugin.++Prove the key and identity by hand (`Bearer` is case-sensitive with exactly one+space):++```bash+URL=<url>; KEY=<key>+curl -sS "$URL/health" # reachability, version, auth_mode+curl -sS -H "Authorization: Bearer $KEY" "$URL/health" # 200 without account_id/user_id/role ⇒ key invalid+curl -sS -w '\n%{http_code}\n' -H "Authorization: Bearer $KEY" "$URL/api/v1/system/status" # real 401/403+```++Prove `/mcp` directly (stateless — no initialize needed):++```bash+curl -sS -o /dev/null -w '%{http_code}\n' -X POST "$URL/mcp" \+ -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \+ -H "Authorization: Bearer $KEY" -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'+```++Prove a capture landed: the state file for the session in+`~/.openviking/codex-plugin-state/<session_id>.json` carries `ovSessionId`+(`cx-<session_id>`) and `capturedTurnCount`; `GET $URL/api/v1/sessions/cx-<session_id>`+(or `ov session get cx-<session_id>`) should show `total_message_count ≥` that+count, and `commit_count > 0` proves extraction ran.++Second opinion from the CLI: `ov health` and `ov config validate` read the+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 retargets the plugin too, unless env vars win.++Server side (only meaningful when the server runs on this machine):++```bash+curl -sS "$URL/ready" # agfs / vectordb / api_key_manager / embedding (live probe, ≤10s) / ollama+openviking-server doctor # in the server's own environment: config, native engine, embedding probe, VLM key, disk+lsof -nP -iTCP:1933 -sTCP:LISTEN # who owns the port+docker logs --tail 100 openviking # container deployments+```++`log.output` defaults to stdout, so the server log is the terminal/tmux pane+it runs in, the nohup file, `journalctl -u openviking`, or `docker logs`;+with `"file"` it is `<storage.workspace>/log/openviking.log`. A server that+exits at startup prints the reason right there — running `openviking-server`+in the foreground is the quickest way to see it. It is the user's process:+ask before stopping or restarting it.++## Fixing++- Edit `~/.openviking/ovcli.conf` only with the user's agreement; show the+ change, keep unknown keys, keep mode 0600, never echo the key.+- Edit `~/.codex/config.toml` only for the specific keys named above.+- After changing `url`, installing or updating the plugin: restart Codex.+ Hooks re-read config per invocation, the MCP proxy does not.+- Updates: GitHub/TOS git marketplaces → `codex plugin marketplace upgrade openviking`+ (keeps the pinned ref; the installer re-registers with the current ref);+ local directory marketplaces → re-run the installer.+- Confirm the fix by rerunning the doctor, then by observing an+ `<openviking-context>` block on the next prompt.++## Documentation++- Source and issues: <https://github.com/volcengine/OpenViking> — plugin code lives under `examples/`, the shared installer under `examples/memory-plugin-shared/`.+- Documentation index (LLM-friendly): <https://docs.openviking.ai/llms.txt>; the harness integration pages under it cover install paths, configuration keys and known limitations.+- `https://api.vikingdb.cn-beijing.volces.com/openviking` is the Volcengine-hosted OpenViking Service (OpenViking Cloud): the path prefix is part of the base url, it accepts `Authorization: Bearer` only, and its keys are issued from the Volcengine console rather than by a self-hosted admin.++## Rules++- Never print a full API key or the raw contents of `ovcli.conf`; the+ doctor's masked forms are the limit.+- `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.+- `/health` returning 200 proves reachability only. Auth is proven by the+ identity fields with a key, or by `/api/v1/system/status`.+- `ov doctor` is `openviking-server doctor`: it validates the server's own+ config and providers in the server's Python environment, makes a live+ embedding call, and says nothing about this plugin. Run it for provider-level+ failures, not first.+- The doctor only reads. Never stop, restart or `kill` the user's server, or+ edit `ov.conf`, without asking.+- Older proxy versions say "check that 'ov serve' is running" — there is no+ such command; the server is started with `openviking-server`.+- Do not read `~/.openviking/state/*.json` for a Codex verdict — those files+ are written by the Claude Code plugin.diff --git a/examples/codex-memory-plugin/skills/ov-memory-doctor/reference.md b/examples/codex-memory-plugin/skills/ov-memory-doctor/reference.mdnew file mode 100644index 000000000..e7f255e4a--- /dev/null+++ b/examples/codex-memory-plugin/skills/ov-memory-doctor/reference.md@@ -0,0 +1,172 @@+# OpenViking Memory Doctor (Codex) — reference++Companion to SKILL.md: where things live, what the exact error strings mean,+and the symptom catalogue. Paths assume the defaults; `OPENVIKING_CONFIG_FILE`,+`OPENVIKING_CLI_CONFIG_FILE`, `OPENVIKING_DEBUG_LOG`, `OPENVIKING_CODEX_STATE_DIR`+and `CODEX_CONFIG_FILE` relocate individual pieces.++## Where things live++| Path | What |+|---|---|+| `~/.openviking/ovcli.conf` | Client connection: `url`, `api_key`, `account`, `user`, optional `plugin.codex.*` tuning. Mode 0600. |+| `~/.openviking/ov.conf` | Server config. The plugin reads only `server.url/host/port`, `server.root_api_key` (last-resort key) and the legacy `codex` block. |+| `~/.openviking/ovcli.conf.<name>` | Saved CLI profiles (`ov config switch` copies one over `ovcli.conf`). `ovcli.conf.bak.<epoch>` are installer backups. |+| `~/.codex/config.toml` | `[features] plugin_hooks`, `[plugins."openviking-memory@openviking"] enabled`, `[marketplaces.openviking]` (source, ref), `[hooks.state."openviking-memory@openviking:hooks/hooks.json:<event>:0:0"] trusted_hash` for `session_start`, `user_prompt_submit`, `stop`, `pre_compact`. |+| `~/.codex/plugins/cache/openviking/openviking-memory/<version>/` | The copy Codex runs hooks from. Keyed by `plugin.json` version. |+| `~/.codex/.tmp/marketplaces/openviking/` | Git clone of the marketplace (GitHub/TOS dist); `examples/codex-memory-plugin` inside it is what `codex plugin list` reports as the source path. |+| `~/.openviking/codex-plugin-state/<session_id>.json` | Per-session state: `ovSessionId` (`cx-<session_id>`, null once committed), `capturedTurnCount`, `lastUpdatedAt`. |+| `~/.openviking/codex-plugin-state/recall-compressor-profile.json` | Cached local-compressor detection (`profile.enabled`, `model`, `source`). |+| `~/.openviking/logs/codex-hooks.log` | JSONL hook + proxy log; written only when `OPENVIKING_DEBUG=1` or `codex.debug: true`. |+| `~/.openviking/codex-plugin.rc.sh`, `~/.openviking/codex-memory-plugin/runtime/` | Residue of the pre-marketplace installer. The rc script, if still sourced, exports `OPENVIKING_*` and pins credentials to env mode. |++## Config resolution++`OPENVIKING_CREDENTIAL_SOURCE` picks the mode: `env` (env vars only), `cli`+(ovcli.conf only — env and ov.conf ignored), default `auto` (env vars win when+any credential var is set, else ovcli.conf, else ov.conf/defaults). The+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` |+| peer | `OPENVIKING_PEER_ID` → `ovcli.conf actor_peer_id/peer_id` → `ov.conf codex.peerId` → derived from cwd unless `OPENVIKING_WORKSPACE_PEER=0` |+| auth mode | `OPENVIKING_AUTH_MODE` → `codex.authMode` → `server.auth_mode` → `trusted` when account/user are set, else `api_key` |+| tuning | env → `ovcli.conf plugin.codex.*` → `ovcli.conf plugin.*` → `ov.conf codex.*` → defaults |++There is no global kill switch: `OPENVIKING_MEMORY_ENABLED` is ignored by the+Codex plugin. Disable features with `OPENVIKING_AUTO_RECALL=0`,+`OPENVIKING_AUTO_CAPTURE=0`, `OPENVIKING_NO_AUTO_INJECT=1`, or the plugin via+`codex plugin remove openviking-memory@openviking` / `enabled = false`.++Hook budgets in `hooks/hooks.json`: SessionStart 70s, UserPromptSubmit 130s,+Stop 30s, PreCompact 60s. `recallTimeoutMs` (default 120000) must stay below+130s and `captureTimeoutMs` (default 30000) at or below 30s.++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.++## Server auth modes (from `GET /health` → `auth_mode`)++| Mode | Credential | Identity |+|---|---|---|+| `dev` | none needed, any key accepted | `X-OpenViking-Account/User` headers, else `default`; role root |+| `api_key` | key required | from the key; account/user headers are silently stripped |+| `trusted` | root key optional | from the headers; missing → 400 `Trusted mode requests must include X-OpenViking-Account …` |++Key formats: `base64url(account).base64url(user).base64url(secret)` (three+segments, identity readable) or a bare 64-hex legacy key. Both fail+identically as `401 Invalid API Key` when unknown — there is no "wrong+account" error.++`role: root` keys are refused on everything the plugin uses (`/api/v1/sessions`,+`/api/v1/search`, `/api/v1/fs`, `/mcp`) with+`403 ROOT API keys cannot access tenant-scoped data APIs in api_key mode`.++## Error strings++Server (REST): `{"status":"error","error":{"code":…,"message":…}}`++| HTTP | code | message | Meaning |+|---|---|---|---|+| 401 | UNAUTHENTICATED | `Missing API Key when resolving identity.` | No credential reached the server (gateway stripped `Authorization`, or `bearer` lowercase) |+| 401 | UNAUTHENTICATED | `Invalid API Key` | Unknown/revoked key, or a well-formed key for a non-existent account/user |+| 403 | PERMISSION_DENIED | `ROOT API keys cannot access tenant-scoped data APIs …` | Root key used as the plugin key |+| 403 | PERMISSION_DENIED | `Requires role: …` | Key valid, role too low for that route |+| 400 | INVALID_ARGUMENT | `Trusted mode requests must include X-OpenViking-Account …` | Trusted mode without account/user |+| 412 | FAILED_PRECONDITION | `User deletion is in progress` | The user is being deleted |++`/mcp` directly: `406 Not Acceptable: Client must accept both application/json and text/event-stream`;+`400` plain text `Invalid Content-Type header`; `401/403` as JSON-RPC `-32001`+with the server message; `404` → no MCP endpoint at that url.++Plugin MCP proxy (what Codex shows for a failing tool call):++| JSON-RPC | Message | Meaning |+|---|---|---|+| `-32001` | `OpenViking MCP authentication failed (HTTP 401\|403). Check ~/.openviking/ovcli.conf or OPENVIKING_API_KEY …` | Credentials; `data.serverMessage` carries the server text |+| `-32001` | `OpenViking MCP request failed. Check the configured URL (<mcpUrl>) …` | Transport: `data.cause` = `fetch failed` (refused/DNS/TLS), `This operation was aborted` (timeout). The url in the message is the one actually used. |+| `-32002` | `OpenViking MCP upstream returned HTTP <n>.` | Any other status; HTML in `data.serverMessage` means the url is not an OpenViking endpoint |+| `-32003` | `OpenViking MCP upstream returned an empty response` | 2xx with blank/non-JSON body — captive portal or proxy interstitial |++Hook log (`codex-hooks.log`) hooks: `session-start`, `auto-recall`,+`auto-capture`, `pre-compact`, `mcp-proxy`. Stages worth grepping:+`health_check`, `appended`, `pending_tokens`, `commit`, `recall_context_assembled`,+`mcp-proxy` `start` (resolved `mcpUrl`, `hasApiKey` = present, not valid),+`uncaught`. Ordinary failed proxy requests are not logged — the JSON-RPC error+on stdout is the artifact.++## Local server (loopback url only)++| Path | What |+|---|---|+| `~/.openviking/ov.conf` (or `OPENVIKING_CONFIG_FILE`, then `/etc/openviking/ov.conf`) | The server's config. The doctor checks the copy the plugin resolves for plugin-only keys; a server started with another `--config` runs from that file instead. |+| `<storage.workspace>/` | Data: `viking/` (content), `vectordb/context/` (index), `_system/queue/queue.db`. `storage.workspace` defaults to `./data` relative to the server's cwd. |+| `<workspace>/log/openviking.log` | Only with `log.output: "file"`. Default is stdout (terminal / tmux / nohup file / `journalctl -u openviking` / `docker logs openviking`). Time-rotated as `openviking.log.YYYY-MM-DD`. |+| docker | Container `openviking`, image `ghcr.io/volcengine/openviking`, `~/.openviking` mounted at `/app/.openviking` (config, ovcli.conf and data). `docker exec openviking openviking-server doctor` works. |++Process: `<python> -E …/bin/openviking-server` — match `openviking-server` in+the command line, never the process name (`Python`). Default bind+`127.0.0.1:1933`; `--host`/`--port` override `server.host`/`server.port`. The+port is bound only after initialization finishes, so "connection refused"+during startup is normal; `/health` 200 says nothing about embedding or VLM.++`GET /ready` (no auth, 200 or 503):+`{"status":"ready"|"not_ready","checks":{"agfs":{"status":…,"checks":{"filesystem":…,"multiwrite_sync":…}},"vectordb":…,"api_key_manager":…,"embedding":…,"ollama":…}}`.+`ok`, `not_configured` and `not_supported` count as healthy; `embedding` is a+real embed call with a 10s cap. `503 {"status":"not_ready","reason":"initializing"}`+while booting; 404 on servers that predate the endpoint. The official docker+image answers every route with `503 {"status":"pending_initialization", "fix":[…]}`+until it has an ov.conf.++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 |+| `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.`) |+| `EmbeddingRebuildRequiredError` / `embedding dimension (…) does not match current configuration` | Embedding model changed on an existing workspace (exit 3) |+| `[Errno 48] / [Errno 98] Address already in use` | Port taken — `lsof -nP -iTCP:1933 -sTCP:LISTEN` |+| `FATAL: AUTHENTICATION HEALTH CHECK FAILED` | OIDC/LDAP backend unreachable |++Runtime signatures in the server log: `Dimension mismatch` (config), `Dense+vector dimension mismatch` (writes dropped), `Credential … failed with auth`+and `Backup VLM also failed` (VLM key), `Embedding circuit breaker is open`+(provider down, messages re-queued).++`openviking-server doctor` (same as `ov doctor`) checks Config, Python,+Native Engine, AGFS, Authentication, Embedding (live probe), VLM (key presence+only), Ollama, VikingBot and Disk. Text only, exit 1 on FAIL, needs the+server's Python environment; the bare Rust `ov` binary (npm / cargo install)+reports `unknown command`.++## Symptom catalogue++| Symptom | Likely cause | Detect | Fix |+|---|---|---|---|+| Plugin listed and enabled, but no `<openviking-context>` ever, no log | `plugin_hooks` off, hooks never trusted, or no parseable config | doctor Plugin install + Configuration sections | Enable hooks / approve the prompt / fix config |+| Worked until an edit to `ovcli.conf` | JSON broken by the edit | doctor "cannot be parsed" | Fix JSON |+| Edits to `ovcli.conf` or `ov config switch` have no effect | Env var or rc-file export wins (`credential source: env`) | doctor "← env"; `env \| grep OPENVIKING_` | Remove the export |+| Recall empty on a healthy server | Wrong key (401 reads as no results), wrong user space, peer scope, threshold | `/health` with key; `/api/v1/system/status` → `result.user` | Fix key; `OPENVIKING_PEER_ID`; lower `OPENVIKING_SCORE_THRESHOLD` |+| Recall empty after moving/renaming the repo | Workspace peer derived from cwd changed (with `recallPeerScope: actor`) | doctor `peer … ← workspace` | Pin `OPENVIKING_PEER_ID` or `OPENVIKING_WORKSPACE_PEER=0` |+| Hooks stopped after a plugin update | `hooks.json` hash changed; Codex re-prompts for trust | doctor "hooks without a trust record" | Accept the prompt in a new session |+| MCP tools missing | `.mcp.json` not loaded (plugin disabled), node missing, or `/mcp` not proxied | doctor Connection `/mcp` probe | Fix enablement / node / reverse proxy |+| Everything duplicated | Two plugin ids installed (legacy `openviking-plugins-local`) | doctor "more than one copy" | `codex plugin remove <stale id>` |+| `codex plugin marketplace upgrade` says up to date but bug persists | Version-keyed cache, version string unchanged | doctor cache versions vs marketplace copy | Re-run the installer (re-registers the marketplace) |+| Every prompt is slow | Local compressor (`codex exec`) on each recall | `recall-compressor-profile.json`; `OPENVIKING_RECALL_COMPRESS=0` to test | Disable compression or fix the model |+| curl works, plugin says offline | Corporate proxy or private CA; Node ignores both | doctor proxy/TLS hints; `node -e "fetch('<url>/health')"` | `NODE_USE_ENV_PROXY=1` / `NODE_EXTRA_CA_CERTS` in the launching environment |+| `0 memories extracted` / commits never produce memories | VLM missing or failing, or embedding failing on the server | doctor `/ready: embedding`; ov.conf without a `vlm` section; server log `Backup VLM also failed` / `Credential … failed with auth` | Fix vlm/embedding in ov.conf, restart the server |+| "server unreachable" right after editing ov.conf | The server exited at its restart because of the edit | doctor Server health lint; the startup text in the server's terminal | Fix the finding, start it again |+| Recall empty and the index never grows after switching the embedding model | Dimension mismatch — every vector write is dropped | startup `EmbeddingRebuildRequiredError`, or log `Dense vector dimension mismatch` while it still runs | Original model, or a fresh workspace |++## Links++- Source: <https://github.com/volcengine/OpenViking>+- Docs index: <https://docs.openviking.ai/llms.txt>diff --git a/examples/memory-plugin-shared/doctor-core.test.mjs b/examples/memory-plugin-shared/doctor-core.test.mjsnew file mode 100644index 000000000..1bc61963d--- /dev/null+++ b/examples/memory-plugin-shared/doctor-core.test.mjs@@ -0,0 +1,193 @@+import assert from "node:assert/strict";+import { mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";++import {+ assessProbes,+ assessReady,+ classifyFetchError,+ createReport,+ describeApiKey,+ inspectJsonFile,+ lintBaseUrl,+ lintServerConf,+ readyCheckState,+ scanDebugLog,+ unknownOvcliKeys,+} from "./lib/doctor-core.mjs";++const b64 = (s) => Buffer.from(s).toString("base64url");++test("describeApiKey decodes identity segments and masks the secret", () => {+ const key = `${b64("acme")}.${b64("alice")}.${b64("0123456789abcdef0123456789abcdef")}`;+ const info = describeApiKey(key);+ assert.equal(info.format, "v2");+ assert.equal(info.account, "acme");+ assert.equal(info.user, "alice");+ assert.match(info.display, /^account=acme user=alice secret=[A-Za-z0-9_-]{4}…[A-Za-z0-9_-]{4}$/);+ assert.ok(!info.display.includes(key.split(".")[2]));+ assert.deepEqual(info.problems, []);+});++test("describeApiKey shows head/tail only for legacy keys", () => {+ const key = "ff6e58" + "a".repeat(54) + "f956";+ const info = describeApiKey(key);+ assert.equal(info.format, "legacy");+ assert.equal(info.display, "ff6e…f956 (64 chars, legacy single-segment format)");+ assert.equal(describeApiKey("").present, false);+ assert.equal(describeApiKey("short").display, "***** (5 chars, legacy single-segment format)");+});++test("describeApiKey flags copy/paste damage", () => {+ assert.ok(describeApiKey("Bearer abcdefghijkl").problems.some((p) => p.includes("Bearer")));+ assert.ok(describeApiKey(" abcdefghijkl\n").problems.some((p) => p.includes("whitespace")));+ const mangled = describeApiKey("YWNt.not*base64.abc");+ assert.equal(mangled.format, "v2");+ assert.ok(mangled.problems.some((p) => p.includes("not decodable")));+});++test("lintBaseUrl catches the common url mistakes", () => {+ assert.deepEqual(lintBaseUrl("https://ov.example.com"), []);+ assert.deepEqual(lintBaseUrl("https://api.vikingdb.cn-beijing.volces.com/openviking"), []);+ assert.ok(lintBaseUrl("ov.example.com").some((p) => p.level === "fail" && /scheme/.test(p.message)));+ assert.ok(lintBaseUrl("https://ov.example.com/api/v1").some((p) => /\/api\/v1/.test(p.message)));+ assert.ok(lintBaseUrl("https://ov.example.com/mcp").some((p) => /\/mcp/.test(p.message)));+ assert.ok(lintBaseUrl("http://0.0.0.0:1933").some((p) => /0\.0\.0\.0/.test(p.message)));+ assert.ok(lintBaseUrl("").some((p) => p.level === "fail"));+});++test("classifyFetchError maps node errors to hints", () => {+ assert.equal(classifyFetchError({ cause: { code: "ECONNREFUSED" } }).kind, "refused");+ assert.equal(classifyFetchError({ cause: { code: "ENOTFOUND" } }).kind, "dns");+ assert.equal(classifyFetchError({ name: "AbortError", message: "aborted" }).kind, "timeout");+ assert.equal(classifyFetchError({ cause: { code: "UNABLE_TO_VERIFY_LEAF_SIGNATURE", message: "unable to verify" } }).kind, "tls");+});++test("inspectJsonFile reports parse errors instead of swallowing them", () => {+ const dir = mkdtempSync(join(tmpdir(), "ov-doctor-"));+ const path = join(dir, "ovcli.conf");+ writeFileSync(path, '{"url": "https://x", "api_key": "y",}');+ const broken = inspectJsonFile(path);+ assert.equal(broken.exists, true);+ assert.equal(broken.ok, false);+ assert.match(broken.error, /invalid JSON/);+ writeFileSync(path, '{"url": "https://x", "apiKey": "y", "plugin": {}}');+ const parsed = inspectJsonFile(path);+ assert.equal(parsed.ok, true);+ assert.deepEqual(unknownOvcliKeys(parsed.data), ["apiKey"]);+ assert.equal(inspectJsonFile(join(dir, "missing.conf")).exists, false);+});++test("assessProbes treats /health without identity as a rejected key", () => {+ const conn = { baseUrl: "https://ov.example.com", apiKey: "k".repeat(64) };+ const health = { ok: true, status: 200, latencyMs: 50, json: { status: "ok", version: "0.4.17", auth_mode: "api_key" } };+ const report = createReport();+ const summary = assessProbes(report, { health, healthAuth: { ...health }, systemStatus: { ok: false, status: 401, json: { error: { message: "Invalid API Key" } } } }, conn, describeApiKey(conn.apiKey));+ assert.equal(summary.reachable, true);+ assert.equal(summary.authOk, false);+ const titles = report.problems().map((p) => p.title);+ assert.ok(titles.some((t) => t.startsWith("api key rejected")));+ assert.ok(titles.some((t) => t.includes("system/status → 401")));+ assert.equal(report.exitCode(), 1);+});++test("assessProbes accepts an echoed identity and warns about root keys", () => {+ const conn = { baseUrl: "https://ov.example.com", apiKey: "k".repeat(64), account: "other" };+ const health = { ok: true, status: 200, latencyMs: 50, json: { status: "ok", version: "0.4.17", auth_mode: "api_key" } };+ const healthAuth = { ...health, json: { ...health.json, account_id: "default", user_id: "default", role: "root" } };+ const report = createReport();+ const summary = assessProbes(report, { health, healthAuth }, conn, describeApiKey(conn.apiKey));+ assert.equal(summary.authOk, true);+ assert.deepEqual(summary.identity, { account: "default", user: "default", role: "root" });+ const titles = report.problems().map((p) => p.title);+ assert.ok(titles.some((t) => t.includes("ROOT api key")));+ assert.ok(titles.some((t) => t.includes("differ from the key's identity")));+});++test("assessProbes reports unreachable servers with the classified cause", () => {+ const report = createReport();+ assessProbes(report, { health: { ok: false, status: 0, error: "connect ECONNREFUSED", errorKind: "refused", errorHint: "connection refused" } }, { baseUrl: "http://127.0.0.1:1933" }, describeApiKey(""));+ assert.equal(report.exitCode(), 1);+ assert.match(report.render(), /server unreachable/);+});++test("scanDebugLog separates recent errors from history", () => {+ const dir = mkdtempSync(join(tmpdir(), "ov-doctor-log-"));+ const path = join(dir, "cc-hooks.log");+ const now = Date.now();+ const line = (ts, hook, stage, error) => JSON.stringify(error ? { ts, hook, stage, error } : { ts, hook, stage, data: {} });+ writeFileSync(path, [+ line(new Date(now - 30 * 86400000).toISOString(), "auto-capture", "transcript_read", { message: "old" }),+ line(new Date(now - 3600000).toISOString(), "mcp-proxy", "start", null).replace('"data":{}', '"data":{"mcpUrl":"https://ov.example.com/mcp"}'),+ line(new Date(now - 60000).toISOString(), "auto-recall", "uncaught", { message: "fresh" }),+ "not json",+ ].join("\n"));+ const scan = scanDebugLog(path);+ assert.equal(scan.exists, true);+ assert.deepEqual(scan.hooks, ["auto-capture", "auto-recall", "mcp-proxy"]);+ assert.equal(scan.errors.length, 2);+ assert.deepEqual(scan.recentErrors.map((e) => e.message), ["fresh"]);+ assert.equal(scan.proxyStart.data.mcpUrl, "https://ov.example.com/mcp");+});++test("report render lists problems in the summary and sets the exit code", () => {+ const report = createReport();+ report.section("A");+ report.ok("fine");+ report.warn("meh", "detail", "do this");+ assert.equal(report.exitCode(), 0);+ report.fail("bad", "", "do that");+ assert.equal(report.exitCode(), 1);+ const text = report.render();+ assert.match(text, /== Summary ==\n 1 failure\(s\), 1 warning\(s\)/);+ assert.match(text, /✗ bad → do that/);+ assert.match(text, /⚠ meh → do this/);+});++test("lintServerConf flags the plugin-only ov.conf keys a server refuses to start on", () => {+ const findings = lintServerConf({ claude_code: { enabled: true }, codex: {}, server: { url: "http://x", port: 1933 } });+ assert.deepEqual(findings.map((f) => f.level), ["warn", "warn", "warn"]);+ assert.match(findings[0].message, /'claude_code' block/);+ assert.match(findings[1].message, /'codex' block/);+ assert.match(findings[2].message, /server\.url is rejected/);+ assert.deepEqual(lintServerConf({ server: { port: 1933 }, embedding: {} }), []);+ assert.deepEqual(lintServerConf(null), []);+});++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();+ assert.equal(assessReady(report, ok).ready, true);+ assert.equal(report.exitCode(), 0);+ assert.match(report.render(), /\/ready: agfs ok, vectordb ok/);++ const failing = { ok: false, status: 503, json: { status: "not_ready", checks: { agfs: { status: "error", checks: { filesystem: "error: boom" } }, vectordb: "ok", api_key_manager: "ok", embedding: "error: probe timed out (provider unreachable)", ollama: "not_configured" } } };+ report = createReport();+ const res = assessReady(report, failing);+ assert.equal(res.ready, false);+ assert.equal(res.checks.agfs, "error (filesystem: error: boom)");+ const titles = report.problems().map((p) => p.title);+ assert.ok(titles.some((t) => t.startsWith("/ready: embedding →")));+ assert.ok(titles.some((t) => t.startsWith("/ready: agfs →")));++ report = createReport();+ assert.equal(assessReady(report, { ok: false, status: 503, json: { status: "not_ready", reason: "initializing" } }).ready, false);+ assert.ok(report.problems().some((p) => p.level === "warn" && /still initializing/.test(p.title)));+ report = createReport();+ assert.equal(assessReady(report, { ok: false, status: 404, json: { detail: "Not Found" } }).ready, null);+ assert.equal(report.exitCode(), 0);+ assert.equal(readyCheckState("not_supported").ok, true);+ assert.equal(readyCheckState({ status: "ok", checks: { a: "ok", b: "error: x" } }).ok, false);+});++test("assessProbes recognises the docker pending-config stub", () => {+ const report = createReport();+ const health = { ok: false, status: 503, latencyMs: 3, json: { status: "pending_initialization", error: "OpenViking config file not found", config_file: "/app/.openviking/ov.conf", fix: ["mount ~/.openviking on the host to /app/.openviking"] } };+ const summary = assessProbes(report, { health }, { baseUrl: "http://127.0.0.1:1933" }, describeApiKey(""));+ assert.equal(summary.reachable, true);+ const problem = report.problems()[0];+ assert.match(problem.title, /docker container is up but has no ov\.conf/);+ assert.match(problem.detail, /mount ~\/\.openviking on the host/);+});diff --git a/examples/memory-plugin-shared/lib/doctor-core.mjs b/examples/memory-plugin-shared/lib/doctor-core.mjsnew file mode 100644index 000000000..f06e7f8f1--- /dev/null+++ b/examples/memory-plugin-shared/lib/doctor-core.mjs@@ -0,0 +1,900 @@+/**+ * Harness-agnostic building blocks for the memory plugin doctor scripts.+ *+ * Each harness ships a thin `ov-memory-doctor.mjs` entrypoint that knows its+ * own install layout (where the plugin is registered, which hooks file, which+ * 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.+ *+ * Nothing here reads harness config; callers pass a resolved connection+ * `{ baseUrl, apiKey, account, user, peerId, userAgent }`.+ */++import { execFileSync } from "node:child_process";+import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";++// ---------------------------------------------------------------------------+// Formatting helpers+// ---------------------------------------------------------------------------++export function homeShort(path) {+ const home = homedir();+ if (!path) return path;+ return path.startsWith(home) ? `~${path.slice(home.length)}` : path;+}++export function fmtAge(ts) {+ if (!ts) return "never";+ const sec = Math.floor((Date.now() - ts) / 1000);+ if (sec < 0) return "just now";+ if (sec < 60) return `${sec}s ago`;+ if (sec < 3600) return `${Math.floor(sec / 60)}m ago`;+ if (sec < 86400) return `${Math.floor(sec / 3600)}h ago`;+ return `${Math.floor(sec / 86400)}d ago`;+}++export function fmtBytes(n) {+ if (n == null) return "?";+ if (n < 1024) return `${n} B`;+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;+ return `${(n / 1024 / 1024).toFixed(1)} MB`;+}++function str(value, fallback = "") {+ return typeof value === "string" && value.trim() ? value.trim() : fallback;+}++// ---------------------------------------------------------------------------+// Report+// ---------------------------------------------------------------------------++const LEVEL_ORDER = { fail: 0, warn: 1, info: 2, ok: 3 };+const LEVEL_MARK = { ok: "✓", info: "·", warn: "⚠", fail: "✗" };+const LEVEL_COLOR = { ok: "32", info: "2", warn: "33", fail: "31" };++export function createReport({ color = false } = {}) {+ const sections = [];+ let current = null;++ function paint(code, text) {+ return color ? `\x1b[${code}m${text}\x1b[0m` : text;+ }++ function section(title) {+ current = { title, findings: [] };+ sections.push(current);+ return current;+ }++ function add(level, title, detail, fix) {+ if (!current) section("General");+ const finding = { level, title };+ if (detail) finding.detail = String(detail);+ if (fix) finding.fix = String(fix);+ current.findings.push(finding);+ return finding;+ }++ const report = {+ sections,+ section,+ add,+ ok: (title, detail) => add("ok", title, detail),+ info: (title, detail) => add("info", title, detail),+ warn: (title, detail, fix) => add("warn", title, detail, fix),+ fail: (title, detail, fix) => add("fail", title, detail, fix),+ problems() {+ return sections.flatMap((s) => s.findings.filter((f) => f.level === "fail" || f.level === "warn"));+ },+ exitCode() {+ return sections.some((s) => s.findings.some((f) => f.level === "fail")) ? 1 : 0;+ },+ render() {+ const lines = [];+ for (const s of sections) {+ lines.push(paint("1", `== ${s.title} ==`));+ for (const f of s.findings) {+ lines.push(` ${paint(LEVEL_COLOR[f.level], LEVEL_MARK[f.level])} ${f.title}`);+ if (f.detail) for (const l of String(f.detail).split("\n")) lines.push(` ${l}`);+ if (f.fix && (f.level === "warn" || f.level === "fail")) lines.push(` ${paint("36", "fix:")} ${f.fix}`);+ }+ lines.push("");+ }+ const problems = report.problems().sort((a, b) => LEVEL_ORDER[a.level] - LEVEL_ORDER[b.level]);+ lines.push(paint("1", "== Summary =="));+ if (!problems.length) {+ lines.push(` ${paint("32", "✓")} no problems found`);+ } else {+ const fails = problems.filter((p) => p.level === "fail").length;+ lines.push(` ${fails} failure(s), ${problems.length - fails} warning(s)`);+ for (const p of problems) {+ lines.push(` ${paint(LEVEL_COLOR[p.level], LEVEL_MARK[p.level])} ${p.title}${p.fix ? ` → ${p.fix}` : ""}`);+ }+ }+ return lines.join("\n");+ },+ toJSON() {+ return { sections };+ },+ };+ return report;+}++// ---------------------------------------------------------------------------+// API key display+// ---------------------------------------------------------------------------++export function decodeBase64Url(segment) {+ if (typeof segment !== "string" || !segment || /[^A-Za-z0-9_-]/.test(segment)) return null;+ try {+ const padded = segment + "=".repeat((4 - (segment.length % 4)) % 4);+ const text = Buffer.from(padded, "base64url").toString("utf-8");+ // Reject decoded text that is not printable — a random string that happens+ // to be valid base64 decodes to binary garbage.+ if (!text || /[^\x20-\x7e]/.test(text)) return null;+ return text;+ } catch {+ return null;+ }+}++function headTail(value, keep = 4) {+ if (!value) return "";+ if (value.length <= keep * 2 + 2) return "*".repeat(Math.max(4, value.length));+ return `${value.slice(0, keep)}…${value.slice(-keep)}`;+}++/**+ * Describe an API key for display without revealing it.+ *+ * three-segment key → account=<decoded> user=<decoded> secret=abcd…wxyz+ * single-segment key → abcd…wxyz (64 chars, legacy format)+ *+ * The three-segment format is base64url(account).base64url(user).base64url(secret);+ * the first two segments carry no secret and are decoded so the operator can see+ * which identity the key claims. Also reports shape problems that commonly come+ * from copy/paste mistakes.+ */+export function describeApiKey(rawKey) {+ const info = { present: false, format: "none", display: "(none)", account: "", user: "", length: 0, problems: [] };+ if (typeof rawKey !== "string" || !rawKey) return info;++ info.present = true;+ info.length = rawKey.length;+ if (rawKey !== rawKey.trim()) info.problems.push("has leading/trailing whitespace");+ if (/[\r\n]/.test(rawKey)) info.problems.push("contains a line break");+ if (/^["']|["']$/.test(rawKey.trim())) info.problems.push("wrapped in quotes");+ if (/^bearer\s+/i.test(rawKey.trim())) info.problems.push("starts with 'Bearer ' — store only the key itself");++ const key = rawKey.trim().replace(/^bearer\s+/i, "").replace(/^["']|["']$/g, "");+ const parts = key.split(".");+ if (parts.length === 3) {+ info.format = "v2";+ const account = decodeBase64Url(parts[0]);+ const user = decodeBase64Url(parts[1]);+ info.account = account || "";+ info.user = user || "";+ const accountText = account ?? `${headTail(parts[0])} (not base64url)`;+ const userText = user ?? `${headTail(parts[1])} (not base64url)`;+ if (account === null || user === null) info.problems.push("account/user segment is not decodable base64url — key may be truncated or mangled");+ if (!parts[2]) info.problems.push("secret segment is empty");+ info.display = `account=${accountText} user=${userText} secret=${headTail(parts[2])}`;+ } else {+ info.format = "legacy";+ if (parts.length !== 1) info.problems.push(`unexpected shape: ${parts.length} dot-separated segments (expected 1 or 3)`);+ info.display = `${headTail(key)} (${key.length} chars, ${parts.length === 1 ? "legacy single-segment" : "unrecognised"} format)`;+ }+ return info;+}++/** Mask any secret-looking env value for display. */+export function maskSecret(value) {+ return headTail(String(value ?? ""), 4);+}++// ---------------------------------------------------------------------------+// Base URL lint+// ---------------------------------------------------------------------------++export function lintBaseUrl(url) {+ const problems = [];+ const value = String(url ?? "");+ if (!value.trim()) {+ problems.push({ level: "fail", message: "base URL is empty", fix: "set url in ovcli.conf or OPENVIKING_URL" });+ return problems;+ }+ if (value !== value.trim() || /\s/.test(value)) {+ problems.push({ level: "fail", message: "base URL contains whitespace", fix: "remove stray spaces/newlines around the url value" });+ }+ if (!/^https?:\/\//i.test(value.trim())) {+ problems.push({ level: "fail", message: "base URL has no http:// or https:// scheme — fetch() rejects it as 'Failed to parse URL'", fix: "prefix the url with http:// or https://" });+ return problems;+ }+ let parsed;+ try {+ parsed = new URL(value.trim());+ } catch {+ problems.push({ level: "fail", message: "base URL does not parse", fix: "check the url value for typos" });+ return problems;+ }+ const path = parsed.pathname.replace(/\/+$/, "");+ if (/\/api(\/v1)?$/i.test(path)) {+ problems.push({ level: "fail", message: `base URL ends with ${path} — every request becomes ${path}/api/v1/... and 404s`, fix: "drop the /api/v1 suffix; the plugin appends API paths itself" });+ }+ if (/\/mcp$/i.test(path)) {+ problems.push({ level: "fail", message: "base URL ends with /mcp — the plugin appends /mcp itself", fix: "use the server root URL, not the MCP endpoint" });+ }+ if (parsed.hostname === "0.0.0.0") {+ problems.push({ level: "warn", message: "host 0.0.0.0 is a bind address, not a destination", fix: "use 127.0.0.1 or the real hostname" });+ }+ if (parsed.search || parsed.hash) {+ problems.push({ level: "warn", message: "base URL carries a query string or fragment", fix: "remove everything after the path" });+ }+ return problems;+}++export function isLoopbackUrl(url) {+ try {+ const host = new URL(url).hostname;+ return host === "127.0.0.1" || host === "localhost" || host === "::1" || host === "[::1]";+ } catch {+ return false;+ }+}++// ---------------------------------------------------------------------------+// Files and environment+// ---------------------------------------------------------------------------++export function inspectJsonFile(path) {+ const out = { path, exists: false, ok: false, error: "", data: null, mode: "", size: 0, mtimeMs: 0 };+ if (!path) return out;+ let st;+ try {+ st = statSync(path);+ } catch {+ return out;+ }+ out.exists = true;+ out.size = st.size;+ out.mtimeMs = st.mtimeMs;+ out.mode = (st.mode & 0o777).toString(8);+ let raw;+ try {+ raw = readFileSync(path, "utf-8");+ } catch (err) {+ out.error = `unreadable: ${err?.message || err}`;+ return out;+ }+ try {+ out.data = JSON.parse(raw);+ out.ok = out.data !== null && typeof out.data === "object";+ if (!out.ok) out.error = "top level is not a JSON object";+ } catch (err) {+ out.error = `invalid JSON: ${err?.message || err}`;+ }+ return out;+}++const KNOWN_OVCLI_KEYS = new Set([+ "url", "api_key", "root_api_key", "account", "user", "account_id", "user_id",+ "actor_peer_id", "peer_id", "agent_id", "timeout", "output", "echo_command",+ "extra_headers", "gateway_token", "auth_mode", "ldap_username", "ldap_password", "plugin",+]);++/** Keys in ovcli.conf that neither the CLI nor the plugins read — usually typos. */+export function unknownOvcliKeys(data) {+ if (!data || typeof data !== "object") return [];+ return Object.keys(data).filter((k) => !KNOWN_OVCLI_KEYS.has(k));+}++const SECRET_ENV = /KEY|TOKEN|SECRET|PASSWORD/i;++export function collectEnv(env = process.env) {+ const openviking = [];+ for (const name of Object.keys(env).sort()) {+ if (!name.startsWith("OPENVIKING_")) continue;+ const value = env[name] ?? "";+ openviking.push({ name, value: SECRET_ENV.test(name) ? maskSecret(value) : value });+ }+ const proxy = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy"]+ .filter((name) => str(env[name]))+ .map((name) => ({ name, value: env[name] }));+ const node = ["NODE_EXTRA_CA_CERTS", "NODE_TLS_REJECT_UNAUTHORIZED", "NODE_USE_ENV_PROXY", "NODE_OPTIONS"]+ .filter((name) => str(env[name]))+ .map((name) => ({ name, value: env[name] }));+ return { openviking, proxy, node };+}++/** Legacy rc-file wrapper blocks written by pre-stdio-proxy installers. */+export function scanRcFiles(markers, home = homedir()) {+ const hits = [];+ for (const file of [".zshrc", ".bashrc", ".zprofile", ".bash_profile", ".profile"]) {+ const path = `${home}/${file}`;+ let text;+ try {+ text = readFileSync(path, "utf-8");+ } catch {+ continue;+ }+ for (const marker of markers) {+ if (text.includes(marker)) hits.push({ file: homeShort(path), kind: "block", detail: marker });+ }+ const exported = [...new Set([...text.matchAll(/^\s*export\s+(OPENVIKING_[A-Z0-9_]+)=/gm)].map((m) => m[1]))];+ if (exported.length) hits.push({ file: homeShort(path), kind: "export", detail: exported.join(", "), vars: exported });+ }+ return hits;+}++// ---------------------------------------------------------------------------+// Commands+// ---------------------------------------------------------------------------++export function runCommand(command, args = [], { timeoutMs = 10000, env = process.env } = {}) {+ try {+ const stdout = execFileSync(command, args, {+ encoding: "utf-8",+ timeout: timeoutMs,+ env,+ stdio: ["ignore", "pipe", "pipe"],+ });+ return { ok: true, stdout: String(stdout).trim(), stderr: "" };+ } catch (err) {+ return {+ ok: false,+ stdout: String(err?.stdout ?? "").trim(),+ stderr: String(err?.stderr ?? "").trim(),+ error: err?.code === "ENOENT" ? "not found" : (err?.killed ? `timed out after ${timeoutMs}ms` : (err?.message || String(err))),+ };+ }+}++export function whichCommand(name) {+ const result = runCommand(process.platform === "win32" ? "where" : "which", [name], { timeoutMs: 5000 });+ return result.ok ? result.stdout.split("\n")[0] : "";+}++export function parseNodeMajor(version) {+ const m = /^v?(\d+)/.exec(String(version || ""));+ return m ? Number(m[1]) : NaN;+}++// ---------------------------------------------------------------------------+// HTTP probes+// ---------------------------------------------------------------------------++export function classifyFetchError(err) {+ const cause = err?.cause || err;+ const code = cause?.code || "";+ const message = String(cause?.message || err?.message || err || "");+ if (err?.name === "AbortError" || /aborted/i.test(message)) {+ return { kind: "timeout", hint: "no response within the timeout — wrong host/port, firewall, or a very slow server" };+ }+ if (code === "ECONNREFUSED") return { kind: "refused", hint: "connection refused — nothing is listening on that host:port (server down or wrong port)" };+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") return { kind: "dns", hint: "hostname does not resolve — typo in the url, or DNS/VPN not available" };+ if (code === "ECONNRESET" || code === "EPIPE") return { kind: "reset", hint: "connection reset — a proxy or TLS terminator closed the connection" };+ if (/certificate|CERT_|SELF_SIGNED|UNABLE_TO_VERIFY|ssl|tls/i.test(`${code} ${message}`)) {+ return { kind: "tls", hint: "TLS verification failed — private CA or self-signed cert; Node ignores the OS keychain, set NODE_EXTRA_CA_CERTS for the harness process" };+ }+ if (/Failed to parse URL|Invalid URL/i.test(message)) return { kind: "url", hint: "the url does not parse — check scheme and host" };+ if (/wrong version number|EPROTO/i.test(`${code} ${message}`)) return { kind: "tls", hint: "protocol mismatch — https:// against a plain-HTTP port (or vice versa)" };+ return { kind: "other", hint: message };+}++export async function httpProbe({ url, method = "GET", headers = {}, body, timeoutMs = 5000 }) {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs);+ const t0 = Date.now();+ const out = { url, method, ok: false, status: 0, latencyMs: 0, text: "", json: null, headers: {}, error: "", errorKind: "", errorHint: "" };+ try {+ const res = await fetch(url, { method, headers, body, signal: controller.signal, redirect: "manual" });+ out.status = res.status;+ out.ok = res.ok;+ out.latencyMs = Date.now() - t0;+ for (const [k, v] of res.headers.entries()) out.headers[k.toLowerCase()] = v;+ const text = await res.text().catch(() => "");+ out.text = text.length > 4000 ? `${text.slice(0, 4000)}…` : text;+ const contentType = out.headers["content-type"] || "";+ if (contentType.includes("text/event-stream")) {+ // Streamable HTTP frames: take the first data: line.+ const line = text.split("\n").find((l) => l.startsWith("data:"));+ if (line) {+ try { out.json = JSON.parse(line.slice(5).trim()); } catch { /* keep text */ }+ }+ } else {+ try { out.json = JSON.parse(text); } catch { /* not JSON */ }+ }+ } catch (err) {+ out.latencyMs = Date.now() - t0;+ const cls = classifyFetchError(err);+ out.error = err?.cause?.message || err?.message || String(err);+ out.errorKind = cls.kind;+ out.errorHint = cls.hint;+ } finally {+ clearTimeout(timer);+ }+ return out;+}++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;+}++export function serverErrorMessage(probe) {+ const body = probe?.json;+ if (!body) return probe?.text ? probe.text.replace(/\s+/g, " ").slice(0, 200) : "";+ return body?.error?.message || body?.error?.code || body?.message || body?.detail || "";+}++/**+ * Run the standard probe ladder against an OpenViking server.+ *+ * health GET /health without credentials — reachability, version, auth_mode+ * healthAuth GET /health with credentials — identity echo (account/user/role)+ * systemStatus GET /api/v1/system/status — first authenticated call the hooks make; real 401/403+ * fsLs GET /api/v1/fs/ls?uri=viking://~/memories — tenant-data authorization + resolved user space+ * mcp POST /mcp tools/list — what the MCP proxy forwards+ */+export async function probeOpenViking(conn, { timeoutMs = 5000, mcp = true } = {}) {+ const base = String(conn.baseUrl || "").replace(/\/+$/, "");+ const out = {};+ out.health = await httpProbe({ url: `${base}/health`, timeoutMs, headers: conn.userAgent ? { "User-Agent": conn.userAgent } : {} });+ if (out.health.error && out.health.errorKind !== "other") {+ // Hard network failure: the rest of the ladder would fail identically.+ return out;+ }+ if (conn.apiKey || conn.account || conn.user) {+ out.healthAuth = await httpProbe({ url: `${base}/health`, timeoutMs, headers: authHeaders(conn) });+ }+ out.systemStatus = await httpProbe({ url: `${base}/api/v1/system/status`, timeoutMs, headers: authHeaders(conn) });+ out.fsLs = await httpProbe({+ url: `${base}/api/v1/fs/ls?uri=${encodeURIComponent("viking://~/memories")}&output=original`,+ timeoutMs,+ headers: authHeaders(conn),+ });+ if (mcp) {+ out.mcp = await httpProbe({+ url: `${base}/mcp`,+ method: "POST",+ timeoutMs: Math.max(timeoutMs, 8000),+ headers: { ...authHeaders(conn), Accept: "application/json, text/event-stream", "MCP-Protocol-Version": "2025-06-18" },+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }),+ });+ }+ return out;+}++/**+ * Turn probe results into findings. `keyInfo` is describeApiKey(conn.apiKey).+ * Returns { authMode, version, identity } for callers that want to cross-check.+ */+export function assessProbes(report, probes, conn, keyInfo) {+ const summary = { authMode: "", version: "", identity: null, reachable: false, authOk: false };+ const health = probes.health;+ if (!health) return summary;++ if (health.error) {+ report.fail(`server unreachable: ${conn.baseUrl}`, `${health.errorKind || "error"}: ${health.error}\n${health.errorHint}`,+ "check that the server is running and the url/port are right; compare with `curl -sS <url>/health`");+ return summary;+ }+ summary.reachable = true;+ if (health.status === 404) {+ report.fail(`GET /health → 404 at ${conn.baseUrl}`, "the url points at a web server, but not at an OpenViking API root",+ "check for a missing path prefix (OpenViking Cloud needs /openviking) or a reverse proxy that does not forward /health");+ return summary;+ }+ if (health.status >= 300 && health.status < 400) {+ report.fail(`GET /health → ${health.status} redirect`, `location: ${health.headers.location || "?"}`,+ "the url is being redirected (http→https, or an SSO/login gateway); use the final url");+ return summary;+ }+ if (health.status === 503 && health.json?.status === "pending_initialization") {+ const fixes = Array.isArray(health.json.fix) ? health.json.fix.map((f) => `- ${f}`).join("\n") : "";+ report.fail("the OpenViking docker container is up but has no ov.conf — every request answers 503 until it does",+ `${health.json.error || ""}${health.json.config_file ? ` (expected at ${health.json.config_file} inside the container)` : ""}${fixes ? `\n${fixes}` : ""}`,+ "mount ~/.openviking (holding ov.conf) at /app/.openviking, or run `docker exec -it openviking openviking-server init`");+ return summary;+ }+ if (!health.ok || !health.json) {+ report.fail(`GET /health → ${health.status}`, serverErrorMessage(health) || "(non-JSON body)",+ "the server answered but not like OpenViking — verify the url reaches the OpenViking API, not a proxy error page");+ return summary;+ }+ summary.authMode = String(health.json.auth_mode || "");+ summary.version = String(health.json.version || "");+ report.ok(`server reachable — ${health.latencyMs}ms, version ${summary.version || "?"}, auth_mode=${summary.authMode || "?"}`);+ if (health.latencyMs > 1000) {+ report.warn(`/health took ${health.latencyMs}ms`, "the statusline probe has a 1s budget and will flap between 'slow' and 'offline'",+ "check network latency to the server; raise OPENVIKING_TIMEOUT_MS if hooks time out");+ }++ const identity = probes.healthAuth?.json;+ if (identity && identity.role) {+ summary.identity = { account: identity.account_id, user: identity.user_id, role: identity.role };+ summary.authOk = true;+ report.ok(`credentials accepted — account=${identity.account_id} user=${identity.user_id} role=${identity.role}`);+ if (identity.role === "root") {+ report.warn("using the ROOT api key", "root keys are rejected on tenant-data APIs and /mcp in api_key mode (403 'ROOT API keys cannot access tenant-scoped data APIs')",+ "create a user key (POST /api/v1/admin/accounts/<account>/users with the root key) and put that in ovcli.conf");+ }+ if (summary.authMode === "api_key" && keyInfo?.format === "v2") {+ if (keyInfo.account && keyInfo.account !== identity.account_id) {+ report.warn(`key claims account=${keyInfo.account} but server resolved account=${identity.account_id}`);+ }+ }+ if (summary.authMode === "api_key" && (conn.account || conn.user)) {+ const mismatch = (conn.account && conn.account !== identity.account_id) || (conn.user && conn.user !== identity.user_id);+ if (mismatch) {+ report.warn(`configured account/user (${conn.account || "-"}/${conn.user || "-"}) differ from the key's identity (${identity.account_id}/${identity.user_id})`,+ "in api_key mode the server ignores X-OpenViking-Account/User headers; the key decides where data lands",+ "remove account/user from the config, or use a key issued for that account/user");+ } else {+ report.info("account/user in config are redundant in api_key mode (identity comes from the key)");+ }+ }+ } else if (summary.authMode === "dev") {+ summary.authOk = true;+ report.info("server runs in dev auth mode — any key is accepted; identity comes from X-OpenViking-Account/User headers (default 'default')");+ if (identity?.account_id) summary.identity = { account: identity.account_id, user: identity.user_id, role: identity.role };+ } else if (conn.apiKey) {+ report.fail("api key rejected", `/health answered 200 but returned no identity for the key (${keyInfo?.display || "?"}) — the key is invalid, revoked, or belongs to another deployment`,+ "check the key in ovcli.conf / OPENVIKING_API_KEY against the one issued by the server admin");+ } else if (summary.authMode === "api_key") {+ report.fail("no api key configured but the server requires one (auth_mode=api_key)", "",+ "set api_key in ~/.openviking/ovcli.conf or OPENVIKING_API_KEY");+ } else if (summary.authMode === "trusted") {+ if (!conn.account || !conn.user) {+ report.fail("server is in trusted mode and needs account + user", "requests without X-OpenViking-Account/User are rejected with HTTP 400",+ "set account and user in ovcli.conf (or OPENVIKING_ACCOUNT / OPENVIKING_USER)");+ } else {+ summary.authOk = true;+ report.ok(`trusted mode — identity from headers account=${conn.account} user=${conn.user}`);+ }+ }++ const status = probes.systemStatus;+ if (status) {+ if (status.ok) {+ const user = status.json?.result?.user;+ report.ok(`GET /api/v1/system/status → 200${user ? ` (user space: ${user})` : ""}`);+ } else if (status.error) {+ report.fail("GET /api/v1/system/status failed", `${status.errorKind}: ${status.error}`);+ } else {+ const msg = serverErrorMessage(status);+ const level = status.status === 401 || status.status === 403 ? "fail" : "warn";+ report[level](`GET /api/v1/system/status → ${status.status}`, msg,+ status.status === 401 ? "the server rejected the credentials — this is what every hook hits after the /health gate passes"+ : status.status === 403 ? "the key is valid but not allowed here — wrong role or root key" : "");+ }+ }++ const fs = probes.fsLs;+ if (fs) {+ if (fs.ok) {+ const first = Array.isArray(fs.json?.result) ? fs.json.result.find((e) => e?.uri) : null;+ const space = first?.uri ? String(first.uri).replace(/\/memories\/.*$/, "/memories") : "";+ report.ok(`GET /api/v1/fs/ls viking://~/memories → 200${space ? ` (${space})` : ""}`);+ } else if (!fs.error) {+ const msg = serverErrorMessage(fs);+ if (fs.status === 403 && /ROOT/i.test(msg)) {+ report.fail("tenant data API rejects this key (root key)", msg, "use a user/admin key, not server.root_api_key");+ } else if (fs.status === 400) {+ report.warn(`GET /api/v1/fs/ls viking://~/memories → 400`, msg,+ /Trusted mode/i.test(msg) ? "set account/user for trusted mode" : "the server may be too old for the viking://~ home alias — upgrade the server");+ } else if (fs.status === 404) {+ report.info("viking://~/memories does not exist yet (nothing captured for this user so far)");+ } else if (fs.status !== 401) {+ report.warn(`GET /api/v1/fs/ls viking://~/memories → ${fs.status}`, msg);+ }+ }+ }++ const mcp = probes.mcp;+ if (mcp) {+ if (mcp.ok && mcp.json?.result?.tools) {+ report.ok(`POST /mcp tools/list → ${mcp.json.result.tools.length} tools`);+ } else if (mcp.error) {+ report.fail("POST /mcp failed", `${mcp.errorKind}: ${mcp.error}`);+ } else {+ const msg = serverErrorMessage(mcp) || mcp.text.replace(/\s+/g, " ").slice(0, 160);+ const hints = {+ 401: "credentials rejected on /mcp",+ 403: "key valid but not allowed on /mcp (root key in api_key mode)",+ 404: "no MCP endpoint at <url>/mcp — missing path prefix, old server, or a reverse proxy that does not forward /mcp",+ 406: "server did not accept the Accept header — something between client and server rewrites headers",+ 502: "reverse proxy cannot reach the upstream",+ 504: "reverse proxy timed out (SSE needs proxy_buffering off)",+ };+ report.fail(`POST /mcp tools/list → ${mcp.status}`, msg, hints[mcp.status] || "");+ }+ }+ return summary;+}++// ---------------------------------------------------------------------------+// State and logs+// ---------------------------------------------------------------------------++export function readStateFiles(stateDir, names) {+ const out = {};+ for (const name of names) {+ const path = `${stateDir}/${name}`;+ const entry = { path, exists: false, ageMs: null, data: null, error: "" };+ try {+ const st = statSync(path);+ entry.exists = true;+ entry.mtimeMs = st.mtimeMs;+ const data = JSON.parse(readFileSync(path, "utf-8"));+ entry.data = data;+ entry.ageMs = typeof data?.ts === "number" ? Date.now() - data.ts : Date.now() - st.mtimeMs;+ } catch (err) {+ if (entry.exists) entry.error = err?.message || String(err);+ }+ out[name] = entry;+ }+ return out;+}++export function countDirEntries(dir, filter = () => true) {+ try {+ return readdirSync(dir).filter(filter).length;+ } catch {+ return null;+ }+}++export function fileInfo(path) {+ try {+ const st = statSync(path);+ return { exists: true, size: st.size, mtimeMs: st.mtimeMs };+ } catch {+ return { exists: false, size: 0, mtimeMs: 0 };+ }+}++/**+ * Scan a JSONL hook log. Returns the last `maxErrors` error entries, the last+ * mcp-proxy start record, and which hooks have written anything.+ */+export function scanDebugLog(path, { maxErrors = 5, maxBytes = 512 * 1024 } = {}) {+ const out = { path, exists: false, size: 0, mtimeMs: 0, lines: 0, errors: [], proxyStart: null, hooks: [] };+ const info = fileInfo(path);+ if (!info.exists) return out;+ Object.assign(out, { exists: true, size: info.size, mtimeMs: info.mtimeMs });+ let text;+ try {+ text = readFileSync(path, "utf-8");+ } catch {+ return out;+ }+ if (text.length > maxBytes) text = text.slice(-maxBytes);+ const hooks = new Set();+ const errors = [];+ for (const line of text.split("\n")) {+ if (!line.trim()) continue;+ out.lines += 1;+ let entry;+ try {+ entry = JSON.parse(line);+ } catch {+ continue;+ }+ if (entry.hook) hooks.add(entry.hook);+ if (entry.hook === "mcp-proxy" && entry.stage === "start") out.proxyStart = entry;+ if (entry.error) {+ errors.push({ ts: entry.ts, hook: entry.hook, stage: entry.stage, message: entry.error?.message || String(entry.error) });+ }+ }+ // Only errors from the last day of logging are "recent"; older ones are+ // history that predates whatever the user is debugging now.+ const cutoff = out.mtimeMs - 24 * 60 * 60 * 1000;+ out.errors = errors.slice(-maxErrors);+ out.recentErrors = errors.filter((e) => Date.parse(e.ts || "") >= cutoff).slice(-maxErrors);+ out.hooks = [...hooks].sort();+ return out;+}++export function existsPath(path) {+ return Boolean(path) && existsSync(path);+}++// ---------------------------------------------------------------------------+// Server health+//+// `GET /ready` is the server's own verdict on its subsystems and works+// against any deployment. The port and ov.conf checks only apply when the+// server runs on this machine (loopback url). Everything else server-side —+// config validation, live embedding probe, native engine, disk — is+// `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" };+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",+ vectordb: "the vector index is unhealthy — check <storage.workspace>/vectordb and the server log; stop duplicate servers on the same workspace",+ agfs: "the content filesystem failed — check <storage.workspace>/viking, free disk space and the server log",+ api_key_manager: "the api key store failed to load — check <storage.workspace>/viking/_system and the server log",+ ollama: "start Ollama (or fix its host/port in ov.conf) — the server cannot reach it",+};++function isObject(v) {+ return Boolean(v) && typeof v === "object" && !Array.isArray(v);+}++/**+ * ov.conf keys that only the plugins read. The server validates its config+ * strictly and refuses to start on them, which shows up as "the server is+ * gone since I edited ov.conf". Returns [{ level, message, detail, fix }].+ */+export function lintServerConf(data) {+ const out = [];+ if (!isObject(data)) return out;+ for (const [key, dest] of Object.entries(PLUGIN_ONLY_OV_CONF_KEYS)) {+ if (!(key in data)) continue;+ out.push({+ level: "warn",+ message: `ov.conf has a top-level '${key}' block, which the server rejects at startup ("Unknown config field '${key}'")`,+ detail: "the plugin reads it, openviking-server does not; a server that is already running is unaffected until its next restart",+ fix: `move those settings to ${dest} (or OPENVIKING_* env) and delete the block; if this ov.conf never starts a server, ignore`,+ });+ }+ if (isObject(data.server) && "url" in data.server) {+ out.push({+ level: "warn",+ message: "ov.conf server.url is rejected by the server at startup (\"Extra inputs are not permitted\")",+ detail: "only the plugin and the CLI read server.url; the server validates its section strictly",+ fix: "put the url in ovcli.conf (url) and remove server.url; if this ov.conf never starts a server, ignore",+ });+ }+ return out;+}++/** Who listens on a TCP port (lsof on macOS/Linux, ss on Linux). */+export function findPortListener(port) {+ const out = { tool: "", pid: null, command: "", error: "" };+ if (process.platform === "win32") {+ out.error = "not supported on Windows";+ return out;+ }+ if (whichCommand("lsof")) {+ out.tool = "lsof";+ const r = runCommand("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-F", "pc"], { timeoutMs: 8000 });+ for (const line of r.stdout.split("\n")) {+ if (line.startsWith("p") && out.pid === null) out.pid = Number(line.slice(1));+ else if (line.startsWith("c") && !out.command) out.command = line.slice(1);+ }+ return out;+ }+ if (whichCommand("ss")) {+ out.tool = "ss";+ const r = runCommand("ss", ["-ltnpH", `sport = :${port}`], { timeoutMs: 8000 });+ const m = r.stdout.match(/users:\(\("([^"]+)",pid=(\d+)/);+ if (m) {+ out.command = m[1];+ out.pid = Number(m[2]);+ } else if (r.stdout.trim()) {+ out.command = "(owner not visible without root)";+ }+ return out;+ }+ out.error = "neither lsof nor ss is available";+ return out;+}++export async function probeReady(baseUrl, { timeoutMs = 15000 } = {}) {+ const base = String(baseUrl || "").replace(/\/+$/, "");+ return httpProbe({ url: `${base}/ready`, timeoutMs: Math.max(timeoutMs, 15000) });+}++/** Flatten one `/ready` check (string or {status, checks}) into { ok, text }. */+export function readyCheckState(value) {+ if (isObject(value)) {+ const status = String(value.status ?? "");+ const nested = isObject(value.checks) ? Object.entries(value.checks).map(([k, v]) => [k, readyCheckState(v)]) : [];+ const failed = nested.filter(([, s]) => !s.ok);+ return {+ ok: READY_OK_VALUES.has(status) && failed.length === 0,+ text: failed.length ? `${status} (${failed.map(([k, s]) => `${k}: ${s.text}`).join(", ")})` : status,+ };+ }+ const text = String(value ?? "");+ return { ok: READY_OK_VALUES.has(text), text };+}++/** Turn the `/ready` probe into findings. Returns { ready, checks } (ready null when unknown). */+export function assessReady(report, probe) {+ const out = { ready: null, checks: {} };+ if (!probe) return out;+ if (probe.error) {+ if (probe.errorKind === "timeout") report.warn(`GET /ready timed out after ${probe.latencyMs}ms`, "the readiness check embeds one token with the configured provider (10s cap) — a timeout usually means that provider hangs", "run `openviking-server doctor` in the server's environment to see the provider's reply");+ else report.info(`GET /ready failed: ${probe.error}`);+ return out;+ }+ if (probe.status === 404) {+ report.info("server has no /ready endpoint (older version) — subsystem status unavailable over HTTP", "`openviking-server doctor` in the server's environment covers embedding/VLM/storage");+ return out;+ }+ const json = probe.json;+ if (!isObject(json)) {+ report.info(`GET /ready → ${probe.status} without a JSON body`);+ return out;+ }+ if (probe.status === 503 && json.status === "not_ready" && json.reason === "initializing" && !isObject(json.checks)) {+ out.ready = false;+ report.warn("server is still initializing (503 /ready)", "storage and the embedder are being set up; the first start of a local embedding model downloads it", "wait and rerun; if it never finishes, read the server log");+ return out;+ }+ if (!isObject(json.checks)) {+ report.info(`GET /ready → ${probe.status}: ${JSON.stringify(json).slice(0, 200)}`);+ return out;+ }+ const states = Object.entries(json.checks).map(([k, v]) => [k, readyCheckState(v)]);+ out.checks = Object.fromEntries(states.map(([k, s]) => [k, s.text]));+ const failed = states.filter(([, s]) => !s.ok);+ out.ready = failed.length === 0 && probe.ok;+ const summary = states.map(([k, s]) => `${k} ${s.text}`).join(", ");+ if (out.ready) {+ report.ok(`/ready: ${summary}`);+ } else {+ for (const [key, s] of failed) report.fail(`/ready: ${key} → ${s.text}`, "", READY_FIXES[key] || "see the server log");+ if (!failed.length) report.warn(`/ready → ${probe.status}: ${summary}`, "", "read the server log");+ }+ return out;+}++function urlHostPort(baseUrl) {+ try {+ const u = new URL(baseUrl);+ return { host: u.host, port: Number(u.port || (u.protocol === "https:" ? 443 : 80)) };+ } catch {+ return null;+ }+}++/**+ * The "Server health" section. `health` is the /health probe already taken+ * for the Connection section; `ovConf` is inspectJsonFile(<ov.conf path>).+ */+export async function checkServerHealth(report, { baseUrl, ovConf, health, offline = false, timeoutMs = 5000 } = {}) {+ report.section("Server health");+ const answered = Boolean(health && !health.error && health.ok && isObject(health.json));+ const summary = { local: isLoopbackUrl(baseUrl), reachable: answered, ready: null, listener: null };+ const target = urlHostPort(baseUrl);++ if (!summary.local) {+ report.info(`server at ${target?.host || baseUrl} is not on this machine — only /ready is probed; \`openviking-server doctor\` on the server host covers the rest`);+ } else {+ if (ovConf?.ok) {+ for (const f of lintServerConf(ovConf.data)) report[f.level](f.message, f.detail, f.fix);+ }+ const listener = findPortListener(target.port);+ if (listener.pid) {+ summary.listener = { pid: listener.pid, command: listener.command };+ report.info(`port ${target.port} is served by pid ${listener.pid} (${listener.command})`);+ } else if (listener.error) {+ report.info(`could not determine who listens on port ${target.port} (${listener.error})`);+ } else if (!answered) {+ report.fail(`nothing listens on port ${target.port} — the server is not running`, "",+ "start it: `openviking-server` (first time: `openviking-server init`), or `docker start openviking` for a container install; a startup error is printed right there");+ }+ report.info("provider-level checks (embedding probe, VLM key, native engine, disk): `openviking-server doctor` in the server's own environment");+ }++ if (offline) report.info("skipped /ready (--offline)");+ else if (health?.json?.status === "pending_initialization") report.info("skipped /ready — the container has no config yet");+ else if (!answered) report.info("skipped /ready — the server did not answer /health");+ else summary.ready = assessReady(report, await probeReady(baseUrl, { timeoutMs })).ready;+ return summary;+}diff --git a/examples/memory-plugin-shared/sync.mjs b/examples/memory-plugin-shared/sync.mjsindex 88e8a2c5d..7316aed12 100644--- a/examples/memory-plugin-shared/sync.mjs+++ b/examples/memory-plugin-shared/sync.mjs@@ -22,6 +22,8 @@ const HARNESS_SHARED_FILES = ["uri-guard.mjs",];const OPENCODE_SHARED_FILES = [...HARNESS_SHARED_FILES, "mcp-proxy-core.mjs", "mcp-proxy-config.mjs", "async-writer.mjs", "batch-send.mjs"];+const DOCTOR_SHARED_FILES = [...OPENCODE_SHARED_FILES, "doctor-core.mjs"];+const ZCODE_SHARED_FILES = [...OPENCODE_SHARED_FILES, "agent-hook-runtime.mjs", "agent-uri-guard.mjs"];const DSH_SHARED_FILES = [...HARNESS_SHARED_FILES, "mcp-proxy-core.mjs", "mcp-proxy-config.mjs"];const AGENT_PLUGINS_SHARED_FILES = ["credentials.mjs",@@ -31,12 +33,12 @@ const AGENT_PLUGINS_SHARED_FILES = ["workspace-peer.mjs",];const TARGETS = [- { dir: join(ROOT, "examples", "claude-code-memory-plugin", "scripts", "shared"), files: OPENCODE_SHARED_FILES },- { dir: join(ROOT, "examples", "codex-memory-plugin", "scripts", "shared"), files: OPENCODE_SHARED_FILES },+ { 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: HARNESS_SHARED_FILES },- { dir: join(ROOT, "examples", "zcode-memory-plugin", "scripts", "shared") },+ { 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 },];diff --git a/examples/memory-plugin-shared/sync.test.mjs b/examples/memory-plugin-shared/sync.test.mjsindex 99c67a181..595605f1c 100644--- a/examples/memory-plugin-shared/sync.test.mjs+++ b/examples/memory-plugin-shared/sync.test.mjs@@ -19,6 +19,8 @@ const HARNESS_SHARED_FILES = ["uri-guard.mjs",];const OPENCODE_SHARED_FILES = [...HARNESS_SHARED_FILES, "mcp-proxy-core.mjs", "async-writer.mjs", "batch-send.mjs"];+const DOCTOR_SHARED_FILES = [...OPENCODE_SHARED_FILES, "doctor-core.mjs"];+const ZCODE_SHARED_FILES = [...OPENCODE_SHARED_FILES, "agent-hook-runtime.mjs", "agent-uri-guard.mjs"];const AGENT_PLUGINS_SHARED_FILES = ["credentials.mjs","debug-log.mjs",@@ -26,12 +28,12 @@ const AGENT_PLUGINS_SHARED_FILES = ["workspace-peer.mjs",];const TARGETS = [- { dir: join(ROOT, "examples", "claude-code-memory-plugin", "scripts", "shared"), files: OPENCODE_SHARED_FILES },- { dir: join(ROOT, "examples", "codex-memory-plugin", "scripts", "shared"), files: OPENCODE_SHARED_FILES },+ { 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: HARNESS_SHARED_FILES },{ dir: join(ROOT, "examples", "pi-coding-agent-extension", "shared"), files: HARNESS_SHARED_FILES },- { dir: join(ROOT, "examples", "zcode-memory-plugin", "scripts", "shared") },+ { 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 },];const GENERATED_HEADER = "// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.\n";