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(claude-code-plugin): add Claude Code memory plugin example (#903)
灿烂甜菜d1698fa53c03
diff --git a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json b/examples/claude-code-memory-plugin/.claude-plugin/plugin.jsonnew file mode 100644index 000000000..7b8db6e24--- /dev/null+++ b/examples/claude-code-memory-plugin/.claude-plugin/plugin.json@@ -0,0 +1,19 @@+{+ "name": "openviking-memory",+ "version": "0.1.0",+ "description": "Long-term semantic memory for Claude Code, powered by OpenViking. Auto-recall relevant memories at session start and capture important information during conversations.",+ "author": {+ "name": "OpenViking",+ "url": "https://github.com/volcengine/OpenViking"+ },+ "repository": "https://github.com/volcengine/OpenViking",+ "license": "Apache-2.0",+ "keywords": [+ "memory",+ "openviking",+ "semantic-search",+ "long-term-memory",+ "context-engine"+ ],+ "mcpServers": "./.mcp.json"+}diff --git a/examples/claude-code-memory-plugin/.gitignore b/examples/claude-code-memory-plugin/.gitignorenew file mode 100644index 000000000..d74551f99--- /dev/null+++ b/examples/claude-code-memory-plugin/.gitignore@@ -0,0 +1,5 @@+node_modules/+servers/*.mjs+servers/*.js+!servers/memory-server.js+*.tsbuildinfodiff --git a/examples/claude-code-memory-plugin/.mcp.json b/examples/claude-code-memory-plugin/.mcp.jsonnew file mode 100644index 000000000..d1646e53b--- /dev/null+++ b/examples/claude-code-memory-plugin/.mcp.json@@ -0,0 +1,9 @@+{+ "openviking-memory": {+ "command": "node",+ "args": ["${CLAUDE_PLUGIN_ROOT}/scripts/start-memory-server.mjs"],+ "env": {+ "OPENVIKING_CONFIG_FILE": "${OPENVIKING_CONFIG_FILE:-}"+ }+ }+}diff --git a/examples/claude-code-memory-plugin/MIGRATION.md b/examples/claude-code-memory-plugin/MIGRATION.mdnew file mode 100644index 000000000..4c635e9dc--- /dev/null+++ b/examples/claude-code-memory-plugin/MIGRATION.md@@ -0,0 +1,151 @@+# Migration Guide: claude-memory-plugin → claude-code-memory-plugin++This guide helps you migrate from the legacy `claude-memory-plugin` to the new `claude-code-memory-plugin`.++## Key Differences++| Aspect | Old Plugin (`claude-memory-plugin`) | New Plugin (`claude-code-memory-plugin`) |+|--------|--------------------------------------|-------------------------------------------|+| **Architecture** | Bash hooks + Python bridge (`ov_memory.py`) | Native MCP server + Node.js hooks |+| **Auto-Recall** | Skill-based, requires explicit invocation | Transparent, injected via `UserPromptSubmit` hook |+| **Memory Capture** | Accumulates on `Stop`, commits on `SessionEnd` (async) | Incremental capture on each `Stop` (sync, safer) |+| **Crash Safety** | Risk of losing accumulated turns if Claude crashes before `SessionEnd` | Each turn persisted independently — no data loss |+| **Type Safety** | Shell + Python, no compile-time checks | TypeScript MCP server, compiled JS artifact |+| **Tool Discovery** | Custom skill file | Standard MCP tools (`memory_recall`, `memory_store`, etc.) |+| **Config Scope** | Project-local (`./ov.conf`) | Global (`~/.openviking/ov.conf`) — works across all projects |+| **Runtime Bootstrap** | Manual setup required | Auto-bootstrap on first `SessionStart` into `${CLAUDE_PLUGIN_DATA}` |++### Why the New Model is Better++1. **Incremental Capture = Crash-Resilient**: The old approach batches all turns until `SessionEnd`. If Claude crashes or the user kills the session, those memories are lost. The new plugin extracts on every `Stop`, so each turn is independently persisted.++2. **Transparent Auto-Recall**: No skill invocation needed — memories are automatically injected into context via `systemMessage` on every prompt. This matches the mental model of "memory just works."++3. **MCP Native**: Standard protocol, better tooling support, type-safe TypeScript implementation. Other MCP-compatible clients can potentially reuse the same server.++4. **Global Configuration**: One config file for all projects (`~/.openviking/ov.conf`), not per-project `./ov.conf` files.++## Capture Strategy: User Messages Only by Default++One design choice worth explaining in detail:++### Why Auto-Capture User Messages Only++In practice, auto-capturing assistant turns in coding scenarios has proven problematic:++1. **VLM Token Cost**: Each capture triggers an LLM extraction call to OpenViking. Capturing every assistant turn (including tool calls, sub-agent outputs, etc.) quickly becomes expensive.++2. **Signal-to-Noise Ratio**: Claude Code's assistant messages often contain verbose tool outputs, file contents, and nested sub-agent traces. These rarely contain memorable personal context — the valuable signal is typically in the *user's* questions, decisions, and stated preferences.++3. **Coding Workflow Nature**: For coding tasks, "memory" is often about:+ - User preferences ("use tabs not spaces", "prefer arrow functions")+ - Project context ("this repo uses bun, not npm")+ - Decisions made ("let's skip the refactor for now")++ These almost always originate from the *user*, not the assistant.++### Current Default++The plugin defaults to `captureAssistantTurns: false` — only user messages are considered for auto-capture. This keeps token usage manageable while still preserving the most valuable context.++Users can opt-in to full capture by setting `"captureAssistantTurns": true` in their `ov.conf` if they want assistant turns included (e.g., for non-coding workflows where assistant insights matter).++## Migration Steps++### 1. Update Config Location++Move your config from project root to the global location:++```bash+# Old location (per-project)+./ov.conf++# New location (global)+~/.openviking/ov.conf+```++If you have project-specific configs, merge them into the global config. The new plugin supports a `claude_code` section for plugin-specific overrides.++### 2. Install Node.js Runtime++The new plugin requires Node.js. Ensure Node.js 18+ is installed:++```bash+node --version # Should be 18.x or higher+```++### 3. Remove Old Plugin, Install New Plugin++```bash+# Uninstall old plugin (if installed via marketplace)+/plugin uninstall openviking-memory++# Install new plugin+/plugin marketplace add Castor6/openviking-plugins+/plugin install claude-code-memory-plugin@openviking-plugin+```++### 4. Remove Per-Project Plugin Files++Delete the old plugin directory from your project if it was checked in:++```bash+rm -rf ./.openviking/memory/+```++### 5. Update Config File (Optional)++Add the `claude_code` section to `~/.openviking/ov.conf` for plugin-specific settings:++```json+{+ "claude_code": {+ "agentId": "claude-code",+ "recallLimit": 6,+ "captureMode": "semantic",+ "captureTimeoutMs": 30000,+ "captureAssistantTurns": false+ }+}+```++## Behavior Changes++### Memory Recall++| Old Plugin | New Plugin |+|------------|------------|+| Run `/memory-recall <query>` manually | Automatic recall on every prompt |+| Skill-based, requires Claude tool call | Transparent, injected as system context |++The new plugin automatically injects relevant memories into the context before each prompt. No manual action needed.++### Memory Capture++| Old Plugin | New Plugin |+|------------|------------|+| Captures at `SessionEnd` (batch) | Captures at `Stop` (incremental) |+| Requires explicit commit | Automatic, real-time |++The new plugin captures memories incrementally after each turn, providing faster feedback and better persistence.++## MCP Tools (New Feature)++The new plugin provides MCP tools for explicit memory operations:++| Tool | Description |+|------|-------------|+| `memory_recall` | Manual semantic search |+| `memory_store` | Manually store a memory |+| `memory_forget` | Delete memories by URI or query |+| `memory_health` | Check server status |++These tools are available when you need explicit control over memory operations.++## Troubleshooting++| Issue | Solution |+|-------|----------|+| MCP tools not available | Start a new Claude session; first run installs runtime deps |+| No memories recalled | Ensure OpenViking server is running: `openviking-server` |+| Hook timeout | Increase timeout in `hooks/hooks.json` |diff --git a/examples/claude-code-memory-plugin/README.md b/examples/claude-code-memory-plugin/README.mdnew file mode 100644index 000000000..5f0b87191--- /dev/null+++ b/examples/claude-code-memory-plugin/README.md@@ -0,0 +1,310 @@+# OpenViking Memory Plugin for Claude Code++Long-term semantic memory for Claude Code, powered by [OpenViking](https://github.com/volcengine/OpenViking).++> Ported from the [OpenClaw context-engine plugin](../openclaw-plugin/) and adapted for Claude Code's plugin architecture (MCP + hooks).++## Architecture++```+┌──────────────────────────────────────────────────────────────────┐+│ Claude Code │+└────────┬──────────────────────────────────────┬──────────────────┘+ │ │+ UserPromptSubmit Stop+ (command hook) (command hook)+ │ │+ ┌──────▼──────────┐ ┌────────▼─────────┐+ │ auto-recall.mjs│ │ auto-capture.mjs │+ │ │ │ │+ │ stdin: │ │ stdin: │+ │ user_prompt │ │ transcript_path │+ │ │ │ │+ │ 1. parse query │ │ 1. read transcript│+ │ 2. search OV │ │ 2. extract turns │+ │ 3. rank & pick │ │ 3. capture check │+ │ 4. read content │ │ 4. session/extract│+ │ │ │ │+ │ stdout: │ │ stdout: │+ │ systemMessage │ │ decision:approve│+ │ (memories) │ │ (auto-captured) │+ └──────┬──────────┘ └────────┬─────────┘+ │ │+ │ ┌──────────────┐ │+ └────────►│ OpenViking │◄────────────┘+ │ Server │+ MCP tools ────►│ (Python) │+ └──────────────┘++ ┌──────────────────────────────────────┐+ │ MCP Server (memory-server.ts) │+ │ Tools for explicit use: │+ │ • memory_recall (manual search) │+ │ • memory_store (manual store) │+ │ • memory_forget (delete memories) │+ │ • memory_health (health check) │+ └──────────────────────────────────────┘+```++On `SessionStart`, the plugin bootstraps its Node runtime into `${CLAUDE_PLUGIN_DATA}/runtime`+when Claude exposes that variable. If not, it falls back to `~/.openviking/claude-code-memory-plugin/runtime`.+That makes the MCP adapter self-healing across marketplace installs without checking `node_modules`+into the plugin source tree.++## How It Works++### Runtime Bootstrap (transparent, on session start)++1. Claude starts a session → `SessionStart` hook fires+2. `bootstrap-runtime.mjs` hashes `package.json`, `package-lock.json`, and `servers/memory-server.js`+3. If the runtime directory is missing or stale, it copies runtime files there+4. Runs `npm ci --omit=dev` in that runtime directory+5. Writes `install-state.json` so later sessions can skip reinstall+6. MCP launcher can also bootstrap on demand if it starts before `SessionStart`++### Auto-Recall (transparent, every turn)++1. User submits a message → `UserPromptSubmit` hook fires+2. `auto-recall.mjs` reads `user_prompt` from stdin+3. Calls OpenViking `/api/v1/search/find` for both `viking://user/memories` and `viking://agent/memories`+4. Ranks results with query-aware scoring (leaf boost, preference boost, temporal boost, lexical overlap)+5. Reads full content for top-ranked leaf memories+6. Returns via `systemMessage` → Claude sees `<relevant-memories>` context transparently++### Auto-Capture (transparent, on stop)++1. Claude finishes a response → `Stop` hook fires+2. `auto-capture.mjs` reads `transcript_path` from stdin+3. Parses transcript and extracts recent turns, then keeps user turns only by default+4. Runs capture decision logic (semantic mode or keyword triggers) on the selected user turns+5. Creates OpenViking temp session → adds message → extracts memories+6. Memories stored automatically, no Claude tool call needed++### MCP Tools (explicit, on-demand)++The MCP server provides tools for when Claude or the user needs explicit memory operations:+- **memory_recall** — manual semantic search+- **memory_store** — manual memory storage+- **memory_forget** — delete memories by URI or query+- **memory_health** — check server status++## What's Different from the OpenClaw Plugin?++| Aspect | OpenClaw Plugin | Claude Code Plugin |+|--------|----------------|-------------------|+| Auto-recall | `before_prompt_build` hook + `prependContext` | `UserPromptSubmit` command hook + `systemMessage` |+| Auto-capture | `afterTurn` context-engine method | `Stop` command hook + transcript parsing |+| Explicit tools | `api.registerTool()` | MCP server (stdio transport) |+| Transparency | Both fully transparent | Both fully transparent — no extra Claude tool calls |+| Process mgmt | Plugin manages local subprocess | User starts OpenViking separately |+| Config | Plugin config schema with UI hints | Single JSON config file |+| JS runtime deps | Bundled in plugin process | Installed on first `SessionStart` into `${CLAUDE_PLUGIN_DATA}` or `~/.openviking/claude-code-memory-plugin` |++## Quick Start++### 1. Install OpenViking++```bash+pip install openviking+```++For mac+```bash+brew install pipx+pipx ensurepath+pipx install openviking+```++### 2. Create Config++If you don't already have `~/.openviking/ov.conf`, create it:++```bash+mkdir -p ~/.openviking+# Edit ov.conf: set your embedding API key, model, etc.+vim ~/.openviking/ov.conf+```++#### `~/.openviking/ov.conf` (Local Mode)++```json+{+ "server": { "host": "127.0.0.1", "port": 1933 },+ "storage": {+ "workspace": "/home/yourname/.openviking/data",+ "vectordb": { "backend": "local" },+ "agfs": { "backend": "local", "port": 1833 }+ },+ "embedding": {+ "dense": {+ "provider": "volcengine",+ "api_key": "<your-ark-api-key>",+ "model": "doubao-embedding-vision-251215",+ "api_base": "https://ark.cn-beijing.volces.com/api/v3",+ "dimension": 1024,+ "input": "multimodal"+ }+ },+ "vlm": {+ "provider": "volcengine",+ "api_key": "<your-ark-api-key>",+ "model": "doubao-seed-2-0-pro-260215",+ "api_base": "https://ark.cn-beijing.volces.com/api/v3"+ }+}+```++> `root_api_key`: Once set, all HTTP requests must carry the `X-API-Key` header. Defaults to `null` in local mode (authentication disabled).++Optionally add a `claude_code` section for plugin-specific overrides:++```json+{+ "claude_code": {+ "agentId": "claude-code",+ "recallLimit": 6,+ "captureMode": "semantic",+ "captureTimeoutMs": 30000,+ "captureAssistantTurns": false,+ "logRankingDetails": false+ }+}+```++### 3. Start OpenViking++```bash+openviking-server+```++### 4. Install Plugin++```bash+/plugin marketplace add Castor6/openviking-plugins+/plugin install claude-code-memory-plugin@openviking-plugin+```++### 5. Start a New Claude Session++```bash+claude+```++The first session automatically prepares the Node runtime for the MCP adapter. By default it uses+`${CLAUDE_PLUGIN_DATA}/runtime`, and falls back to `~/.openviking/claude-code-memory-plugin/runtime`+if Claude does not inject `CLAUDE_PLUGIN_DATA`. No manual `npm install` is required after marketplace install.++## Configuration++Uses the same `~/.openviking/ov.conf` as the OpenViking server and OpenClaw plugin.++Override the path via environment variable:+```bash+export OPENVIKING_CONFIG_FILE="~/custom/path/ov.conf"+```++**Connection info** is read from ov.conf's `server` section:++| ov.conf field | Used as | Description |+|---------------|---------|-------------|+| `server.host` + `server.port` | `baseUrl` | Derives `http://{host}:{port}` |+| `server.root_api_key` | `apiKey` | API key for authentication |++**Plugin overrides** go in an optional `claude_code` section:++| Field | Default | Description |+|-------|---------|-------------|+| `agentId` | `claude-code` | Agent identity for memory isolation |+| `timeoutMs` | `15000` | HTTP request timeout for recall/general requests (ms) |+| `autoRecall` | `true` | Enable auto-recall on every user prompt |+| `recallLimit` | `6` | Max memories to inject per turn |+| `scoreThreshold` | `0.01` | Min relevance score (0-1) |+| `minQueryLength` | `3` | Skip recall for very short queries |+| `logRankingDetails` | `false` | Emit per-candidate `ranking_detail` logs for recall; otherwise only log a compact ranking summary |+| `autoCapture` | `true` | Enable auto-capture on stop |+| `captureMode` | `semantic` | `semantic` (always capture) or `keyword` (trigger-based) |+| `captureMaxLength` | `24000` | Max text length for capture |+| `captureTimeoutMs` | `30000` | HTTP request timeout for auto-capture requests (ms) |+| `captureAssistantTurns` | `false` | Include assistant turns in auto-capture input; default is user-only capture |++## Hook Timeouts++The bundled hooks are intentionally asymmetric:++| Hook | Default timeout | Notes |+|------|-----------------|-------|+| `SessionStart` | `120s` | First session may need time to install runtime dependencies into `${CLAUDE_PLUGIN_DATA}` |+| `UserPromptSubmit` | `8s` | Auto-recall should stay fast so prompt submission is not blocked |+| `Stop` | `45s` | Gives auto-capture enough room to finish and persist incremental state |++Keep `claude_code.captureTimeoutMs` lower than the `Stop` hook timeout so the script can fail gracefully and still update its incremental state.++## Debug Logging++When `claude_code.debug` or `OPENVIKING_DEBUG=1` is enabled, hook logs are written to `~/.openviking/logs/cc-hooks.log`.++- `auto-recall` now logs key stages plus a compact `ranking_summary` by default.+- Set `claude_code.logRankingDetails=true` only when you need per-candidate scoring logs.+- For deep diagnosis, prefer the standalone scripts `scripts/debug-recall.mjs` and `scripts/debug-capture.mjs` instead of leaving verbose hook logging on all the time.++## Runtime Dependency Bootstrap++The plugin keeps its runtime npm dependencies in a dedicated runtime directory:++- Prefers `${CLAUDE_PLUGIN_DATA}/runtime` and falls back to `~/.openviking/claude-code-memory-plugin/runtime`+- `SessionStart` installs or refreshes dependencies with `npm ci --omit=dev`+- `install-state.json` records the active manifest and server hashes+- MCP startup can also perform the same bootstrap itself, so first-run installs do not depend on hook ordering+- If installation fails, Claude Code remains usable; only the explicit MCP tools stay unavailable until the next successful bootstrap++## Plugin Structure++```+claude-code-memory-plugin/+├── .claude-plugin/+│ └── plugin.json # Plugin manifest+├── hooks/+│ └── hooks.json # SessionStart + UserPromptSubmit + Stop hooks+├── scripts/+│ ├── config.mjs # Shared config loader+│ ├── runtime-common.mjs # Shared runtime paths + install state helpers+│ ├── bootstrap-runtime.mjs # SessionStart installer for runtime deps+│ ├── start-memory-server.mjs # Launches MCP server from plugin data runtime+│ ├── auto-recall.mjs # Auto-recall hook script+│ └── auto-capture.mjs # Auto-capture hook script+├── servers/+│ └── memory-server.js # Compiled MCP server+├── src/+│ └── memory-server.ts # MCP server source+├── .mcp.json # MCP server definition+├── package.json+├── tsconfig.json+└── README.md+```++## Relationship to Claude Code's Built-in Memory++Claude Code has a built-in auto-memory system using `MEMORY.md` files. This plugin **complements** that system:++| Feature | Built-in Memory | OpenViking Plugin |+|---------|----------------|-------------------|+| Storage | Flat markdown files | Vector DB + structured extraction |+| Search | Loaded into context entirely | Semantic similarity search |+| Scope | Per-project | Cross-project, cross-session |+| Capacity | ~200 lines (context limit) | Unlimited (server-side storage) |+| Extraction | Manual rules | AI-powered entity extraction |++## Troubleshooting++| Symptom | Cause | Solution |+|---------|-------|----------|+| No memories recalled | Server not running | Start OpenViking server |+| Auto-capture extracts 0 | Wrong API key / model | Check `ov.conf` embedding config |+| MCP tools not available | First-run runtime install failed | Start a new Claude session to retry bootstrap and inspect SessionStart stderr for the npm failure |+| Repeated auto-capture of old context | `Stop` hook timed out before incremental state was saved | Keep `captureAssistantTurns=false`, raise the `Stop` hook timeout, and keep `captureTimeoutMs` below that hook timeout |+| Hook timeout | Server slow / unreachable | Increase the `Stop` hook timeout in `hooks/hooks.json` and tune `claude_code.captureTimeoutMs` in `ov.conf` |+| Logs too verbose | Detailed recall ranking logs are enabled | Leave `logRankingDetails=false` for normal use and use the debug scripts for one-off inspection |++## License++Apache-2.0 — same as [OpenViking](https://github.com/volcengine/OpenViking).diff --git a/examples/claude-code-memory-plugin/hooks/hooks.json b/examples/claude-code-memory-plugin/hooks/hooks.jsonnew file mode 100644index 000000000..fb522dfbc--- /dev/null+++ b/examples/claude-code-memory-plugin/hooks/hooks.json@@ -0,0 +1,39 @@+{+ "hooks": {+ "SessionStart": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/bootstrap-runtime.mjs",+ "timeout": 120+ }+ ]+ }+ ],+ "UserPromptSubmit": [+ {+ "matcher": "",+ "hooks": [+ {+ "type": "command",+ "command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/auto-recall.mjs",+ "timeout": 8+ }+ ]+ }+ ],+ "Stop": [+ {+ "matcher": "",+ "hooks": [+ {+ "type": "command",+ "command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/auto-capture.mjs",+ "timeout": 45+ }+ ]+ }+ ]+ }+}diff --git a/examples/claude-code-memory-plugin/package-lock.json b/examples/claude-code-memory-plugin/package-lock.jsonnew file mode 100644index 000000000..cd9009ba2--- /dev/null+++ b/examples/claude-code-memory-plugin/package-lock.json@@ -0,0 +1,1174 @@+{+ "name": "claude-code-openviking-memory",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "claude-code-openviking-memory",+ "version": "0.1.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.12.1",+ "zod": "^4.3.6"+ },+ "devDependencies": {+ "@types/node": "^22.0.0",+ "typescript": "^5.7.0"+ }+ },+ "node_modules/@hono/node-server": {+ "version": "1.19.11",+ "resolved": "https://registry.npmmirror.com/@hono/node-server/-/node-server-1.19.11.tgz",+ "integrity": "sha512-dr8/3zEaB+p0D2n/IUrlPF1HZm586qgJNXK1a9fhg/PzdtkK7Ksd5l312tJX2yBuALqDYBlG20QEbayqPyxn+g==",+ "license": "MIT",+ "engines": {+ "node": ">=18.14.1"+ },+ "peerDependencies": {+ "hono": "^4"+ }+ },+ "node_modules/@modelcontextprotocol/sdk": {+ "version": "1.27.1",+ "resolved": "https://registry.npmmirror.com/@modelcontextprotocol/sdk/-/sdk-1.27.1.tgz",+ "integrity": "sha512-sr6GbP+4edBwFndLbM60gf07z0FQ79gaExpnsjMGePXqFcSSb7t6iscpjk9DhFhwd+mTEQrzNafGP8/iGGFYaA==",+ "license": "MIT",+ "dependencies": {+ "@hono/node-server": "^1.19.9",+ "ajv": "^8.17.1",+ "ajv-formats": "^3.0.1",+ "content-type": "^1.0.5",+ "cors": "^2.8.5",+ "cross-spawn": "^7.0.5",+ "eventsource": "^3.0.2",+ "eventsource-parser": "^3.0.0",+ "express": "^5.2.1",+ "express-rate-limit": "^8.2.1",+ "hono": "^4.11.4",+ "jose": "^6.1.3",+ "json-schema-typed": "^8.0.2",+ "pkce-challenge": "^5.0.0",+ "raw-body": "^3.0.0",+ "zod": "^3.25 || ^4.0",+ "zod-to-json-schema": "^3.25.1"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@cfworker/json-schema": "^4.1.1",+ "zod": "^3.25 || ^4.0"+ },+ "peerDependenciesMeta": {+ "@cfworker/json-schema": {+ "optional": true+ },+ "zod": {+ "optional": false+ }+ }+ },+ "node_modules/@types/node": {+ "version": "22.19.15",+ "resolved": "https://registry.npmmirror.com/@types/node/-/node-22.19.15.tgz",+ "integrity": "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": "~6.21.0"+ }+ },+ "node_modules/accepts": {+ "version": "2.0.0",+ "resolved": "https://registry.npmmirror.com/accepts/-/accepts-2.0.0.tgz",+ "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",+ "license": "MIT",+ "dependencies": {+ "mime-types": "^3.0.0",+ "negotiator": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/ajv": {+ "version": "8.18.0",+ "resolved": "https://registry.npmmirror.com/ajv/-/ajv-8.18.0.tgz",+ "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3",+ "fast-uri": "^3.0.1",+ "json-schema-traverse": "^1.0.0",+ "require-from-string": "^2.0.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/epoberezkin"+ }+ },+ "node_modules/ajv-formats": {+ "version": "3.0.1",+ "resolved": "https://registry.npmmirror.com/ajv-formats/-/ajv-formats-3.0.1.tgz",+ "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",+ "license": "MIT",+ "dependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependenciesMeta": {+ "ajv": {+ "optional": true+ }+ }+ },+ "node_modules/body-parser": {+ "version": "2.2.2",+ "resolved": "https://registry.npmmirror.com/body-parser/-/body-parser-2.2.2.tgz",+ "integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==",+ "license": "MIT",+ "dependencies": {+ "bytes": "^3.1.2",+ "content-type": "^1.0.5",+ "debug": "^4.4.3",+ "http-errors": "^2.0.0",+ "iconv-lite": "^0.7.0",+ "on-finished": "^2.4.1",+ "qs": "^6.14.1",+ "raw-body": "^3.0.1",+ "type-is": "^2.0.1"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/bytes": {+ "version": "3.1.2",+ "resolved": "https://registry.npmmirror.com/bytes/-/bytes-3.1.2.tgz",+ "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/call-bind-apply-helpers": {+ "version": "1.0.2",+ "resolved": "https://registry.npmmirror.com/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/call-bound": {+ "version": "1.0.4",+ "resolved": "https://registry.npmmirror.com/call-bound/-/call-bound-1.0.4.tgz",+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "get-intrinsic": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/content-disposition": {+ "version": "1.0.1",+ "resolved": "https://registry.npmmirror.com/content-disposition/-/content-disposition-1.0.1.tgz",+ "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/content-type": {+ "version": "1.0.5",+ "resolved": "https://registry.npmmirror.com/content-type/-/content-type-1.0.5.tgz",+ "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/cookie": {+ "version": "0.7.2",+ "resolved": "https://registry.npmmirror.com/cookie/-/cookie-0.7.2.tgz",+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/cookie-signature": {+ "version": "1.2.2",+ "resolved": "https://registry.npmmirror.com/cookie-signature/-/cookie-signature-1.2.2.tgz",+ "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",+ "license": "MIT",+ "engines": {+ "node": ">=6.6.0"+ }+ },+ "node_modules/cors": {+ "version": "2.8.6",+ "resolved": "https://registry.npmmirror.com/cors/-/cors-2.8.6.tgz",+ "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",+ "license": "MIT",+ "dependencies": {+ "object-assign": "^4",+ "vary": "^1"+ },+ "engines": {+ "node": ">= 0.10"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/cross-spawn": {+ "version": "7.0.6",+ "resolved": "https://registry.npmmirror.com/cross-spawn/-/cross-spawn-7.0.6.tgz",+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.1.0",+ "shebang-command": "^2.0.0",+ "which": "^2.0.1"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmmirror.com/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/depd": {+ "version": "2.0.0",+ "resolved": "https://registry.npmmirror.com/depd/-/depd-2.0.0.tgz",+ "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/dunder-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmmirror.com/dunder-proto/-/dunder-proto-1.0.1.tgz",+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.1",+ "es-errors": "^1.3.0",+ "gopd": "^1.2.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/ee-first": {+ "version": "1.1.1",+ "resolved": "https://registry.npmmirror.com/ee-first/-/ee-first-1.1.1.tgz",+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",+ "license": "MIT"+ },+ "node_modules/encodeurl": {+ "version": "2.0.0",+ "resolved": "https://registry.npmmirror.com/encodeurl/-/encodeurl-2.0.0.tgz",+ "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/es-define-property": {+ "version": "1.0.1",+ "resolved": "https://registry.npmmirror.com/es-define-property/-/es-define-property-1.0.1.tgz",+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-errors": {+ "version": "1.3.0",+ "resolved": "https://registry.npmmirror.com/es-errors/-/es-errors-1.3.0.tgz",+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-object-atoms": {+ "version": "1.1.1",+ "resolved": "https://registry.npmmirror.com/es-object-atoms/-/es-object-atoms-1.1.1.tgz",+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/escape-html": {+ "version": "1.0.3",+ "resolved": "https://registry.npmmirror.com/escape-html/-/escape-html-1.0.3.tgz",+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",+ "license": "MIT"+ },+ "node_modules/etag": {+ "version": "1.8.1",+ "resolved": "https://registry.npmmirror.com/etag/-/etag-1.8.1.tgz",+ "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/eventsource": {+ "version": "3.0.7",+ "resolved": "https://registry.npmmirror.com/eventsource/-/eventsource-3.0.7.tgz",+ "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",+ "license": "MIT",+ "dependencies": {+ "eventsource-parser": "^3.0.1"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/eventsource-parser": {+ "version": "3.0.6",+ "resolved": "https://registry.npmmirror.com/eventsource-parser/-/eventsource-parser-3.0.6.tgz",+ "integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/express": {+ "version": "5.2.1",+ "resolved": "https://registry.npmmirror.com/express/-/express-5.2.1.tgz",+ "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",+ "license": "MIT",+ "dependencies": {+ "accepts": "^2.0.0",+ "body-parser": "^2.2.1",+ "content-disposition": "^1.0.0",+ "content-type": "^1.0.5",+ "cookie": "^0.7.1",+ "cookie-signature": "^1.2.1",+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "finalhandler": "^2.1.0",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.0",+ "merge-descriptors": "^2.0.0",+ "mime-types": "^3.0.0",+ "on-finished": "^2.4.1",+ "once": "^1.4.0",+ "parseurl": "^1.3.3",+ "proxy-addr": "^2.0.7",+ "qs": "^6.14.0",+ "range-parser": "^1.2.1",+ "router": "^2.2.0",+ "send": "^1.1.0",+ "serve-static": "^2.2.0",+ "statuses": "^2.0.1",+ "type-is": "^2.0.1",+ "vary": "^1.1.2"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/express-rate-limit": {+ "version": "8.3.1",+ "resolved": "https://registry.npmmirror.com/express-rate-limit/-/express-rate-limit-8.3.1.tgz",+ "integrity": "sha512-D1dKN+cmyPWuvB+G2SREQDzPY1agpBIcTa9sJxOPMCNeH3gwzhqJRDWCXW3gg0y//+LQ/8j52JbMROWyrKdMdw==",+ "license": "MIT",+ "dependencies": {+ "ip-address": "10.1.0"+ },+ "engines": {+ "node": ">= 16"+ },+ "funding": {+ "url": "https://github.com/sponsors/express-rate-limit"+ },+ "peerDependencies": {+ "express": ">= 4.11"+ }+ },+ "node_modules/fast-deep-equal": {+ "version": "3.1.3",+ "resolved": "https://registry.npmmirror.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",+ "license": "MIT"+ },+ "node_modules/fast-uri": {+ "version": "3.1.0",+ "resolved": "https://registry.npmmirror.com/fast-uri/-/fast-uri-3.1.0.tgz",+ "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/fastify"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fastify"+ }+ ],+ "license": "BSD-3-Clause"+ },+ "node_modules/finalhandler": {+ "version": "2.1.1",+ "resolved": "https://registry.npmmirror.com/finalhandler/-/finalhandler-2.1.1.tgz",+ "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "on-finished": "^2.4.1",+ "parseurl": "^1.3.3",+ "statuses": "^2.0.1"+ },+ "engines": {+ "node": ">= 18.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/forwarded": {+ "version": "0.2.0",+ "resolved": "https://registry.npmmirror.com/forwarded/-/forwarded-0.2.0.tgz",+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/fresh": {+ "version": "2.0.0",+ "resolved": "https://registry.npmmirror.com/fresh/-/fresh-2.0.0.tgz",+ "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/function-bind": {+ "version": "1.1.2",+ "resolved": "https://registry.npmmirror.com/function-bind/-/function-bind-1.1.2.tgz",+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-intrinsic": {+ "version": "1.3.0",+ "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.3.0.tgz",+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "es-define-property": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "function-bind": "^1.1.2",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "has-symbols": "^1.1.0",+ "hasown": "^2.0.2",+ "math-intrinsics": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmmirror.com/get-proto/-/get-proto-1.0.1.tgz",+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",+ "license": "MIT",+ "dependencies": {+ "dunder-proto": "^1.0.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/gopd": {+ "version": "1.2.0",+ "resolved": "https://registry.npmmirror.com/gopd/-/gopd-1.2.0.tgz",+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-symbols": {+ "version": "1.1.0",+ "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.1.0.tgz",+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/hasown": {+ "version": "2.0.2",+ "resolved": "https://registry.npmmirror.com/hasown/-/hasown-2.0.2.tgz",+ "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",+ "license": "MIT",+ "dependencies": {+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/hono": {+ "version": "4.12.8",+ "resolved": "https://registry.npmmirror.com/hono/-/hono-4.12.8.tgz",+ "integrity": "sha512-VJCEvtrezO1IAR+kqEYnxUOoStaQPGrCmX3j4wDTNOcD1uRPFpGlwQUIW8niPuvHXaTUxeOUl5MMDGrl+tmO9A==",+ "license": "MIT",+ "engines": {+ "node": ">=16.9.0"+ }+ },+ "node_modules/http-errors": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/http-errors/-/http-errors-2.0.1.tgz",+ "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",+ "license": "MIT",+ "dependencies": {+ "depd": "~2.0.0",+ "inherits": "~2.0.4",+ "setprototypeof": "~1.2.0",+ "statuses": "~2.0.2",+ "toidentifier": "~1.0.1"+ },+ "engines": {+ "node": ">= 0.8"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/iconv-lite": {+ "version": "0.7.2",+ "resolved": "https://registry.npmmirror.com/iconv-lite/-/iconv-lite-0.7.2.tgz",+ "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==",+ "license": "MIT",+ "dependencies": {+ "safer-buffer": ">= 2.1.2 < 3.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/inherits": {+ "version": "2.0.4",+ "resolved": "https://registry.npmmirror.com/inherits/-/inherits-2.0.4.tgz",+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",+ "license": "ISC"+ },+ "node_modules/ip-address": {+ "version": "10.1.0",+ "resolved": "https://registry.npmmirror.com/ip-address/-/ip-address-10.1.0.tgz",+ "integrity": "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==",+ "license": "MIT",+ "engines": {+ "node": ">= 12"+ }+ },+ "node_modules/ipaddr.js": {+ "version": "1.9.1",+ "resolved": "https://registry.npmmirror.com/ipaddr.js/-/ipaddr.js-1.9.1.tgz",+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/is-promise": {+ "version": "4.0.0",+ "resolved": "https://registry.npmmirror.com/is-promise/-/is-promise-4.0.0.tgz",+ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",+ "license": "MIT"+ },+ "node_modules/isexe": {+ "version": "2.0.0",+ "resolved": "https://registry.npmmirror.com/isexe/-/isexe-2.0.0.tgz",+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",+ "license": "ISC"+ },+ "node_modules/jose": {+ "version": "6.2.2",+ "resolved": "https://registry.npmmirror.com/jose/-/jose-6.2.2.tgz",+ "integrity": "sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/panva"+ }+ },+ "node_modules/json-schema-traverse": {+ "version": "1.0.0",+ "resolved": "https://registry.npmmirror.com/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",+ "license": "MIT"+ },+ "node_modules/json-schema-typed": {+ "version": "8.0.2",+ "resolved": "https://registry.npmmirror.com/json-schema-typed/-/json-schema-typed-8.0.2.tgz",+ "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",+ "license": "BSD-2-Clause"+ },+ "node_modules/math-intrinsics": {+ "version": "1.1.0",+ "resolved": "https://registry.npmmirror.com/math-intrinsics/-/math-intrinsics-1.1.0.tgz",+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/media-typer": {+ "version": "1.1.0",+ "resolved": "https://registry.npmmirror.com/media-typer/-/media-typer-1.1.0.tgz",+ "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/merge-descriptors": {+ "version": "2.0.0",+ "resolved": "https://registry.npmmirror.com/merge-descriptors/-/merge-descriptors-2.0.0.tgz",+ "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/mime-db": {+ "version": "1.54.0",+ "resolved": "https://registry.npmmirror.com/mime-db/-/mime-db-1.54.0.tgz",+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mime-types": {+ "version": "3.0.2",+ "resolved": "https://registry.npmmirror.com/mime-types/-/mime-types-3.0.2.tgz",+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "^1.54.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },+ "node_modules/negotiator": {+ "version": "1.0.0",+ "resolved": "https://registry.npmmirror.com/negotiator/-/negotiator-1.0.0.tgz",+ "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/object-assign": {+ "version": "4.1.1",+ "resolved": "https://registry.npmmirror.com/object-assign/-/object-assign-4.1.1.tgz",+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/object-inspect": {+ "version": "1.13.4",+ "resolved": "https://registry.npmmirror.com/object-inspect/-/object-inspect-1.13.4.tgz",+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/on-finished": {+ "version": "2.4.1",+ "resolved": "https://registry.npmmirror.com/on-finished/-/on-finished-2.4.1.tgz",+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",+ "license": "MIT",+ "dependencies": {+ "ee-first": "1.1.1"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/once": {+ "version": "1.4.0",+ "resolved": "https://registry.npmmirror.com/once/-/once-1.4.0.tgz",+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",+ "license": "ISC",+ "dependencies": {+ "wrappy": "1"+ }+ },+ "node_modules/parseurl": {+ "version": "1.3.3",+ "resolved": "https://registry.npmmirror.com/parseurl/-/parseurl-1.3.3.tgz",+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/path-key": {+ "version": "3.1.1",+ "resolved": "https://registry.npmmirror.com/path-key/-/path-key-3.1.1.tgz",+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/path-to-regexp": {+ "version": "8.3.0",+ "resolved": "https://registry.npmmirror.com/path-to-regexp/-/path-to-regexp-8.3.0.tgz",+ "integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/pkce-challenge": {+ "version": "5.0.1",+ "resolved": "https://registry.npmmirror.com/pkce-challenge/-/pkce-challenge-5.0.1.tgz",+ "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",+ "license": "MIT",+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/proxy-addr": {+ "version": "2.0.7",+ "resolved": "https://registry.npmmirror.com/proxy-addr/-/proxy-addr-2.0.7.tgz",+ "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",+ "license": "MIT",+ "dependencies": {+ "forwarded": "0.2.0",+ "ipaddr.js": "1.9.1"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/qs": {+ "version": "6.15.0",+ "resolved": "https://registry.npmmirror.com/qs/-/qs-6.15.0.tgz",+ "integrity": "sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "side-channel": "^1.1.0"+ },+ "engines": {+ "node": ">=0.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/range-parser": {+ "version": "1.2.1",+ "resolved": "https://registry.npmmirror.com/range-parser/-/range-parser-1.2.1.tgz",+ "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/raw-body": {+ "version": "3.0.2",+ "resolved": "https://registry.npmmirror.com/raw-body/-/raw-body-3.0.2.tgz",+ "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",+ "license": "MIT",+ "dependencies": {+ "bytes": "~3.1.2",+ "http-errors": "~2.0.1",+ "iconv-lite": "~0.7.0",+ "unpipe": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/require-from-string": {+ "version": "2.0.2",+ "resolved": "https://registry.npmmirror.com/require-from-string/-/require-from-string-2.0.2.tgz",+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/router": {+ "version": "2.2.0",+ "resolved": "https://registry.npmmirror.com/router/-/router-2.2.0.tgz",+ "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "is-promise": "^4.0.0",+ "parseurl": "^1.3.3",+ "path-to-regexp": "^8.0.0"+ },+ "engines": {+ "node": ">= 18"+ }+ },+ "node_modules/safer-buffer": {+ "version": "2.1.2",+ "resolved": "https://registry.npmmirror.com/safer-buffer/-/safer-buffer-2.1.2.tgz",+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",+ "license": "MIT"+ },+ "node_modules/send": {+ "version": "1.2.1",+ "resolved": "https://registry.npmmirror.com/send/-/send-1.2.1.tgz",+ "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.3",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.1",+ "mime-types": "^3.0.2",+ "ms": "^2.1.3",+ "on-finished": "^2.4.1",+ "range-parser": "^1.2.1",+ "statuses": "^2.0.2"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/serve-static": {+ "version": "2.2.1",+ "resolved": "https://registry.npmmirror.com/serve-static/-/serve-static-2.2.1.tgz",+ "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",+ "license": "MIT",+ "dependencies": {+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "parseurl": "^1.3.3",+ "send": "^1.2.0"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/setprototypeof": {+ "version": "1.2.0",+ "resolved": "https://registry.npmmirror.com/setprototypeof/-/setprototypeof-1.2.0.tgz",+ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",+ "license": "ISC"+ },+ "node_modules/shebang-command": {+ "version": "2.0.0",+ "resolved": "https://registry.npmmirror.com/shebang-command/-/shebang-command-2.0.0.tgz",+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",+ "license": "MIT",+ "dependencies": {+ "shebang-regex": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shebang-regex": {+ "version": "3.0.0",+ "resolved": "https://registry.npmmirror.com/shebang-regex/-/shebang-regex-3.0.0.tgz",+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/side-channel": {+ "version": "1.1.0",+ "resolved": "https://registry.npmmirror.com/side-channel/-/side-channel-1.1.0.tgz",+ "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.3",+ "side-channel-list": "^1.0.0",+ "side-channel-map": "^1.0.1",+ "side-channel-weakmap": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-list": {+ "version": "1.0.0",+ "resolved": "https://registry.npmmirror.com/side-channel-list/-/side-channel-list-1.0.0.tgz",+ "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-map": {+ "version": "1.0.1",+ "resolved": "https://registry.npmmirror.com/side-channel-map/-/side-channel-map-1.0.1.tgz",+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-weakmap": {+ "version": "1.0.2",+ "resolved": "https://registry.npmmirror.com/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3",+ "side-channel-map": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/statuses": {+ "version": "2.0.2",+ "resolved": "https://registry.npmmirror.com/statuses/-/statuses-2.0.2.tgz",+ "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/toidentifier": {+ "version": "1.0.1",+ "resolved": "https://registry.npmmirror.com/toidentifier/-/toidentifier-1.0.1.tgz",+ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.6"+ }+ },+ "node_modules/type-is": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/type-is/-/type-is-2.0.1.tgz",+ "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==",+ "license": "MIT",+ "dependencies": {+ "content-type": "^1.0.5",+ "media-typer": "^1.1.0",+ "mime-types": "^3.0.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "resolved": "https://registry.npmmirror.com/typescript/-/typescript-5.9.3.tgz",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/undici-types": {+ "version": "6.21.0",+ "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-6.21.0.tgz",+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/unpipe": {+ "version": "1.0.0",+ "resolved": "https://registry.npmmirror.com/unpipe/-/unpipe-1.0.0.tgz",+ "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/vary": {+ "version": "1.1.2",+ "resolved": "https://registry.npmmirror.com/vary/-/vary-1.1.2.tgz",+ "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/which": {+ "version": "2.0.2",+ "resolved": "https://registry.npmmirror.com/which/-/which-2.0.2.tgz",+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",+ "license": "ISC",+ "dependencies": {+ "isexe": "^2.0.0"+ },+ "bin": {+ "node-which": "bin/node-which"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/wrappy": {+ "version": "1.0.2",+ "resolved": "https://registry.npmmirror.com/wrappy/-/wrappy-1.0.2.tgz",+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",+ "license": "ISC"+ },+ "node_modules/zod": {+ "version": "4.3.6",+ "resolved": "https://registry.npmmirror.com/zod/-/zod-4.3.6.tgz",+ "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },+ "node_modules/zod-to-json-schema": {+ "version": "3.25.1",+ "resolved": "https://registry.npmmirror.com/zod-to-json-schema/-/zod-to-json-schema-3.25.1.tgz",+ "integrity": "sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA==",+ "license": "ISC",+ "peerDependencies": {+ "zod": "^3.25 || ^4"+ }+ }+ }+}diff --git a/examples/claude-code-memory-plugin/package.json b/examples/claude-code-memory-plugin/package.jsonnew file mode 100644index 000000000..004938724--- /dev/null+++ b/examples/claude-code-memory-plugin/package.json@@ -0,0 +1,18 @@+{+ "name": "claude-code-openviking-memory",+ "version": "0.1.0",+ "description": "OpenViking memory plugin for Claude Code — semantic long-term memory via MCP",+ "type": "module",+ "scripts": {+ "build": "tsc",+ "dev": "tsc --watch"+ },+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.12.1",+ "zod": "^4.3.6"+ },+ "devDependencies": {+ "@types/node": "^22.0.0",+ "typescript": "^5.7.0"+ }+}diff --git a/examples/claude-code-memory-plugin/scripts/auto-capture.mjs b/examples/claude-code-memory-plugin/scripts/auto-capture.mjsnew file mode 100644index 000000000..3c3662fb2--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/auto-capture.mjs@@ -0,0 +1,353 @@+#!/usr/bin/env node++/**+ * Auto-Capture Hook Script for Claude Code+ *+ * Triggered by Stop hook.+ * Reads transcript_path from stdin → extracts INCREMENTAL conversation+ * (only new turns since last capture) → keeps user turns by default →+ * sends to OpenViking session/extract pipeline → memories stored automatically.+ *+ * Incremental tracking: uses a state file per session_id to record how many+ * turns have been captured. Only new turns are processed on each invocation.+ *+ * Ported from openclaw-plugin/ auto-capture logic in context-engine.ts + text-utils.ts.+ */++import { readFile, writeFile, mkdir } from "node:fs/promises";+import { join } from "node:path";+import { tmpdir } from "node:os";+import { loadConfig } from "./config.mjs";+import { createLogger } from "./debug-log.mjs";++const cfg = loadConfig();+const { log, logError } = createLogger("auto-capture");++// State directory for incremental tracking+const STATE_DIR = join(tmpdir(), "openviking-cc-capture-state");++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++function output(obj) {+ process.stdout.write(JSON.stringify(obj) + "\n");+}++function approve(msg) {+ const out = { decision: "approve" };+ if (msg) out.systemMessage = msg;+ output(out);+}++async function fetchJSON(path, init = {}) {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), cfg.captureTimeoutMs);+ try {+ const headers = { "Content-Type": "application/json" };+ if (cfg.apiKey) headers["X-API-Key"] = cfg.apiKey;+ if (cfg.agentId) headers["X-OpenViking-Agent"] = cfg.agentId;+ const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });+ const body = await res.json();+ if (!res.ok || body.status === "error") return null;+ return body.result ?? body;+ } catch {+ return null;+ } finally {+ clearTimeout(timer);+ }+}++// ---------------------------------------------------------------------------+// Incremental state tracking+// ---------------------------------------------------------------------------++function stateFilePath(sessionId) {+ const safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, "_");+ return join(STATE_DIR, `${safe}.json`);+}++async function loadState(sessionId) {+ try {+ const data = await readFile(stateFilePath(sessionId), "utf-8");+ return JSON.parse(data);+ } catch {+ return { capturedTurnCount: 0 };+ }+}++async function saveState(sessionId, state) {+ try {+ await mkdir(STATE_DIR, { recursive: true });+ await writeFile(stateFilePath(sessionId), JSON.stringify(state));+ } catch { /* best effort */ }+}++// ---------------------------------------------------------------------------+// Text processing (ported from text-utils.ts)+// ---------------------------------------------------------------------------++const MEMORY_TRIGGERS = [+ /remember|preference|prefer|important|decision|decided|always|never/i,+ /记住|偏好|喜欢|喜爱|崇拜|讨厌|害怕|重要|决定|总是|永远|优先|习惯|爱好|擅长|最爱|不喜欢/i,+ /[\w.-]+@[\w.-]+\.\w+/,+ /\+\d{10,}/,+ /(?:我|my)\s*(?:是|叫|名字|name|住在|live|来自|from|生日|birthday|电话|phone|邮箱|email)/i,+ /(?:我|i)\s*(?:喜欢|崇拜|讨厌|害怕|擅长|不会|爱|恨|想要|需要|希望|觉得|认为|相信)/i,+ /(?:favorite|favourite|love|hate|enjoy|dislike|admire|idol|fan of)/i,+];++const RELEVANT_MEMORIES_BLOCK_RE = /<relevant-memories>[\s\S]*?<\/relevant-memories>/gi;+const COMMAND_TEXT_RE = /^\/[a-z0-9_-]{1,64}\b/i;+const NON_CONTENT_TEXT_RE = /^[\p{P}\p{S}\s]+$/u;+const CJK_CHAR_RE = /[\u3040-\u30ff\u3400-\u9fff\uf900-\ufaff\uac00-\ud7af]/;++function sanitize(text) {+ return text+ .replace(RELEVANT_MEMORIES_BLOCK_RE, " ")+ .replace(/\u0000/g, "")+ .replace(/\s+/g, " ")+ .trim();+}++function shouldCapture(text) {+ const normalized = sanitize(text);+ if (!normalized) return { capture: false, reason: "empty", text: "" };++ const compact = normalized.replace(/\s+/g, "");+ const minLen = CJK_CHAR_RE.test(compact) ? 4 : 10;+ if (compact.length < minLen || normalized.length > cfg.captureMaxLength) {+ return { capture: false, reason: "length_out_of_range", text: normalized };+ }++ if (COMMAND_TEXT_RE.test(normalized)) {+ return { capture: false, reason: "command", text: normalized };+ }++ if (NON_CONTENT_TEXT_RE.test(normalized)) {+ return { capture: false, reason: "non_content", text: normalized };+ }++ if (cfg.captureMode === "keyword") {+ for (const trigger of MEMORY_TRIGGERS) {+ if (trigger.test(normalized)) {+ return { capture: true, reason: `trigger:${trigger}`, text: normalized };+ }+ }+ return { capture: false, reason: "no_trigger", text: normalized };+ }++ // semantic mode — always capture+ return { capture: true, reason: "semantic", text: normalized };+}++// ---------------------------------------------------------------------------+// Transcript parsing+// ---------------------------------------------------------------------------++function parseTranscript(content) {+ try {+ const data = JSON.parse(content);+ if (Array.isArray(data)) return data;+ } catch { /* not a JSON array */ }++ const lines = content.split("\n").filter(l => l.trim());+ const messages = [];+ for (const line of lines) {+ try { messages.push(JSON.parse(line)); } catch { /* skip */ }+ }+ return messages;+}++function extractAllTurns(messages) {+ const turns = [];+ for (const msg of messages) {+ if (!msg || typeof msg !== "object") continue;++ let role = msg.role;+ let text = "";++ if (typeof msg.content === "string") {+ text = msg.content;+ } else if (Array.isArray(msg.content)) {+ const textParts = msg.content+ .filter(b => b && b.type === "text" && typeof b.text === "string")+ .map(b => b.text);+ text = textParts.join("\n");+ } else if (typeof msg.message === "object" && msg.message) {+ const inner = msg.message;+ role = inner.role || role;+ if (typeof inner.content === "string") {+ text = inner.content;+ } else if (Array.isArray(inner.content)) {+ const textParts = inner.content+ .filter(b => b && b.type === "text" && typeof b.text === "string")+ .map(b => b.text);+ text = textParts.join("\n");+ }+ }++ if (role !== "user" && role !== "assistant") continue;+ if (text.trim()) {+ turns.push({ role, text: text.trim() });+ }+ }+ return turns;+}++// ---------------------------------------------------------------------------+// OpenViking session capture+// ---------------------------------------------------------------------------++async function captureToOpenViking(text) {+ const sessionResult = await fetchJSON("/api/v1/sessions", {+ method: "POST",+ body: JSON.stringify({}),+ });+ if (!sessionResult?.session_id) return { ok: false, reason: "session_create_failed" };++ const sessionId = sessionResult.session_id;+ try {+ await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`, {+ method: "POST",+ body: JSON.stringify({ role: "user", content: text }),+ });++ const extracted = await fetchJSON(+ `/api/v1/sessions/${encodeURIComponent(sessionId)}/extract`,+ { method: "POST", body: JSON.stringify({}) }+ );++ return { ok: true, count: Array.isArray(extracted) ? extracted.length : 0 };+ } finally {+ await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}`, {+ method: "DELETE",+ }).catch(() => {});+ }+}++// ---------------------------------------------------------------------------+// Main+// ---------------------------------------------------------------------------++async function main() {+ if (!cfg.autoCapture) {+ log("skip", { stage: "init", reason: "autoCapture disabled" });+ approve();+ return;+ }++ let input;+ try {+ const chunks = [];+ for await (const chunk of process.stdin) chunks.push(chunk);+ input = JSON.parse(Buffer.concat(chunks).toString());+ } catch {+ log("skip", { stage: "stdin_parse", reason: "invalid input" });+ approve();+ return;+ }++ const transcriptPath = input.transcript_path;+ const sessionId = input.session_id || "unknown";+ log("start", { sessionId, transcriptPath });++ // Quick health check+ const health = await fetchJSON("/health");+ if (!health) {+ logError("health_check", "server unreachable or unhealthy");+ approve();+ return;+ }++ if (!transcriptPath) {+ log("skip", { stage: "input_check", reason: "no transcript_path" });+ approve();+ return;+ }++ let transcriptContent;+ try {+ transcriptContent = await readFile(transcriptPath, "utf-8");+ } catch (err) {+ logError("transcript_read", err);+ approve();+ return;+ }++ if (!transcriptContent.trim()) {+ log("skip", { stage: "transcript_read", reason: "empty transcript" });+ approve();+ return;+ }++ // Parse transcript and extract all turns+ const messages = parseTranscript(transcriptContent);+ const allTurns = extractAllTurns(messages);+ if (allTurns.length === 0) {+ log("skip", { stage: "transcript_parse", reason: "no user/assistant turns found" });+ approve();+ return;+ }++ // Load incremental state — skip already-captured turns+ const state = await loadState(sessionId);+ const newTurns = allTurns.slice(state.capturedTurnCount);+ const captureTurns = cfg.captureAssistantTurns+ ? newTurns+ : newTurns.filter(turn => turn.role === "user");+ log("transcript_parse", {+ totalTurns: allTurns.length,+ previouslyCaptured: state.capturedTurnCount,+ newTurns: newTurns.length,+ captureTurns: captureTurns.length,+ assistantTurnsSkipped: newTurns.length - captureTurns.length,+ });++ if (newTurns.length === 0) {+ log("skip", { stage: "incremental_check", reason: "no new turns" });+ approve();+ return;+ }++ if (captureTurns.length === 0) {+ await saveState(sessionId, { capturedTurnCount: allTurns.length });+ log("state_update", { newCapturedTurnCount: allTurns.length, reason: "assistant_only_increment" });+ approve();+ return;+ }++ // Format only the capturable turns+ const turnText = captureTurns.map(t => `[${t.role}]: ${t.text}`).join("\n");++ // Check capture decision+ const decision = shouldCapture(turnText);+ log("should_capture", {+ capture: decision.capture,+ reason: decision.reason,+ textPreview: decision.text.slice(0, 100),+ });++ if (!decision.capture) {+ await saveState(sessionId, { capturedTurnCount: allTurns.length });+ approve();+ return;+ }++ // Send to OpenViking+ const result = await captureToOpenViking(decision.text);+ log("openviking_capture", { sessionCreated: result.ok, extractedCount: result.count || 0 });++ // Update state+ await saveState(sessionId, { capturedTurnCount: allTurns.length });+ log("state_update", { newCapturedTurnCount: allTurns.length });++ if (result.ok && result.count > 0) {+ log("done", { captureTurns: captureTurns.length, extractedCount: result.count });+ approve(`captured ${captureTurns.length} turns, extracted ${result.count} memories`);+ } else {+ approve();+ }+}++main().catch((err) => { logError("uncaught", err); approve(); });diff --git a/examples/claude-code-memory-plugin/scripts/auto-recall.mjs b/examples/claude-code-memory-plugin/scripts/auto-recall.mjsnew file mode 100644index 000000000..2718a04ea--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/auto-recall.mjs@@ -0,0 +1,355 @@+#!/usr/bin/env node++/**+ * Auto-Recall Hook Script for Claude Code+ *+ * Triggered by UserPromptSubmit hook.+ * Reads user_prompt from stdin → searches OpenViking → returns recalled+ * memories via systemMessage so Claude sees them transparently.+ *+ * Ported from openclaw-plugin/ auto-recall logic in index.ts + memory-ranking.ts.+ */++import { loadConfig } from "./config.mjs";+import { createLogger } from "./debug-log.mjs";++const cfg = loadConfig();+const { log, logError } = createLogger("auto-recall");++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++function output(obj) {+ process.stdout.write(JSON.stringify(obj) + "\n");+}++function approve(msg) {+ const out = { decision: "approve" };+ if (msg) out.hookSpecificOutput = { hookEventName: "UserPromptSubmit", additionalContext: msg };+ output(out);+}++async function fetchJSON(path, init = {}) {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), cfg.timeoutMs);+ try {+ const headers = { "Content-Type": "application/json" };+ if (cfg.apiKey) headers["X-API-Key"] = cfg.apiKey;+ if (cfg.agentId) headers["X-OpenViking-Agent"] = cfg.agentId;+ const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });+ const body = await res.json();+ if (!res.ok || body.status === "error") return null;+ return body.result ?? body;+ } catch {+ return null;+ } finally {+ clearTimeout(timer);+ }+}++// ---------------------------------------------------------------------------+// Ranking (ported from memory-ranking.ts)+// ---------------------------------------------------------------------------++function clampScore(v) {+ if (typeof v !== "number" || Number.isNaN(v)) return 0;+ return Math.max(0, Math.min(1, v));+}++const PREFERENCE_QUERY_RE = /prefer|preference|favorite|favourite|like|偏好|喜欢|爱好|更倾向/i;+const TEMPORAL_QUERY_RE = /when|what time|date|day|month|year|yesterday|today|tomorrow|last|next|什么时候|何时|哪天|几月|几年|昨天|今天|明天/i;+const QUERY_TOKEN_RE = /[a-z0-9\u4e00-\u9fa5]{2,}/gi;+const STOPWORDS = new Set([+ "what","when","where","which","who","whom","whose","why","how","did","does",+ "is","are","was","were","the","and","for","with","from","that","this","your","you",+]);++function buildQueryProfile(query) {+ const text = query.trim();+ const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) || [];+ const tokens = allTokens.filter(t => !STOPWORDS.has(t));+ return {+ tokens,+ wantsPreference: PREFERENCE_QUERY_RE.test(text),+ wantsTemporal: TEMPORAL_QUERY_RE.test(text),+ };+}++function lexicalOverlapBoost(tokens, text) {+ if (tokens.length === 0 || !text) return 0;+ const haystack = ` ${text.toLowerCase()} `;+ let matched = 0;+ for (const token of tokens.slice(0, 8)) {+ if (haystack.includes(token)) matched += 1;+ }+ return Math.min(0.2, (matched / Math.min(tokens.length, 4)) * 0.2);+}++function getRankingBreakdown(item, profile) {+ const base = clampScore(item.score);+ const abstract = (item.abstract || item.overview || "").trim();+ const cat = (item.category || "").toLowerCase();+ const uri = item.uri.toLowerCase();+ const leafBoost = (item.level === 2 || uri.endsWith(".md")) ? 0.12 : 0;+ const eventBoost = profile.wantsTemporal && (cat === "events" || uri.includes("/events/")) ? 0.1 : 0;+ const prefBoost = profile.wantsPreference && (cat === "preferences" || uri.includes("/preferences/")) ? 0.08 : 0;+ const overlapBoost = lexicalOverlapBoost(profile.tokens, `${item.uri} ${abstract}`);+ return {+ baseScore: base,+ leafBoost,+ eventBoost,+ prefBoost,+ overlapBoost,+ finalScore: base + leafBoost + eventBoost + prefBoost + overlapBoost,+ };+}++function rankForInjection(item, profile) {+ return getRankingBreakdown(item, profile).finalScore;+}++function dedupeByAbstract(items) {+ const seen = new Set();+ return items.filter(item => {+ const key = (item.abstract || item.overview || "").trim().toLowerCase() || item.uri;+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+}++function pickMemories(items, limit, queryText) {+ if (items.length === 0 || limit <= 0) return [];+ const profile = buildQueryProfile(queryText);+ const sorted = [...items].sort((a, b) => rankForInjection(b, profile) - rankForInjection(a, profile));+ const deduped = dedupeByAbstract(sorted);+ const leaves = deduped.filter(m => m.level === 2 || m.uri.endsWith(".md"));+ if (leaves.length >= limit) return leaves.slice(0, limit);+ const picked = [...leaves];+ const used = new Set(picked.map(m => m.uri));+ for (const item of deduped) {+ if (picked.length >= limit) break;+ if (used.has(item.uri)) continue;+ picked.push(item);+ }+ return picked;+}++function postProcess(items, limit, threshold) {+ const seen = new Set();+ const sorted = [...items].sort((a, b) => clampScore(b.score) - clampScore(a.score));+ const result = [];+ for (const item of sorted) {+ if (item.level !== 2) continue;+ if (clampScore(item.score) < threshold) continue;+ const cat = (item.category || "").toLowerCase() || "unknown";+ const abs = (item.abstract || item.overview || "").trim().toLowerCase();+ const key = abs ? `${cat}:${abs}` : `uri:${item.uri}`;+ if (seen.has(key)) continue;+ seen.add(key);+ result.push(item);+ if (result.length >= limit) break;+ }+ return result;+}++// ---------------------------------------------------------------------------+// URI space resolution (mirrors MCP server's normalizeTargetUri logic)+// ---------------------------------------------------------------------------++const USER_RESERVED_DIRS = new Set(["memories"]);+const AGENT_RESERVED_DIRS = new Set(["memories", "skills", "instructions", "workspaces"]);+const _spaceCache = {};++async function resolveScopeSpace(scope) {+ if (_spaceCache[scope]) return _spaceCache[scope];++ let fallbackSpace = "default";+ try {+ const status = await fetchJSON("/api/v1/system/status");+ if (status && typeof status.user === "string" && status.user.trim()) {+ fallbackSpace = status.user.trim();+ }+ } catch { /* use fallback */ }++ const reservedDirs = scope === "user" ? USER_RESERVED_DIRS : AGENT_RESERVED_DIRS;+ try {+ const entries = await fetchJSON(`/api/v1/fs/ls?uri=${encodeURIComponent(`viking://${scope}`)}&output=original`);+ if (Array.isArray(entries)) {+ const spaces = entries+ .filter(e => e?.isDir)+ .map(e => (typeof e.name === "string" ? e.name.trim() : ""))+ .filter(n => n && !n.startsWith(".") && !reservedDirs.has(n));+ if (spaces.length > 0) {+ if (spaces.includes(fallbackSpace)) { _spaceCache[scope] = fallbackSpace; return fallbackSpace; }+ if (scope === "user" && spaces.includes("default")) { _spaceCache[scope] = "default"; return "default"; }+ if (spaces.length === 1) { _spaceCache[scope] = spaces[0]; return spaces[0]; }+ }+ }+ } catch { /* use fallback */ }++ _spaceCache[scope] = fallbackSpace;+ return fallbackSpace;+}++async function resolveTargetUri(targetUri) {+ const trimmed = targetUri.trim().replace(/\/+$/, "");+ const m = trimmed.match(/^viking:\/\/(user|agent)(?:\/(.*))?$/);+ if (!m) return trimmed;+ const scope = m[1];+ const rawRest = (m[2] ?? "").trim();+ if (!rawRest) return trimmed;+ const parts = rawRest.split("/").filter(Boolean);+ if (parts.length === 0) return trimmed;+ const reservedDirs = scope === "user" ? USER_RESERVED_DIRS : AGENT_RESERVED_DIRS;+ if (!reservedDirs.has(parts[0])) return trimmed;+ const space = await resolveScopeSpace(scope);+ return `viking://${scope}/${space}/${parts.join("/")}`;+}++// ---------------------------------------------------------------------------+// Search OpenViking+// ---------------------------------------------------------------------------++async function searchScope(query, targetUri, limit) {+ const resolvedUri = await resolveTargetUri(targetUri);+ const result = await fetchJSON("/api/v1/search/find", {+ method: "POST",+ body: JSON.stringify({ query, target_uri: resolvedUri, limit, score_threshold: 0 }),+ });+ return result?.memories || [];+}++async function searchBothScopes(query, limit) {+ const [userMems, agentMems] = await Promise.all([+ searchScope(query, "viking://user/memories", limit),+ searchScope(query, "viking://agent/memories", limit),+ ]);+ log("search_complete", { scope: "user", rawCount: userMems.length, topScores: userMems.slice(0, 3).map(m => m.score) });+ log("search_complete", { scope: "agent", rawCount: agentMems.length, topScores: agentMems.slice(0, 3).map(m => m.score) });+ const all = [...userMems, ...agentMems];+ const uriSet = new Set();+ return all.filter(m => {+ if (uriSet.has(m.uri)) return false;+ uriSet.add(m.uri);+ return true;+ });+}++async function readMemoryContent(uri) {+ try {+ const result = await fetchJSON(`/api/v1/content/read?uri=${encodeURIComponent(uri)}`);+ if (result && typeof result === "string" && result.trim()) return result.trim();+ } catch { /* fallback */ }+ return null;+}++// ---------------------------------------------------------------------------+// Main+// ---------------------------------------------------------------------------++async function main() {+ if (!cfg.autoRecall) {+ log("skip", { stage: "init", reason: "autoRecall disabled" });+ approve();+ return;+ }++ let input;+ try {+ const chunks = [];+ for await (const chunk of process.stdin) chunks.push(chunk);+ input = JSON.parse(Buffer.concat(chunks).toString());+ } catch {+ log("skip", { stage: "stdin_parse", reason: "invalid input" });+ approve();+ return;+ }++ const userPrompt = (input.prompt || "").trim();+ log("start", {+ query: userPrompt.slice(0, 200),+ queryLength: userPrompt.length,+ config: { recallLimit: cfg.recallLimit, scoreThreshold: cfg.scoreThreshold },+ });++ if (!userPrompt || userPrompt.length < cfg.minQueryLength) {+ log("skip", { stage: "query_check", reason: "query too short or empty" });+ approve();+ return;+ }++ // Quick health check+ const health = await fetchJSON("/health");+ if (!health) {+ logError("health_check", "server unreachable or unhealthy");+ approve();+ return;+ }++ // Search+ const candidateLimit = Math.max(cfg.recallLimit * 4, 20);+ const allMemories = await searchBothScopes(userPrompt, candidateLimit);+ if (allMemories.length === 0) {+ log("skip", { stage: "search", reason: "no results from either scope" });+ approve();+ return;+ }++ // Post-process & rank+ const processed = postProcess(allMemories, candidateLimit, cfg.scoreThreshold);+ log("post_process", { beforeCount: allMemories.length, afterCount: processed.length });++ const profile = buildQueryProfile(userPrompt);+ const ranked = [...processed]+ .map(item => ({ item, breakdown: getRankingBreakdown(item, profile) }))+ .sort((a, b) => b.breakdown.finalScore - a.breakdown.finalScore);++ if (cfg.logRankingDetails) {+ for (const entry of ranked) {+ log("ranking_detail", {+ uri: entry.item.uri,+ ...entry.breakdown,+ });+ }+ } else {+ log("ranking_summary", {+ candidateCount: processed.length,+ topCandidates: ranked.slice(0, 5).map(entry => ({+ uri: entry.item.uri,+ finalScore: entry.breakdown.finalScore,+ })),+ });+ }++ const memories = pickMemories(processed, cfg.recallLimit, userPrompt);+ if (memories.length === 0) {+ log("skip", { stage: "pick", reason: "no memories survived ranking" });+ approve();+ return;+ }++ log("picked", { pickedCount: memories.length, uris: memories.map(m => m.uri) });++ // Read full content for leaf memories+ const lines = await Promise.all(+ memories.map(async (item) => {+ if (item.level === 2) {+ const content = await readMemoryContent(item.uri);+ if (content) return `- [${item.category || "memory"}] ${content}`;+ }+ return `- [${item.category || "memory"}] ${(item.abstract || item.overview || item.uri).trim()}`;+ })+ );++ const memoryContext =+ "<relevant-memories>\n" ++ "The following long-term memories from OpenViking may be relevant to this conversation:\n" ++ lines.join("\n") + "\n" ++ "</relevant-memories>";++ approve(memoryContext);+}++main().catch((err) => { logError("uncaught", err); approve(); });diff --git a/examples/claude-code-memory-plugin/scripts/bootstrap-runtime.mjs b/examples/claude-code-memory-plugin/scripts/bootstrap-runtime.mjsnew file mode 100644index 000000000..27c0150f3--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/bootstrap-runtime.mjs@@ -0,0 +1,25 @@+import {+ computeSourceState,+ ensureRuntimeInstalled,+ getRuntimePaths,+} from "./runtime-common.mjs";++async function main() {+ const paths = getRuntimePaths();+ const expectedState = await computeSourceState(paths);++ try {+ await ensureRuntimeInstalled(paths, expectedState);+ } catch (err) {+ process.stderr.write(+ `[openviking-memory] Failed to prepare MCP runtime dependencies: ${err instanceof Error ? err.message : String(err)}\n`,+ );+ }+}++main().catch(async (err) => {+ process.stderr.write(+ `[openviking-memory] Runtime bootstrap failed: ${err instanceof Error ? err.message : String(err)}\n`,+ );+ process.exit(0);+});diff --git a/examples/claude-code-memory-plugin/scripts/config.mjs b/examples/claude-code-memory-plugin/scripts/config.mjsnew file mode 100644index 000000000..dfbbd26c1--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/config.mjs@@ -0,0 +1,102 @@+/**+ * Shared configuration loader for the Claude Code OpenViking memory plugin.+ *+ * Reads from the OpenViking server config file (ov.conf, JSON format),+ * shared with the OpenClaw plugin and other OpenViking clients.+ *+ * Env var: OPENVIKING_CONFIG_FILE (default: ~/.openviking/ov.conf)+ *+ * Connection info is derived from ov.conf's `server` section.+ * Plugin-specific overrides go in an optional `claude_code` section.+ */++import { readFileSync } from "node:fs";+import { homedir } from "node:os";+import { join, resolve as resolvePath } from "node:path";++const DEFAULT_CONFIG_PATH = join(homedir(), ".openviking", "ov.conf");++function num(val, fallback) {+ if (typeof val === "number" && Number.isFinite(val)) return val;+ if (typeof val === "string" && val.trim()) {+ const n = Number(val);+ if (Number.isFinite(n)) return n;+ }+ return fallback;+}++function str(val, fallback) {+ if (typeof val === "string" && val.trim()) return val.trim();+ return fallback;+}++export function loadConfig() {+ const configPath = resolvePath(+ (process.env.OPENVIKING_CONFIG_FILE || DEFAULT_CONFIG_PATH).replace(/^~/, homedir()),+ );++ let raw;+ try {+ raw = readFileSync(configPath, "utf-8");+ } catch (err) {+ const msg = err?.code === "ENOENT"+ ? `Config file not found: ${configPath}\n Create it from the example: cp ov.conf.example ~/.openviking/ov.conf`+ : `Failed to read config file: ${configPath} — ${err?.message || err}`;+ process.stderr.write(`[openviking-memory] ${msg}\n`);+ process.exit(1);+ }++ let file;+ try {+ file = JSON.parse(raw);+ } catch (err) {+ process.stderr.write(`[openviking-memory] Invalid JSON in ${configPath}: ${err?.message || err}\n`);+ process.exit(1);+ }++ // Server connection — from ov.conf [server] section+ const server = file.server || {};+ const host = str(server.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");+ const port = Math.floor(num(server.port, 1933));+ const baseUrl = `http://${host}:${port}`;+ const apiKey = str(server.root_api_key, "") || "";++ // Plugin-specific overrides — from optional [claude_code] section+ const cc = file.claude_code || {};++ const debug = cc.debug === true || process.env.OPENVIKING_DEBUG === "1";+ const defaultLogPath = join(homedir(), ".openviking", "logs", "cc-hooks.log");+ const debugLogPath = str(process.env.OPENVIKING_DEBUG_LOG, defaultLogPath);++ const timeoutMs = Math.max(1000, Math.floor(num(cc.timeoutMs, 15000)));+ const captureTimeoutMs = Math.max(+ 1000,+ Math.floor(num(cc.captureTimeoutMs, Math.max(timeoutMs * 2, 30000))),+ );++ return {+ configPath,+ baseUrl,+ apiKey,+ agentId: str(cc.agentId, "claude-code"),+ timeoutMs,++ // Recall+ autoRecall: cc.autoRecall !== false,+ recallLimit: Math.max(1, Math.floor(num(cc.recallLimit, 6))),+ scoreThreshold: Math.min(1, Math.max(0, num(cc.scoreThreshold, 0.01))),+ minQueryLength: Math.max(1, Math.floor(num(cc.minQueryLength, 3))),+ logRankingDetails: cc.logRankingDetails === true,++ // Capture+ autoCapture: cc.autoCapture !== false,+ captureMode: cc.captureMode === "keyword" ? "keyword" : "semantic",+ captureMaxLength: Math.max(200, Math.floor(num(cc.captureMaxLength, 24000))),+ captureTimeoutMs,+ captureAssistantTurns: cc.captureAssistantTurns === true,++ // Debug+ debug,+ debugLogPath,+ };+}diff --git a/examples/claude-code-memory-plugin/scripts/debug-capture.mjs b/examples/claude-code-memory-plugin/scripts/debug-capture.mjsnew file mode 100755index 000000000..0de35f9c9--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/debug-capture.mjs@@ -0,0 +1,485 @@+#!/usr/bin/env node++/**+ * Debug Capture Pipeline — standalone test script.+ *+ * Usage:+ * node scripts/debug-capture.mjs /path/to/transcript.jsonl [session-id]+ * echo "remember I like Rust" | node scripts/debug-capture.mjs --stdin+ *+ * Runs the same capture pipeline as auto-capture.mjs but prints every+ * intermediate stage to stdout in a human-readable format instead of+ * silently returning a hook decision.+ */++import { readFile, writeFile, mkdir } from "node:fs/promises";+import { join } from "node:path";+import { tmpdir } from "node:os";+import { loadConfig } from "./config.mjs";++// ---------------------------------------------------------------------------+// ANSI helpers+// ---------------------------------------------------------------------------++const C = {+ reset: "\x1b[0m",+ dim: "\x1b[2m",+ bold: "\x1b[1m",+ red: "\x1b[31m",+ green: "\x1b[32m",+ yellow: "\x1b[33m",+ cyan: "\x1b[36m",+};++function header(title) {+ console.log(`\n${C.cyan}${C.bold}═══ ${title} ═══${C.reset}\n`);+}++function ok(msg) { console.log(`${C.green}\u2713${C.reset} ${msg}`); }+function warn(msg) { console.log(`${C.yellow}\u26A0${C.reset} ${msg}`); }+function fail(msg) { console.log(`${C.red}\u2717${C.reset} ${msg}`); }+function dim(msg) { console.log(`${C.dim}${msg}${C.reset}`); }++function preview(text, maxLen) {+ if (text.length <= maxLen) return text;+ return text.slice(0, maxLen) + "...";+}++// ---------------------------------------------------------------------------+// State directory for incremental tracking+// ---------------------------------------------------------------------------++const STATE_DIR = join(tmpdir(), "openviking-cc-capture-state");++function stateFilePath(sessionId) {+ const safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, "_");+ return join(STATE_DIR, `${safe}.json`);+}++async function loadState(sessionId) {+ try {+ const data = await readFile(stateFilePath(sessionId), "utf-8");+ return JSON.parse(data);+ } catch {+ return { capturedTurnCount: 0 };+ }+}++async function saveState(sessionId, state) {+ try {+ await mkdir(STATE_DIR, { recursive: true });+ await writeFile(stateFilePath(sessionId), JSON.stringify(state));+ } catch { /* best effort */ }+}++// ---------------------------------------------------------------------------+// Text processing (copied from auto-capture.mjs)+// ---------------------------------------------------------------------------++const MEMORY_TRIGGERS = [+ /remember|preference|prefer|important|decision|decided|always|never/i,+ /记住|偏好|喜欢|喜爱|崇拜|讨厌|害怕|重要|决定|总是|永远|优先|习惯|爱好|擅长|最爱|不喜欢/i,+ /[\w.-]+@[\w.-]+\.\w+/,+ /\+\d{10,}/,+ /(?:我|my)\s*(?:是|叫|名字|name|住在|live|来自|from|生日|birthday|电话|phone|邮箱|email)/i,+ /(?:我|i)\s*(?:喜欢|崇拜|讨厌|害怕|擅长|不会|爱|恨|想要|需要|希望|觉得|认为|相信)/i,+ /(?:favorite|favourite|love|hate|enjoy|dislike|admire|idol|fan of)/i,+];++const RELEVANT_MEMORIES_BLOCK_RE = /<relevant-memories>[\s\S]*?<\/relevant-memories>/gi;+const COMMAND_TEXT_RE = /^\/[a-z0-9_-]{1,64}\b/i;+const NON_CONTENT_TEXT_RE = /^[\p{P}\p{S}\s]+$/u;+const CJK_CHAR_RE = /[\u3040-\u30ff\u3400-\u9fff\uf900-\ufaff\uac00-\ud7af]/;++function sanitize(text) {+ return text+ .replace(RELEVANT_MEMORIES_BLOCK_RE, " ")+ .replace(/\u0000/g, "")+ .replace(/\s+/g, " ")+ .trim();+}++function shouldCapture(text) {+ const normalized = sanitize(text);+ if (!normalized) return { capture: false, reason: "empty", text: "" };++ const compact = normalized.replace(/\s+/g, "");+ const minLen = CJK_CHAR_RE.test(compact) ? 4 : 10;+ if (compact.length < minLen || normalized.length > cfg.captureMaxLength) {+ return { capture: false, reason: "length_out_of_range", text: normalized };+ }++ if (COMMAND_TEXT_RE.test(normalized)) {+ return { capture: false, reason: "command", text: normalized };+ }++ if (NON_CONTENT_TEXT_RE.test(normalized)) {+ return { capture: false, reason: "non_content", text: normalized };+ }++ if (cfg.captureMode === "keyword") {+ for (const trigger of MEMORY_TRIGGERS) {+ if (trigger.test(normalized)) {+ return { capture: true, reason: `trigger:${trigger}`, text: normalized };+ }+ }+ return { capture: false, reason: "no_trigger", text: normalized };+ }++ // semantic mode — always capture+ return { capture: true, reason: "semantic", text: normalized };+}++// ---------------------------------------------------------------------------+// Transcript parsing (copied from auto-capture.mjs)+// ---------------------------------------------------------------------------++function parseTranscript(content) {+ try {+ const data = JSON.parse(content);+ if (Array.isArray(data)) return { messages: data, format: "JSON array" };+ } catch { /* not a JSON array */ }++ const lines = content.split("\n").filter(l => l.trim());+ const messages = [];+ for (const line of lines) {+ try { messages.push(JSON.parse(line)); } catch { /* skip */ }+ }+ return { messages, format: "JSONL" };+}++function extractAllTurns(messages) {+ const turns = [];+ for (const msg of messages) {+ if (!msg || typeof msg !== "object") continue;++ let role = msg.role;+ let text = "";++ if (typeof msg.content === "string") {+ text = msg.content;+ } else if (Array.isArray(msg.content)) {+ const textParts = msg.content+ .filter(b => b && b.type === "text" && typeof b.text === "string")+ .map(b => b.text);+ text = textParts.join("\n");+ } else if (typeof msg.message === "object" && msg.message) {+ const inner = msg.message;+ role = inner.role || role;+ if (typeof inner.content === "string") {+ text = inner.content;+ } else if (Array.isArray(inner.content)) {+ const textParts = inner.content+ .filter(b => b && b.type === "text" && typeof b.text === "string")+ .map(b => b.text);+ text = textParts.join("\n");+ }+ }++ if (role !== "user" && role !== "assistant") continue;+ if (text.trim()) {+ turns.push({ role, text: text.trim() });+ }+ }+ return turns;+}++// ---------------------------------------------------------------------------+// fetchJSON — verbose version for debugging+// ---------------------------------------------------------------------------++async function fetchJSON(path, init = {}) {+ const url = `${cfg.baseUrl}${path}`;+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), cfg.captureTimeoutMs);+ try {+ const headers = { "Content-Type": "application/json" };+ if (cfg.apiKey) headers["X-API-Key"] = cfg.apiKey;+ if (cfg.agentId) headers["X-OpenViking-Agent"] = cfg.agentId;+ const res = await fetch(url, { ...init, headers, signal: controller.signal });+ const body = await res.json();+ dim(` ${init.method || "GET"} ${path} -> ${res.status}`);+ if (!res.ok || body.status === "error") {+ fail(` Response error: ${JSON.stringify(body).slice(0, 300)}`);+ return null;+ }+ const result = body.result ?? body;+ dim(` Response: ${JSON.stringify(result).slice(0, 300)}`);+ return result;+ } catch (err) {+ fail(` Fetch failed: ${url} — ${err?.message || err}`);+ return null;+ } finally {+ clearTimeout(timer);+ }+}++// ---------------------------------------------------------------------------+// captureToOpenViking — verbose version showing each step+// ---------------------------------------------------------------------------++async function captureToOpenViking(text) {+ header("Session Pipeline");++ // Step 1: Create session+ console.log("Step 1: Creating session...");+ const sessionResult = await fetchJSON("/api/v1/sessions", {+ method: "POST",+ body: JSON.stringify({}),+ });+ if (!sessionResult?.session_id) {+ fail("Session creation failed — no session_id returned");+ return { ok: false, reason: "session_create_failed" };+ }+ ok(`Session created: ${sessionResult.session_id}`);++ const sessionId = sessionResult.session_id;+ try {+ // Step 2: Add message+ console.log("\nStep 2: Adding message...");+ const addResult = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`, {+ method: "POST",+ body: JSON.stringify({ role: "user", content: text }),+ });+ if (addResult) {+ ok("Message added to session");+ } else {+ warn("addMessage returned null (may still work)");+ }++ // Step 3: Extract+ console.log("\nStep 3: Extracting memories...");+ const extracted = await fetchJSON(+ `/api/v1/sessions/${encodeURIComponent(sessionId)}/extract`,+ { method: "POST", body: JSON.stringify({}) },+ );++ if (extracted) {+ ok("Extraction completed");+ } else {+ fail("Extraction returned null");+ }++ // Show extracted memories+ header("Extracted Memories");+ const memories = Array.isArray(extracted) ? extracted : [];+ if (memories.length === 0) {+ warn("No memories extracted");+ } else {+ ok(`${memories.length} memor${memories.length === 1 ? "y" : "ies"} extracted:`);+ for (let i = 0; i < memories.length; i++) {+ const m = memories[i];+ console.log(`\n ${C.green}[${i + 1}]${C.reset}`);+ if (m.id) dim(` id: ${m.id}`);+ if (m.content) console.log(` content: ${preview(String(m.content), 200)}`);+ if (m.category) dim(` category: ${m.category}`);+ if (m.score != null) dim(` score: ${m.score}`);+ // Print any other fields+ for (const key of Object.keys(m)) {+ if (!["id", "content", "category", "score"].includes(key)) {+ dim(` ${key}: ${JSON.stringify(m[key]).slice(0, 150)}`);+ }+ }+ }+ }++ return { ok: true, count: memories.length };+ } finally {+ // Cleanup session+ dim("\nCleaning up session...");+ await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}`, {+ method: "DELETE",+ }).catch(() => {});+ }+}++// ---------------------------------------------------------------------------+// stdin reader+// ---------------------------------------------------------------------------++async function readStdin() {+ const chunks = [];+ for await (const chunk of process.stdin) chunks.push(chunk);+ return Buffer.concat(chunks).toString();+}++// ---------------------------------------------------------------------------+// Config (loaded at module level like auto-capture.mjs)+// ---------------------------------------------------------------------------++const cfg = loadConfig();++// ---------------------------------------------------------------------------+// Main+// ---------------------------------------------------------------------------++async function main() {+ const args = process.argv.slice(2);+ const isStdin = args.includes("--stdin");++ if (args.length === 0 && !isStdin) {+ console.error(`Usage:+ node scripts/debug-capture.mjs /path/to/transcript.jsonl [session-id]+ echo "remember I like Rust" | node scripts/debug-capture.mjs --stdin`);+ process.exit(1);+ }++ // ── Stage 1: Config summary ──+ header("Config Summary");+ console.log(` baseUrl: ${cfg.baseUrl}`);+ console.log(` captureMode: ${cfg.captureMode}`);+ console.log(` captureMaxLength: ${cfg.captureMaxLength}`);+ console.log(` captureTimeoutMs: ${cfg.captureTimeoutMs}`);+ console.log(` captureAssistant: ${cfg.captureAssistantTurns}`);+ console.log(` debug: ${cfg.debug}`);+ console.log(` agentId: ${cfg.agentId}`);+ console.log(` timeoutMs: ${cfg.timeoutMs}`);++ let allTurns;+ let sessionId;+ let skipIncremental = false;+ let transcriptFormat;++ if (isStdin) {+ // ── stdin mode ──+ header("Transcript Parsing");+ const stdinText = await readStdin();+ if (!stdinText.trim()) {+ fail("No input received on stdin");+ process.exit(1);+ }+ allTurns = [{ role: "user", text: stdinText.trim() }];+ sessionId = "stdin-debug";+ skipIncremental = true;+ transcriptFormat = "stdin text";+ ok(`Format: ${transcriptFormat}`);+ ok(`Total turns: ${allTurns.length}`);+ dim(` Text: ${preview(stdinText.trim(), 100)}`);+ } else {+ // ── file mode ──+ const transcriptPath = args[0];+ sessionId = args[1] || "debug-" + Date.now();++ header("Transcript Parsing");+ let transcriptContent;+ try {+ transcriptContent = await readFile(transcriptPath, "utf-8");+ } catch (err) {+ fail(`Failed to read transcript: ${transcriptPath} — ${err?.message || err}`);+ process.exit(1);+ }++ if (!transcriptContent.trim()) {+ fail("Transcript file is empty");+ process.exit(1);+ }++ const { messages, format } = parseTranscript(transcriptContent);+ transcriptFormat = format;+ allTurns = extractAllTurns(messages);++ ok(`Format: ${transcriptFormat}`);+ ok(`Total messages parsed: ${messages.length}`);+ ok(`Total turns extracted: ${allTurns.length}`);+ dim(` Session ID: ${sessionId}`);+ }++ if (allTurns.length === 0) {+ warn("No turns to process");+ process.exit(0);+ }++ // ── Stage 3: Incremental state ──+ header("Incremental State");+ let newTurns;+ let captureTurns;+ if (skipIncremental) {+ dim(" Skipped (stdin mode)");+ newTurns = allTurns;+ ok(`New turns to process: ${newTurns.length}`);+ } else {+ const state = await loadState(sessionId);+ dim(` State file: ${stateFilePath(sessionId)}`);+ console.log(` Previously captured: ${state.capturedTurnCount}`);+ newTurns = allTurns.slice(state.capturedTurnCount);+ ok(`New turns to process: ${newTurns.length}`);+ if (newTurns.length === 0) {+ warn("All turns already captured — nothing to do");+ process.exit(0);+ }+ }+ captureTurns = cfg.captureAssistantTurns+ ? newTurns+ : newTurns.filter(turn => turn.role === "user");+ ok(`Turns selected for capture: ${captureTurns.length}`);+ if (!cfg.captureAssistantTurns) {+ dim(` Assistant turns skipped: ${newTurns.length - captureTurns.length}`);+ }+ if (captureTurns.length === 0) {+ warn("No user turns in the new incremental slice — nothing will be sent");+ if (!skipIncremental) {+ await saveState(sessionId, { capturedTurnCount: allTurns.length });+ dim(" State updated (assistant-only turns marked as seen)");+ }+ process.exit(0);+ }++ // ── Stage 4: shouldCapture decisions ──+ header("shouldCapture Decisions");+ for (let i = 0; i < captureTurns.length; i++) {+ const turn = captureTurns[i];+ const decision = shouldCapture(turn.text);+ const captureLabel = decision.capture+ ? `${C.green}true${C.reset}`+ : `${C.dim}false${C.reset}`;+ console.log(` [${i}] ${C.dim}(${turn.role})${C.reset} capture=${captureLabel} reason=${decision.reason}`);+ dim(` ${preview(decision.text || turn.text, 100)}`);+ }++ // Build combined text from capturable turns (same logic as auto-capture.mjs)+ const turnText = captureTurns.map(t => `[${t.role}]: ${t.text}`).join("\n");+ const combinedDecision = shouldCapture(turnText);++ header("Combined Capture Decision");+ if (combinedDecision.capture) {+ ok(`capture=true reason=${combinedDecision.reason}`);+ } else {+ fail(`capture=false reason=${combinedDecision.reason}`);+ // Save state even on skip so next run doesn't re-examine these turns+ if (!skipIncremental) {+ await saveState(sessionId, { capturedTurnCount: allTurns.length });+ dim(" State updated (turns marked as seen)");+ }+ console.log("\nPipeline stopped — combined text did not pass shouldCapture.");+ process.exit(0);+ }++ // ── Stage 5: Text sent to OpenViking ──+ header("Text Sent to OpenViking");+ console.log(preview(combinedDecision.text, 500));+ dim(`\n (total length: ${combinedDecision.text.length} chars)`);++ // ── Stage 6 + 7: Session pipeline + extracted memories ──+ const result = await captureToOpenViking(combinedDecision.text);++ // Update state+ if (!skipIncremental) {+ await saveState(sessionId, { capturedTurnCount: allTurns.length });+ dim("\nState updated (turns marked as captured)");+ }++ // Final summary+ header("Summary");+ if (result.ok) {+ ok(`Pipeline completed — ${result.count} memor${result.count === 1 ? "y" : "ies"} extracted from ${captureTurns.length} captured turn${captureTurns.length === 1 ? "" : "s"}`);+ } else {+ fail(`Pipeline failed: ${result.reason}`);+ process.exit(1);+ }+}++main().catch(err => {+ fail(`Unhandled error: ${err?.message || err}`);+ if (err?.stack) dim(err.stack);+ process.exit(1);+});diff --git a/examples/claude-code-memory-plugin/scripts/debug-log.mjs b/examples/claude-code-memory-plugin/scripts/debug-log.mjsnew file mode 100644index 000000000..452b27635--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/debug-log.mjs@@ -0,0 +1,70 @@+/**+ * Shared structured debug logger for Claude Code hook scripts.+ *+ * Activation: OPENVIKING_DEBUG=1 env var OR claude_code.debug: true in ov.conf.+ * Log path: OPENVIKING_DEBUG_LOG env var OR ~/.openviking/logs/cc-hooks.log.+ * Format: JSON Lines — { ts, hook, stage, data } | { ts, hook, stage, error }.+ *+ * When inactive, log() and logError() are zero-cost no-ops.+ */++import { appendFileSync, mkdirSync } from "node:fs";+import { dirname } from "node:path";+import { loadConfig } from "./config.mjs";++let _cfg;+function cfg() {+ if (!_cfg) _cfg = loadConfig();+ return _cfg;+}++function ensureDir(filePath) {+ try {+ mkdirSync(dirname(filePath), { recursive: true });+ } catch { /* already exists or no permission — will fail on write */ }+}++function writeLine(filePath, obj) {+ try {+ appendFileSync(filePath, JSON.stringify(obj) + "\n");+ } catch { /* best effort — never crash the hook */ }+}++function localISO() {+ const d = new Date();+ const off = d.getTimezoneOffset();+ const sign = off <= 0 ? "+" : "-";+ const abs = Math.abs(off);+ const local = new Date(d.getTime() - off * 60000);+ return local.toISOString().replace("Z",+ `${sign}${String(Math.floor(abs / 60)).padStart(2, "0")}:${String(abs % 60).padStart(2, "0")}`);+}++const noop = () => {};++/**+ * @param {string} hookName — e.g. "auto-recall" or "auto-capture"+ * @param {{ debug?: boolean, debugLogPath?: string }} [overrideCfg]+ * Pass a config object directly (avoids re-loading ov.conf in test scripts).+ * @returns {{ log: (stage: string, data: any) => void, logError: (stage: string, err: any) => void }}+ */+export function createLogger(hookName, overrideCfg) {+ const c = overrideCfg || cfg();+ if (!c.debug) return { log: noop, logError: noop };++ const logPath = c.debugLogPath;+ ensureDir(logPath);++ function log(stage, data) {+ writeLine(logPath, { ts: localISO(), hook: hookName, stage, data });+ }++ function logError(stage, err) {+ const error = err instanceof Error+ ? { message: err.message, stack: err.stack }+ : String(err);+ writeLine(logPath, { ts: localISO(), hook: hookName, stage, error });+ }++ return { log, logError };+}diff --git a/examples/claude-code-memory-plugin/scripts/debug-recall.mjs b/examples/claude-code-memory-plugin/scripts/debug-recall.mjsnew file mode 100755index 000000000..61271d9b7--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/debug-recall.mjs@@ -0,0 +1,445 @@+#!/usr/bin/env node++/**+ * Debug Recall Pipeline — standalone test script.+ *+ * Usage: node scripts/debug-recall.mjs "我喜欢什么语言"+ *+ * Walks through every stage of the auto-recall pipeline and prints+ * human-readable output so you can see exactly what OpenViking returns,+ * how scoring/ranking works, and what the final injected message looks like.+ */++import { loadConfig } from "./config.mjs";++// ---------------------------------------------------------------------------+// ANSI helpers+// ---------------------------------------------------------------------------++const C = {+ reset: "\x1b[0m",+ dim: "\x1b[2m",+ bold: "\x1b[1m",+ red: "\x1b[31m",+ green: "\x1b[32m",+ yellow: "\x1b[33m",+ cyan: "\x1b[36m",+};++function header(title) {+ console.log(`\n${C.cyan}${C.bold}═══ ${title} ═══${C.reset}\n`);+}++function ok(msg) { console.log(`${C.green}${msg}${C.reset}`); }+function warn(msg) { console.log(`${C.yellow}${msg}${C.reset}`); }+function fail(msg) { console.log(`${C.red}${msg}${C.reset}`); }+function dim(msg) { console.log(`${C.dim}${msg}${C.reset}`); }++// ---------------------------------------------------------------------------+// CLI validation+// ---------------------------------------------------------------------------++const query = process.argv[2];+if (!query || !query.trim()) {+ fail("Usage: node scripts/debug-recall.mjs \"<query>\"");+ fail(" e.g. node scripts/debug-recall.mjs \"我喜欢什么语言\"");+ process.exit(1);+}++// ---------------------------------------------------------------------------+// Config+// ---------------------------------------------------------------------------++let cfg;+try {+ cfg = loadConfig();+} catch (err) {+ fail(`Config loading failed: ${err?.message || err}`);+ process.exit(1);+}++// ---------------------------------------------------------------------------+// fetchJSON (verbose version — shows response details on error)+// ---------------------------------------------------------------------------++async function fetchJSON(path, init = {}) {+ const url = `${cfg.baseUrl}${path}`;+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), cfg.timeoutMs);+ try {+ const headers = { "Content-Type": "application/json" };+ if (cfg.apiKey) headers["X-API-Key"] = cfg.apiKey;+ if (cfg.agentId) headers["X-OpenViking-Agent"] = cfg.agentId;+ const res = await fetch(url, { ...init, headers, signal: controller.signal });+ const body = await res.json();+ if (!res.ok || body.status === "error") {+ warn(` HTTP ${res.status} from ${path}`);+ dim(` Response: ${JSON.stringify(body).slice(0, 500)}`);+ return null;+ }+ return body.result ?? body;+ } catch (err) {+ if (err?.name === "AbortError") {+ fail(` Request timed out after ${cfg.timeoutMs}ms: ${path}`);+ } else {+ fail(` Fetch error for ${path}: ${err?.message || err}`);+ }+ return null;+ } finally {+ clearTimeout(timer);+ }+}++// ---------------------------------------------------------------------------+// Pure functions — copied from auto-recall.mjs+// ---------------------------------------------------------------------------++function clampScore(v) {+ if (typeof v !== "number" || Number.isNaN(v)) return 0;+ return Math.max(0, Math.min(1, v));+}++const PREFERENCE_QUERY_RE = /prefer|preference|favorite|favourite|like|偏好|喜欢|爱好|更倾向/i;+const TEMPORAL_QUERY_RE = /when|what time|date|day|month|year|yesterday|today|tomorrow|last|next|什么时候|何时|哪天|几月|几年|昨天|今天|明天/i;+const QUERY_TOKEN_RE = /[a-z0-9\u4e00-\u9fa5]{2,}/gi;+const STOPWORDS = new Set([+ "what","when","where","which","who","whom","whose","why","how","did","does",+ "is","are","was","were","the","and","for","with","from","that","this","your","you",+]);++function buildQueryProfile(queryText) {+ const text = queryText.trim();+ const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) || [];+ const tokens = allTokens.filter(t => !STOPWORDS.has(t));+ return {+ tokens,+ wantsPreference: PREFERENCE_QUERY_RE.test(text),+ wantsTemporal: TEMPORAL_QUERY_RE.test(text),+ };+}++function lexicalOverlapBoost(tokens, text) {+ if (tokens.length === 0 || !text) return 0;+ const haystack = ` ${text.toLowerCase()} `;+ let matched = 0;+ for (const token of tokens.slice(0, 8)) {+ if (haystack.includes(token)) matched += 1;+ }+ return Math.min(0.2, (matched / Math.min(tokens.length, 4)) * 0.2);+}++function rankForInjection(item, profile) {+ const base = clampScore(item.score);+ const abstract = (item.abstract || item.overview || "").trim();+ const cat = (item.category || "").toLowerCase();+ const uri = item.uri.toLowerCase();+ const leafBoost = (item.level === 2 || uri.endsWith(".md")) ? 0.12 : 0;+ const eventBoost = profile.wantsTemporal && (cat === "events" || uri.includes("/events/")) ? 0.1 : 0;+ const prefBoost = profile.wantsPreference && (cat === "preferences" || uri.includes("/preferences/")) ? 0.08 : 0;+ const overlapBoost = lexicalOverlapBoost(profile.tokens, `${item.uri} ${abstract}`);+ return base + leafBoost + eventBoost + prefBoost + overlapBoost;+}++function dedupeByAbstract(items) {+ const seen = new Set();+ return items.filter(item => {+ const key = (item.abstract || item.overview || "").trim().toLowerCase() || item.uri;+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+}++function pickMemories(items, limit, queryText) {+ if (items.length === 0 || limit <= 0) return [];+ const profile = buildQueryProfile(queryText);+ const sorted = [...items].sort((a, b) => rankForInjection(b, profile) - rankForInjection(a, profile));+ const deduped = dedupeByAbstract(sorted);+ const leaves = deduped.filter(m => m.level === 2 || m.uri.endsWith(".md"));+ if (leaves.length >= limit) return leaves.slice(0, limit);+ const picked = [...leaves];+ const used = new Set(picked.map(m => m.uri));+ for (const item of deduped) {+ if (picked.length >= limit) break;+ if (used.has(item.uri)) continue;+ picked.push(item);+ }+ return picked;+}++function postProcess(items, limit, threshold) {+ const seen = new Set();+ const sorted = [...items].sort((a, b) => clampScore(b.score) - clampScore(a.score));+ const result = [];+ for (const item of sorted) {+ if (item.level !== 2) continue;+ if (clampScore(item.score) < threshold) continue;+ const cat = (item.category || "").toLowerCase() || "unknown";+ const abs = (item.abstract || item.overview || "").trim().toLowerCase();+ const key = abs ? `${cat}:${abs}` : `uri:${item.uri}`;+ if (seen.has(key)) continue;+ seen.add(key);+ result.push(item);+ if (result.length >= limit) break;+ }+ return result;+}++// ---------------------------------------------------------------------------+// URI space resolution — copied from auto-recall.mjs+// ---------------------------------------------------------------------------++const USER_RESERVED_DIRS = new Set(["memories"]);+const AGENT_RESERVED_DIRS = new Set(["memories", "skills", "instructions", "workspaces"]);+const _spaceCache = {};++async function resolveScopeSpace(scope) {+ if (_spaceCache[scope]) return _spaceCache[scope];++ let fallbackSpace = "default";+ try {+ const status = await fetchJSON("/api/v1/system/status");+ if (status && typeof status.user === "string" && status.user.trim()) {+ fallbackSpace = status.user.trim();+ }+ } catch { /* use fallback */ }++ const reservedDirs = scope === "user" ? USER_RESERVED_DIRS : AGENT_RESERVED_DIRS;+ try {+ const entries = await fetchJSON(`/api/v1/fs/ls?uri=${encodeURIComponent(`viking://${scope}`)}&output=original`);+ if (Array.isArray(entries)) {+ const spaces = entries+ .filter(e => e?.isDir)+ .map(e => (typeof e.name === "string" ? e.name.trim() : ""))+ .filter(n => n && !n.startsWith(".") && !reservedDirs.has(n));+ if (spaces.length > 0) {+ if (spaces.includes(fallbackSpace)) { _spaceCache[scope] = fallbackSpace; return fallbackSpace; }+ if (scope === "user" && spaces.includes("default")) { _spaceCache[scope] = "default"; return "default"; }+ if (spaces.length === 1) { _spaceCache[scope] = spaces[0]; return spaces[0]; }+ }+ }+ } catch { /* use fallback */ }++ _spaceCache[scope] = fallbackSpace;+ return fallbackSpace;+}++async function resolveTargetUri(targetUri) {+ const trimmed = targetUri.trim().replace(/\/+$/, "");+ const m = trimmed.match(/^viking:\/\/(user|agent)(?:\/(.*))?$/);+ if (!m) return trimmed;+ const scope = m[1];+ const rawRest = (m[2] ?? "").trim();+ if (!rawRest) return trimmed;+ const parts = rawRest.split("/").filter(Boolean);+ if (parts.length === 0) return trimmed;+ const reservedDirs = scope === "user" ? USER_RESERVED_DIRS : AGENT_RESERVED_DIRS;+ if (!reservedDirs.has(parts[0])) return trimmed;+ const space = await resolveScopeSpace(scope);+ return `viking://${scope}/${space}/${parts.join("/")}`;+}++// ---------------------------------------------------------------------------+// Search — adapted from auto-recall.mjs (verbose on error)+// ---------------------------------------------------------------------------++async function searchScope(queryText, targetUri, limit) {+ const resolvedUri = await resolveTargetUri(targetUri);+ dim(` target: ${targetUri} -> ${resolvedUri}`);+ const result = await fetchJSON("/api/v1/search/find", {+ method: "POST",+ body: JSON.stringify({ query: queryText, target_uri: resolvedUri, limit, score_threshold: 0 }),+ });+ return result?.memories || [];+}++async function searchBothScopes(queryText, limit) {+ console.log(`${C.dim}Searching user scope...${C.reset}`);+ const userMems = await searchScope(queryText, "viking://user/memories", limit);+ console.log(`${C.dim}Searching agent scope...${C.reset}`);+ const agentMems = await searchScope(queryText, "viking://agent/memories", limit);++ const all = [...userMems, ...agentMems];+ const uriSet = new Set();+ return {+ userMems,+ agentMems,+ combined: all.filter(m => {+ if (uriSet.has(m.uri)) return false;+ uriSet.add(m.uri);+ return true;+ }),+ };+}++async function readMemoryContent(uri) {+ try {+ const result = await fetchJSON(`/api/v1/content/read?uri=${encodeURIComponent(uri)}`);+ if (result && typeof result === "string" && result.trim()) return result.trim();+ } catch (err) {+ warn(` Failed to read content for ${uri}: ${err?.message || err}`);+ }+ return null;+}++// ---------------------------------------------------------------------------+// Print helpers+// ---------------------------------------------------------------------------++function printSearchResults(label, items) {+ console.log(`${C.bold}${label}${C.reset} (${items.length} result${items.length === 1 ? "" : "s"}):`);+ if (items.length === 0) {+ dim(" (none)");+ return;+ }+ for (const item of items) {+ const score = clampScore(item.score).toFixed(4);+ console.log(` ${C.bold}${item.uri}${C.reset}`);+ dim(` score=${score} level=${item.level} category=${item.category || "(none)"}`);+ dim(` abstract: ${(item.abstract || item.overview || "(none)").trim().slice(0, 120)}`);+ }+}++// ---------------------------------------------------------------------------+// Main pipeline+// ---------------------------------------------------------------------------++async function main() {+ // ── Stage 1: Config ──+ header("Config Summary");+ console.log(` baseUrl: ${C.bold}${cfg.baseUrl}${C.reset}`);+ console.log(` recallLimit: ${cfg.recallLimit}`);+ console.log(` scoreThreshold: ${cfg.scoreThreshold}`);+ console.log(` timeoutMs: ${cfg.timeoutMs}`);+ console.log(` agentId: ${cfg.agentId}`);+ console.log(` debug: ${cfg.debug}`);+ console.log(` configPath: ${C.dim}${cfg.configPath}${C.reset}`);+ console.log(`\n Query: ${C.bold}${query}${C.reset}`);++ // Query profile+ const profile = buildQueryProfile(query);+ dim(` tokens: [${profile.tokens.join(", ")}]`);+ dim(` wantsPreference: ${profile.wantsPreference}`);+ dim(` wantsTemporal: ${profile.wantsTemporal}`);++ // ── Stage 2: Health check ──+ header("Health Check");+ const health = await fetchJSON("/health");+ if (health) {+ ok(` OK`);+ dim(` ${JSON.stringify(health).slice(0, 300)}`);+ } else {+ fail(` FAILED — OpenViking is not reachable at ${cfg.baseUrl}`);+ fail(" The search stages below will likely fail as well.");+ }++ // ── Stage 3: Raw search results ──+ header("Raw Search Results");+ const candidateLimit = Math.max(cfg.recallLimit * 4, 20);+ dim(` candidateLimit: ${candidateLimit}`);++ const { userMems, agentMems, combined } = await searchBothScopes(query, candidateLimit);++ console.log();+ printSearchResults("User scope (viking://user/memories)", userMems);+ console.log();+ printSearchResults("Agent scope (viking://agent/memories)", agentMems);+ console.log();+ dim(` Combined (deduplicated): ${combined.length} result${combined.length === 1 ? "" : "s"}`);++ if (combined.length === 0) {+ warn("\n No search results found. Pipeline ends here.");+ return;+ }++ // ── Stage 4: PostProcess ──+ header("PostProcess Results");+ const processed = postProcess(combined, candidateLimit, cfg.scoreThreshold);+ console.log(` Raw count: ${combined.length}`);+ console.log(` Filtered count: ${processed.length}`);+ const dropped = combined.length - processed.length;+ if (dropped > 0) {+ dim(` Dropped ${dropped} item${dropped === 1 ? "" : "s"} (non-leaf, below threshold, or duplicate)`);+ }++ if (processed.length === 0) {+ warn("\n All candidates were filtered out. Pipeline ends here.");+ return;+ }++ // ── Stage 5: Ranking details ──+ header("Ranking Details");+ const rankedItems = [...processed].sort((a, b) => rankForInjection(b, profile) - rankForInjection(a, profile));++ for (const item of rankedItems) {+ const base = clampScore(item.score);+ const abstract = (item.abstract || item.overview || "").trim();+ const cat = (item.category || "").toLowerCase();+ const uri = item.uri.toLowerCase();++ const leafBoost = (item.level === 2 || uri.endsWith(".md")) ? 0.12 : 0;+ const eventBoost = profile.wantsTemporal && (cat === "events" || uri.includes("/events/")) ? 0.1 : 0;+ const prefBoost = profile.wantsPreference && (cat === "preferences" || uri.includes("/preferences/")) ? 0.08 : 0;+ const overlapBoost = lexicalOverlapBoost(profile.tokens, `${item.uri} ${abstract}`);+ const finalScore = base + leafBoost + eventBoost + prefBoost + overlapBoost;++ console.log(` ${C.bold}${item.uri}${C.reset}`);+ dim(` baseScore: ${base.toFixed(4)}`);+ dim(` leafBoost: ${leafBoost > 0 ? C.reset + C.green + "+" + leafBoost.toFixed(4) + C.reset + C.dim : "+0.0000"}`);+ dim(` eventBoost: ${eventBoost > 0 ? C.reset + C.green + "+" + eventBoost.toFixed(4) + C.reset + C.dim : "+0.0000"}`);+ dim(` prefBoost: ${prefBoost > 0 ? C.reset + C.green + "+" + prefBoost.toFixed(4) + C.reset + C.dim : "+0.0000"}`);+ dim(` overlapBoost: ${overlapBoost > 0 ? C.reset + C.green + "+" + overlapBoost.toFixed(4) + C.reset + C.dim : "+0.0000"}`);+ console.log(` ${C.bold}finalScore: ${finalScore.toFixed(4)}${C.reset}`);+ }++ // ── Stage 6: Final picks ──+ header("Final Picks");+ const memories = pickMemories(processed, cfg.recallLimit, query);++ if (memories.length === 0) {+ warn(" No memories selected after pick stage.");+ return;+ }++ console.log(` Selected ${C.bold}${memories.length}${C.reset} of ${processed.length} candidates (limit: ${cfg.recallLimit})\n`);++ const lines = [];+ for (const item of memories) {+ console.log(` ${C.green}*${C.reset} ${C.bold}${item.uri}${C.reset}`);+ dim(` score=${clampScore(item.score).toFixed(4)} level=${item.level} category=${item.category || "(none)"}`);++ let lineText;+ if (item.level === 2) {+ const content = await readMemoryContent(item.uri);+ if (content) {+ ok(` content: ${content.slice(0, 200)}${content.length > 200 ? "..." : ""}`);+ lineText = `- [${item.category || "memory"}] ${content}`;+ } else {+ warn(" content: (could not read)");+ lineText = `- [${item.category || "memory"}] ${(item.abstract || item.overview || item.uri).trim()}`;+ }+ } else {+ lineText = `- [${item.category || "memory"}] ${(item.abstract || item.overview || item.uri).trim()}`;+ dim(` abstract: ${(item.abstract || item.overview || "(none)").trim().slice(0, 200)}`);+ }+ lines.push(lineText);+ }++ // ── Stage 7: Generated system message ──+ header("Generated System Message");+ const memoryContext =+ "<relevant-memories>\n" ++ "The following long-term memories from OpenViking may be relevant to this conversation:\n" ++ lines.join("\n") + "\n" ++ "</relevant-memories>";++ console.log(memoryContext);+ console.log();+ dim(` (${Buffer.byteLength(memoryContext, "utf-8")} bytes)`);+}++main().catch((err) => {+ fail(`\nUnexpected error: ${err?.message || err}`);+ if (err?.stack) dim(err.stack);+ process.exit(1);+});diff --git a/examples/claude-code-memory-plugin/scripts/runtime-common.mjs b/examples/claude-code-memory-plugin/scripts/runtime-common.mjsnew file mode 100644index 000000000..61e3188ab--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/runtime-common.mjs@@ -0,0 +1,277 @@+import { spawnSync } from "node:child_process";+import { createHash } from "node:crypto";+import { constants as fsConstants } from "node:fs";+import { access, copyFile, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";+import { homedir } from "node:os";+import { join } from "node:path";++export const INSTALL_TIMEOUT_MS = 120000;++const LOCK_STALE_MS = 10 * 60 * 1000;+const FALLBACK_PLUGIN_DATA_ROOT = join(homedir(), ".openviking", "claude-code-memory-plugin");+const RUNTIME_ENV_META_PATH = ".runtime-env.json";++export function getRuntimePaths() {+ const pluginRoot = process.env.CLAUDE_PLUGIN_ROOT;+ const pluginDataRoot = process.env.CLAUDE_PLUGIN_DATA || FALLBACK_PLUGIN_DATA_ROOT;++ if (!pluginRoot) throw new Error("CLAUDE_PLUGIN_ROOT is not set");++ const runtimeRoot = join(pluginDataRoot, "runtime");++ return {+ pluginRoot,+ pluginDataRoot,+ runtimeRoot,+ sourcePackagePath: join(pluginRoot, "package.json"),+ sourceLockPath: join(pluginRoot, "package-lock.json"),+ sourceServerPath: join(pluginRoot, "servers", "memory-server.js"),+ runtimePackagePath: join(runtimeRoot, "package.json"),+ runtimeLockPath: join(runtimeRoot, "package-lock.json"),+ runtimeServerPath: join(runtimeRoot, "servers", "memory-server.js"),+ runtimeNodeModulesPath: join(runtimeRoot, "node_modules"),+ statePath: join(runtimeRoot, "install-state.json"),+ lockDir: join(runtimeRoot, ".install-lock"),+ envMetaPath: join(runtimeRoot, RUNTIME_ENV_META_PATH),+ usingFallbackPluginData: !process.env.CLAUDE_PLUGIN_DATA,+ };+}++export async function computeSourceState(paths) {+ const [pkgRaw, lockRaw, serverRaw] = await Promise.all([+ readFile(paths.sourcePackagePath),+ readFile(paths.sourceLockPath),+ readFile(paths.sourceServerPath),+ ]);++ const pkg = JSON.parse(pkgRaw.toString("utf8"));++ return {+ pluginVersion: typeof pkg.version === "string" ? pkg.version : "0.0.0",+ manifestHash: sha256(pkgRaw, lockRaw),+ serverHash: sha256(serverRaw),+ };+}++export async function loadInstallState(paths) {+ try {+ return JSON.parse(await readFile(paths.statePath, "utf8"));+ } catch {+ return null;+ }+}++export async function writeInstallState(paths, state) {+ await mkdir(paths.runtimeRoot, { recursive: true });+ await writeFile(+ paths.statePath,+ JSON.stringify(+ {+ ...state,+ updatedAt: new Date().toISOString(),+ },+ null,+ 2,+ ) + "\n",+ );+}++export async function writeRuntimeEnvMeta(paths) {+ await mkdir(paths.runtimeRoot, { recursive: true });+ await writeFile(+ paths.envMetaPath,+ JSON.stringify(+ {+ pluginDataRoot: paths.pluginDataRoot,+ runtimeRoot: paths.runtimeRoot,+ usingFallbackPluginData: paths.usingFallbackPluginData,+ updatedAt: new Date().toISOString(),+ },+ null,+ 2,+ ) + "\n",+ );+}++export async function runtimeIsReady(paths, expectedState) {+ const state = await loadInstallState(paths);+ if (!state || state.status !== "ready") return false;+ if (state.manifestHash !== expectedState.manifestHash) return false;+ if (state.serverHash !== expectedState.serverHash) return false;++ for (const target of [+ paths.runtimePackagePath,+ paths.runtimeLockPath,+ paths.runtimeServerPath,+ paths.runtimeNodeModulesPath,+ ]) {+ if (!(await pathExists(target))) return false;+ }++ return true;+}++export async function syncRuntimeFiles(paths) {+ await mkdir(join(paths.runtimeRoot, "servers"), { recursive: true });+ await copyFile(paths.sourcePackagePath, paths.runtimePackagePath);+ await copyFile(paths.sourceLockPath, paths.runtimeLockPath);+ await copyFile(paths.sourceServerPath, paths.runtimeServerPath);+ await writeRuntimeEnvMeta(paths);+}++export async function acquireInstallLock(paths, timeoutMs = INSTALL_TIMEOUT_MS) {+ const startedAt = Date.now();++ while (Date.now() - startedAt < timeoutMs) {+ await mkdir(paths.runtimeRoot, { recursive: true });++ try {+ await mkdir(paths.lockDir);+ await writeFile(+ join(paths.lockDir, "owner.json"),+ JSON.stringify({+ pid: process.pid,+ createdAt: new Date().toISOString(),+ }) + "\n",+ );+ return async () => {+ await rm(paths.lockDir, { recursive: true, force: true });+ };+ } catch (err) {+ if (err?.code !== "EEXIST") throw err;++ if (await isStaleLock(paths.lockDir)) {+ await rm(paths.lockDir, { recursive: true, force: true });+ continue;+ }++ await wait(500);+ }+ }++ throw new Error(`Timed out waiting for install lock in ${paths.runtimeRoot}`);+}++export async function waitForRuntime(paths, expectedState, options = {}) {+ const timeoutMs = options.timeoutMs ?? INSTALL_TIMEOUT_MS;+ const pollMs = options.pollMs ?? 500;+ const graceMs = options.graceMs ?? 5000;+ const startedAt = Date.now();+ let sawLock = await pathExists(paths.lockDir);++ while (Date.now() - startedAt < timeoutMs) {+ if (await runtimeIsReady(paths, expectedState)) return true;++ const lockExists = await pathExists(paths.lockDir);+ sawLock ||= lockExists;++ if (!sawLock && Date.now() - startedAt >= graceMs) return false;++ await wait(pollMs);+ }++ return runtimeIsReady(paths, expectedState);+}++export function wait(ms) {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++export async function ensureRuntimeInstalled(paths, expectedState) {+ if (await runtimeIsReady(paths, expectedState)) return false;++ const releaseLock = await acquireInstallLock(paths, INSTALL_TIMEOUT_MS);++ try {+ if (await runtimeIsReady(paths, expectedState)) return false;++ await syncRuntimeFiles(paths);+ const result = spawnSync(getNpmCommand(), installArgs(), {+ cwd: paths.runtimeRoot,+ encoding: "utf8",+ stdio: "pipe",+ });++ if (result.error) throw result.error;+ if (result.status !== 0) throw new Error(formatInstallFailure(result));++ await writeInstallState(paths, {+ status: "ready",+ pluginVersion: expectedState.pluginVersion,+ manifestHash: expectedState.manifestHash,+ serverHash: expectedState.serverHash,+ pluginDataRoot: paths.pluginDataRoot,+ usingFallbackPluginData: paths.usingFallbackPluginData,+ });++ return true;+ } catch (err) {+ await rm(paths.runtimeNodeModulesPath, { recursive: true, force: true });++ await writeInstallState(paths, {+ status: "error",+ pluginVersion: expectedState.pluginVersion,+ manifestHash: expectedState.manifestHash,+ serverHash: expectedState.serverHash,+ pluginDataRoot: paths.pluginDataRoot,+ usingFallbackPluginData: paths.usingFallbackPluginData,+ error: err instanceof Error ? err.message : String(err),+ });++ throw err;+ } finally {+ await releaseLock();+ }+}++async function pathExists(target) {+ try {+ await access(target, fsConstants.F_OK);+ return true;+ } catch {+ return false;+ }+}++async function isStaleLock(lockDir) {+ try {+ const info = await stat(lockDir);+ return Date.now() - info.mtimeMs > LOCK_STALE_MS;+ } catch {+ return false;+ }+}++function sha256(...buffers) {+ const hash = createHash("sha256");+ for (const buf of buffers) hash.update(buf);+ return hash.digest("hex");+}++function getNpmCommand() {+ return process.platform === "win32" ? "npm.cmd" : "npm";+}++function installArgs() {+ return ["ci", "--omit=dev", "--ignore-scripts", "--no-audit", "--no-fund"];+}++function formatInstallFailure(result) {+ const lines = [+ `npm ci exited with status ${result.status ?? "unknown"}`,+ trimOutput(result.stderr),+ trimOutput(result.stdout),+ ].filter(Boolean);++ return lines.join("\n");+}++function trimOutput(output) {+ if (!output) return "";+ const text = output.trim();+ if (!text) return "";++ const maxChars = 4000;+ if (text.length <= maxChars) return text;+ return text.slice(-maxChars);+}diff --git a/examples/claude-code-memory-plugin/scripts/start-memory-server.mjs b/examples/claude-code-memory-plugin/scripts/start-memory-server.mjsnew file mode 100644index 000000000..2738a5685--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/start-memory-server.mjs@@ -0,0 +1,54 @@+import { spawn } from "node:child_process";+import {+ computeSourceState,+ ensureRuntimeInstalled,+ getRuntimePaths,+ loadInstallState,+} from "./runtime-common.mjs";++async function main() {+ const paths = getRuntimePaths();+ const expectedState = await computeSourceState(paths);++ try {+ await ensureRuntimeInstalled(paths, expectedState);+ } catch (err) {+ const state = await loadInstallState(paths);+ const detail = state?.error ? ` Last install error: ${state.error}` : "";+ process.stderr.write(+ `[openviking-memory] MCP runtime is not ready in ${paths.runtimeRoot}.${detail}\n`,+ );+ process.exit(1);+ return;+ }++ const child = spawn(process.execPath, [paths.runtimeServerPath], {+ cwd: paths.runtimeRoot,+ env: process.env,+ stdio: "inherit",+ });++ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {+ process.on(signal, () => {+ if (!child.killed) child.kill(signal);+ });+ }++ child.on("error", (err) => {+ process.stderr.write(+ `[openviking-memory] Failed to start MCP server: ${err instanceof Error ? err.message : String(err)}\n`,+ );+ process.exit(1);+ });++ child.on("exit", (code) => {+ process.exit(code ?? 1);+ });+}++main().catch((err) => {+ process.stderr.write(+ `[openviking-memory] MCP launcher failed: ${err instanceof Error ? err.message : String(err)}\n`,+ );+ process.exit(1);+});diff --git a/examples/claude-code-memory-plugin/servers/memory-server.js b/examples/claude-code-memory-plugin/servers/memory-server.jsnew file mode 100644index 000000000..0f0e494dc--- /dev/null+++ b/examples/claude-code-memory-plugin/servers/memory-server.js@@ -0,0 +1,523 @@+/**+ * OpenViking Memory MCP Server for Claude Code+ *+ * Exposes OpenViking long-term memory as MCP tools:+ * - memory_recall : semantic search across memories+ * - memory_store : extract and persist new memories+ * - memory_forget : delete memories by URI or query+ *+ * Ported from the OpenClaw context-engine plugin (openclaw-plugin/).+ * Adapted for Claude Code's MCP server interface (stdio transport).+ */+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";+import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";+import { z } from "zod";+import { createHash } from "node:crypto";+// ---------------------------------------------------------------------------+// Configuration — loaded from ov.conf (shared with OpenClaw plugin).+// Env var: OPENVIKING_CONFIG_FILE (default: ~/.openviking/ov.conf)+// Plugin-specific overrides go in the optional "claude_code" section.+// ---------------------------------------------------------------------------+import { readFileSync } from "node:fs";+import { homedir } from "node:os";+import { join, resolve as resolvePath } from "node:path";+function loadOvConf() {+ const defaultPath = join(homedir(), ".openviking", "ov.conf");+ const configPath = resolvePath((process.env.OPENVIKING_CONFIG_FILE || defaultPath).replace(/^~/, homedir()));+ try {+ return JSON.parse(readFileSync(configPath, "utf-8"));+ }+ catch (err) {+ const code = err?.code;+ const msg = code === "ENOENT"+ ? `Config file not found: ${configPath}`+ : `Failed to read config: ${configPath}`;+ process.stderr.write(`[openviking-memory] ${msg}\n`);+ process.exit(1);+ }+}+function num(val, fallback) {+ if (typeof val === "number" && Number.isFinite(val))+ return val;+ if (typeof val === "string" && val.trim()) {+ const n = Number(val);+ if (Number.isFinite(n))+ return n;+ }+ return fallback;+}+function str(val, fallback) {+ if (typeof val === "string" && val.trim())+ return val.trim();+ return fallback;+}+const file = loadOvConf();+const serverCfg = (file.server ?? {});+const cc = (file.claude_code ?? {});+const host = str(serverCfg.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");+const port = Math.floor(num(serverCfg.port, 1933));+const config = {+ baseUrl: `http://${host}:${port}`,+ apiKey: str(serverCfg.root_api_key, ""),+ agentId: str(cc.agentId, "claude-code"),+ timeoutMs: Math.max(1000, Math.floor(num(cc.timeoutMs, 15000))),+ recallLimit: Math.max(1, Math.floor(num(cc.recallLimit, 6))),+ scoreThreshold: Math.min(1, Math.max(0, num(cc.scoreThreshold, 0.01))),+};+// ---------------------------------------------------------------------------+// OpenViking HTTP Client (ported from openclaw-plugin/client.ts)+// ---------------------------------------------------------------------------+const MEMORY_URI_PATTERNS = [+ /^viking:\/\/user\/(?:[^/]+\/)?memories(?:\/|$)/,+ /^viking:\/\/agent\/(?:[^/]+\/)?memories(?:\/|$)/,+];+const USER_STRUCTURE_DIRS = new Set(["memories"]);+const AGENT_STRUCTURE_DIRS = new Set(["memories", "skills", "instructions", "workspaces"]);+function md5Short(input) {+ return createHash("md5").update(input).digest("hex").slice(0, 12);+}+function isMemoryUri(uri) {+ return MEMORY_URI_PATTERNS.some((p) => p.test(uri));+}+class OpenVikingClient {+ baseUrl;+ apiKey;+ agentId;+ timeoutMs;+ resolvedSpaceByScope = {};+ runtimeIdentity = null;+ constructor(baseUrl, apiKey, agentId, timeoutMs) {+ this.baseUrl = baseUrl;+ this.apiKey = apiKey;+ this.agentId = agentId;+ this.timeoutMs = timeoutMs;+ }+ async request(path, init = {}) {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);+ try {+ const headers = new Headers(init.headers ?? {});+ if (this.apiKey)+ headers.set("X-API-Key", this.apiKey);+ if (this.agentId)+ headers.set("X-OpenViking-Agent", this.agentId);+ if (init.body && !headers.has("Content-Type"))+ headers.set("Content-Type", "application/json");+ const response = await fetch(`${this.baseUrl}${path}`, {+ ...init,+ headers,+ signal: controller.signal,+ });+ const payload = (await response.json().catch(() => ({})));+ if (!response.ok || payload.status === "error") {+ const code = payload.error?.code ? ` [${payload.error.code}]` : "";+ const message = payload.error?.message ?? `HTTP ${response.status}`;+ throw new Error(`OpenViking request failed${code}: ${message}`);+ }+ return (payload.result ?? payload);+ }+ finally {+ clearTimeout(timer);+ }+ }+ async healthCheck() {+ try {+ await this.request("/health");+ return true;+ }+ catch {+ return false;+ }+ }+ async ls(uri) {+ return this.request(`/api/v1/fs/ls?uri=${encodeURIComponent(uri)}&output=original`);+ }+ async getRuntimeIdentity() {+ if (this.runtimeIdentity)+ return this.runtimeIdentity;+ const fallback = { userId: "default", agentId: this.agentId || "default" };+ try {+ const status = await this.request("/api/v1/system/status");+ const userId = typeof status.user === "string" && status.user.trim() ? status.user.trim() : "default";+ this.runtimeIdentity = { userId, agentId: this.agentId || "default" };+ return this.runtimeIdentity;+ }+ catch {+ this.runtimeIdentity = fallback;+ return fallback;+ }+ }+ async resolveScopeSpace(scope) {+ const cached = this.resolvedSpaceByScope[scope];+ if (cached)+ return cached;+ const identity = await this.getRuntimeIdentity();+ const fallbackSpace = scope === "user" ? identity.userId : md5Short(`${identity.userId}:${identity.agentId}`);+ const reservedDirs = scope === "user" ? USER_STRUCTURE_DIRS : AGENT_STRUCTURE_DIRS;+ try {+ const entries = await this.ls(`viking://${scope}`);+ const spaces = entries+ .filter((e) => e?.isDir === true)+ .map((e) => (typeof e.name === "string" ? e.name.trim() : ""))+ .filter((n) => n && !n.startsWith(".") && !reservedDirs.has(n));+ if (spaces.length > 0) {+ if (spaces.includes(fallbackSpace)) {+ this.resolvedSpaceByScope[scope] = fallbackSpace;+ return fallbackSpace;+ }+ if (scope === "user" && spaces.includes("default")) {+ this.resolvedSpaceByScope[scope] = "default";+ return "default";+ }+ if (spaces.length === 1) {+ this.resolvedSpaceByScope[scope] = spaces[0];+ return spaces[0];+ }+ }+ }+ catch { /* fall through */ }+ this.resolvedSpaceByScope[scope] = fallbackSpace;+ return fallbackSpace;+ }+ async normalizeTargetUri(targetUri) {+ const trimmed = targetUri.trim().replace(/\/+$/, "");+ const match = trimmed.match(/^viking:\/\/(user|agent)(?:\/(.*))?$/);+ if (!match)+ return trimmed;+ const scope = match[1];+ const rawRest = (match[2] ?? "").trim();+ if (!rawRest)+ return trimmed;+ const parts = rawRest.split("/").filter(Boolean);+ if (parts.length === 0)+ return trimmed;+ const reservedDirs = scope === "user" ? USER_STRUCTURE_DIRS : AGENT_STRUCTURE_DIRS;+ if (!reservedDirs.has(parts[0]))+ return trimmed;+ const space = await this.resolveScopeSpace(scope);+ return `viking://${scope}/${space}/${parts.join("/")}`;+ }+ async find(query, options) {+ const normalizedTargetUri = await this.normalizeTargetUri(options.targetUri);+ return this.request("/api/v1/search/find", {+ method: "POST",+ body: JSON.stringify({+ query,+ target_uri: normalizedTargetUri,+ limit: options.limit,+ score_threshold: options.scoreThreshold,+ }),+ });+ }+ async read(uri) {+ return this.request(`/api/v1/content/read?uri=${encodeURIComponent(uri)}`);+ }+ async createSession() {+ const result = await this.request("/api/v1/sessions", {+ method: "POST",+ body: JSON.stringify({}),+ });+ return result.session_id;+ }+ async addSessionMessage(sessionId, role, content) {+ await this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`, {+ method: "POST",+ body: JSON.stringify({ role, content }),+ });+ }+ async extractSessionMemories(sessionId) {+ return this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}/extract`, { method: "POST", body: JSON.stringify({}) });+ }+ async deleteSession(sessionId) {+ await this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}`, { method: "DELETE" });+ }+ async deleteUri(uri) {+ await this.request(`/api/v1/fs?uri=${encodeURIComponent(uri)}&recursive=false`, {+ method: "DELETE",+ });+ }+}+// ---------------------------------------------------------------------------+// Memory ranking helpers (ported from openclaw-plugin/memory-ranking.ts)+// ---------------------------------------------------------------------------+function clampScore(value) {+ if (typeof value !== "number" || Number.isNaN(value))+ return 0;+ return Math.max(0, Math.min(1, value));+}+function normalizeDedupeText(text) {+ return text.toLowerCase().replace(/\s+/g, " ").trim();+}+function getMemoryDedupeKey(item) {+ const abstract = normalizeDedupeText(item.abstract ?? item.overview ?? "");+ const category = (item.category ?? "").toLowerCase() || "unknown";+ if (abstract)+ return `abstract:${category}:${abstract}`;+ return `uri:${item.uri}`;+}+function postProcessMemories(items, options) {+ const deduped = [];+ const seen = new Set();+ const sorted = [...items].sort((a, b) => clampScore(b.score) - clampScore(a.score));+ for (const item of sorted) {+ if (options.leafOnly && item.level !== 2)+ continue;+ if (clampScore(item.score) < options.scoreThreshold)+ continue;+ const key = getMemoryDedupeKey(item);+ if (seen.has(key))+ continue;+ seen.add(key);+ deduped.push(item);+ if (deduped.length >= options.limit)+ break;+ }+ return deduped;+}+function formatMemoryLines(items) {+ return items+ .map((item, i) => {+ const score = clampScore(item.score);+ const abstract = item.abstract?.trim() || item.overview?.trim() || item.uri;+ const category = item.category ?? "memory";+ return `${i + 1}. [${category}] ${abstract} (${(score * 100).toFixed(0)}%)`;+ })+ .join("\n");+}+// Query-aware ranking (ported from openclaw-plugin/memory-ranking.ts)+const PREFERENCE_QUERY_RE = /prefer|preference|favorite|favourite|like|偏好|喜欢|爱好|更倾向/i;+const TEMPORAL_QUERY_RE = /when|what time|date|day|month|year|yesterday|today|tomorrow|last|next|什么时候|何时|哪天|几月|几年|昨天|今天|明天/i;+const QUERY_TOKEN_RE = /[a-z0-9]{2,}/gi;+const QUERY_TOKEN_STOPWORDS = new Set([+ "what", "when", "where", "which", "who", "whom", "whose", "why", "how", "did", "does",+ "is", "are", "was", "were", "the", "and", "for", "with", "from", "that", "this", "your", "you",+]);+function buildQueryProfile(query) {+ const text = query.trim();+ const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) ?? [];+ const tokens = allTokens.filter((t) => !QUERY_TOKEN_STOPWORDS.has(t));+ return {+ tokens,+ wantsPreference: PREFERENCE_QUERY_RE.test(text),+ wantsTemporal: TEMPORAL_QUERY_RE.test(text),+ };+}+function lexicalOverlapBoost(tokens, text) {+ if (tokens.length === 0 || !text)+ return 0;+ const haystack = ` ${text.toLowerCase()} `;+ let matched = 0;+ for (const token of tokens.slice(0, 8)) {+ if (haystack.includes(token))+ matched += 1;+ }+ return Math.min(0.2, (matched / Math.min(tokens.length, 4)) * 0.2);+}+function rankForInjection(item, query) {+ const baseScore = clampScore(item.score);+ const abstract = (item.abstract ?? item.overview ?? "").trim();+ const leafBoost = item.level === 2 ? 0.12 : 0;+ const cat = (item.category ?? "").toLowerCase();+ const eventBoost = query.wantsTemporal && (cat === "events" || item.uri.includes("/events/")) ? 0.1 : 0;+ const prefBoost = query.wantsPreference && (cat === "preferences" || item.uri.includes("/preferences/")) ? 0.08 : 0;+ const overlapBoost = lexicalOverlapBoost(query.tokens, `${item.uri} ${abstract}`);+ return baseScore + leafBoost + eventBoost + prefBoost + overlapBoost;+}+function pickMemoriesForInjection(items, limit, queryText) {+ if (items.length === 0 || limit <= 0)+ return [];+ const query = buildQueryProfile(queryText);+ const sorted = [...items].sort((a, b) => rankForInjection(b, query) - rankForInjection(a, query));+ const deduped = [];+ const seen = new Set();+ for (const item of sorted) {+ const key = (item.abstract ?? item.overview ?? "").trim().toLowerCase() || item.uri;+ if (seen.has(key))+ continue;+ seen.add(key);+ deduped.push(item);+ }+ const leaves = deduped.filter((item) => item.level === 2);+ if (leaves.length >= limit)+ return leaves.slice(0, limit);+ const picked = [...leaves];+ const used = new Set(leaves.map((item) => item.uri));+ for (const item of deduped) {+ if (picked.length >= limit)+ break;+ if (used.has(item.uri))+ continue;+ picked.push(item);+ }+ return picked;+}+// ---------------------------------------------------------------------------+// Shared search helpers+// ---------------------------------------------------------------------------+async function searchBothScopes(client, query, limit) {+ const [userSettled, agentSettled] = await Promise.allSettled([+ client.find(query, { targetUri: "viking://user/memories", limit, scoreThreshold: 0 }),+ client.find(query, { targetUri: "viking://agent/memories", limit, scoreThreshold: 0 }),+ ]);+ const userResult = userSettled.status === "fulfilled" ? userSettled.value : { memories: [] };+ const agentResult = agentSettled.status === "fulfilled" ? agentSettled.value : { memories: [] };+ const all = [...(userResult.memories ?? []), ...(agentResult.memories ?? [])];+ // Deduplicate by URI and keep only leaf memories+ const unique = all.filter((m, i, self) => i === self.findIndex((o) => o.uri === m.uri));+ return unique.filter((m) => m.level === 2);+}+// ---------------------------------------------------------------------------+// MCP Server+// ---------------------------------------------------------------------------+const client = new OpenVikingClient(config.baseUrl, config.apiKey, config.agentId, config.timeoutMs);+const server = new McpServer({+ name: "openviking-memory",+ version: "0.1.0",+});+// -- Tool: memory_recall --------------------------------------------------+server.tool("memory_recall", "Search long-term memories from OpenViking. Use when you need past user preferences, facts, decisions, or any previously stored information.", {+ query: z.string().describe("Search query — describe what you want to recall"),+ limit: z.number().optional().describe("Max results to return (default: 6)"),+ score_threshold: z.number().optional().describe("Min relevance score 0-1 (default: 0.01)"),+ target_uri: z.string().optional().describe("Search scope URI, e.g. viking://user/memories"),+}, async ({ query, limit, score_threshold, target_uri }) => {+ const recallLimit = limit ?? config.recallLimit;+ const threshold = score_threshold ?? config.scoreThreshold;+ const candidateLimit = Math.max(recallLimit * 4, 20);+ let leafMemories;+ if (target_uri) {+ const result = await client.find(query, { targetUri: target_uri, limit: candidateLimit, scoreThreshold: 0 });+ leafMemories = (result.memories ?? []).filter((m) => m.level === 2);+ }+ else {+ leafMemories = await searchBothScopes(client, query, candidateLimit);+ }+ const processed = postProcessMemories(leafMemories, { limit: candidateLimit, scoreThreshold: threshold });+ const memories = pickMemoriesForInjection(processed, recallLimit, query);+ if (memories.length === 0) {+ return { content: [{ type: "text", text: "No relevant memories found in OpenViking." }] };+ }+ // Read full content for leaf memories+ const lines = await Promise.all(memories.map(async (item) => {+ if (item.level === 2) {+ try {+ const content = await client.read(item.uri);+ if (content?.trim())+ return `- [${item.category ?? "memory"}] ${content.trim()}`;+ }+ catch { /* fallback */ }+ }+ return `- [${item.category ?? "memory"}] ${item.abstract ?? item.uri}`;+ }));+ return {+ content: [{+ type: "text",+ text: `Found ${memories.length} relevant memories:\n\n${lines.join("\n")}\n\n---\n${formatMemoryLines(memories)}`,+ }],+ };+});+// -- Tool: memory_store ---------------------------------------------------+server.tool("memory_store", "Store information into OpenViking long-term memory. Use when the user says 'remember this', shares preferences, important facts, decisions, or any information worth persisting across sessions.", {+ text: z.string().describe("The information to store as memory"),+ role: z.string().optional().describe("Message role: 'user' (default) or 'assistant'"),+}, async ({ text, role }) => {+ const msgRole = role || "user";+ let sessionId;+ try {+ sessionId = await client.createSession();+ await client.addSessionMessage(sessionId, msgRole, text);+ const extracted = await client.extractSessionMemories(sessionId);+ if (extracted.length === 0) {+ return {+ content: [{+ type: "text",+ text: "Memory stored but extraction returned 0 memories. The text may be too short or not contain extractable information. Check OpenViking server logs for details.",+ }],+ };+ }+ return {+ content: [{+ type: "text",+ text: `Successfully extracted ${extracted.length} memory/memories from the provided text and stored them in OpenViking.`,+ }],+ };+ }+ finally {+ if (sessionId) {+ await client.deleteSession(sessionId).catch(() => { });+ }+ }+});+// -- Tool: memory_forget --------------------------------------------------+server.tool("memory_forget", "Delete a memory from OpenViking. Provide an exact URI for direct deletion, or a search query to find and delete matching memories.", {+ uri: z.string().optional().describe("Exact viking:// memory URI to delete"),+ query: z.string().optional().describe("Search query to find the memory to delete"),+ target_uri: z.string().optional().describe("Search scope URI (default: viking://user/memories)"),+}, async ({ uri, query, target_uri }) => {+ // Direct URI deletion+ if (uri) {+ if (!isMemoryUri(uri)) {+ return { content: [{ type: "text", text: `Refusing to delete non-memory URI: ${uri}` }] };+ }+ await client.deleteUri(uri);+ return { content: [{ type: "text", text: `Deleted memory: ${uri}` }] };+ }+ if (!query) {+ return { content: [{ type: "text", text: "Please provide either a uri or query parameter." }] };+ }+ // Search then delete+ const candidateLimit = 20;+ let candidates;+ if (target_uri) {+ const result = await client.find(query, { targetUri: target_uri, limit: candidateLimit, scoreThreshold: 0 });+ candidates = postProcessMemories(result.memories ?? [], {+ limit: candidateLimit,+ scoreThreshold: config.scoreThreshold,+ leafOnly: true,+ }).filter((item) => isMemoryUri(item.uri));+ }+ else {+ const leafMemories = await searchBothScopes(client, query, candidateLimit);+ candidates = postProcessMemories(leafMemories, {+ limit: candidateLimit,+ scoreThreshold: config.scoreThreshold,+ leafOnly: true,+ }).filter((item) => isMemoryUri(item.uri));+ }+ if (candidates.length === 0) {+ return { content: [{ type: "text", text: "No matching memories found. Try a more specific query." }] };+ }+ // Auto-delete if single strong match+ const top = candidates[0];+ if (candidates.length === 1 && clampScore(top.score) >= 0.85) {+ await client.deleteUri(top.uri);+ return { content: [{ type: "text", text: `Deleted memory: ${top.uri}` }] };+ }+ // List candidates for confirmation+ const list = candidates+ .map((item) => `- ${item.uri} — ${item.abstract?.trim() || "?"} (${(clampScore(item.score) * 100).toFixed(0)}%)`)+ .join("\n");+ return {+ content: [{+ type: "text",+ text: `Found ${candidates.length} candidate memories. Please specify the exact URI to delete:\n\n${list}`,+ }],+ };+});+// -- Tool: memory_health --------------------------------------------------+server.tool("memory_health", "Check whether the OpenViking memory server is reachable and healthy.", {}, async () => {+ const ok = await client.healthCheck();+ return {+ content: [{+ type: "text",+ text: ok+ ? `OpenViking is healthy (${config.baseUrl})`+ : `OpenViking is unreachable at ${config.baseUrl}. Please check if the server is running.`,+ }],+ };+});+// ---------------------------------------------------------------------------+// Start+// ---------------------------------------------------------------------------+const transport = new StdioServerTransport();+await server.connect(transport);diff --git a/examples/claude-code-memory-plugin/src/memory-server.ts b/examples/claude-code-memory-plugin/src/memory-server.tsnew file mode 100644index 000000000..2dd0ac0ad--- /dev/null+++ b/examples/claude-code-memory-plugin/src/memory-server.ts@@ -0,0 +1,637 @@+/**+ * OpenViking Memory MCP Server for Claude Code+ *+ * Exposes OpenViking long-term memory as MCP tools:+ * - memory_recall : semantic search across memories+ * - memory_store : extract and persist new memories+ * - memory_forget : delete memories by URI or query+ *+ * Ported from the OpenClaw context-engine plugin (openclaw-plugin/).+ * Adapted for Claude Code's MCP server interface (stdio transport).+ */++import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";+import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";+import { z } from "zod";+import { createHash } from "node:crypto";++// ---------------------------------------------------------------------------+// Types (ported from openclaw-plugin/client.ts)+// ---------------------------------------------------------------------------++type FindResultItem = {+ uri: string;+ level?: number;+ abstract?: string;+ overview?: string;+ category?: string;+ score?: number;+ match_reason?: string;+};++type FindResult = {+ memories?: FindResultItem[];+ resources?: FindResultItem[];+ skills?: FindResultItem[];+ total?: number;+};++type ScopeName = "user" | "agent";++// ---------------------------------------------------------------------------+// Configuration — loaded from ov.conf (shared with OpenClaw plugin).+// Env var: OPENVIKING_CONFIG_FILE (default: ~/.openviking/ov.conf)+// Plugin-specific overrides go in the optional "claude_code" section.+// ---------------------------------------------------------------------------++import { readFileSync } from "node:fs";+import { homedir } from "node:os";+import { join, resolve as resolvePath } from "node:path";++function loadOvConf(): Record<string, unknown> {+ const defaultPath = join(homedir(), ".openviking", "ov.conf");+ const configPath = resolvePath(+ (process.env.OPENVIKING_CONFIG_FILE || defaultPath).replace(/^~/, homedir()),+ );+ try {+ return JSON.parse(readFileSync(configPath, "utf-8"));+ } catch (err: unknown) {+ const code = (err as { code?: string })?.code;+ const msg = code === "ENOENT"+ ? `Config file not found: ${configPath}`+ : `Failed to read config: ${configPath}`;+ process.stderr.write(`[openviking-memory] ${msg}\n`);+ process.exit(1);+ }+}++function num(val: unknown, fallback: number): number {+ if (typeof val === "number" && Number.isFinite(val)) return val;+ if (typeof val === "string" && val.trim()) {+ const n = Number(val);+ if (Number.isFinite(n)) return n;+ }+ return fallback;+}++function str(val: unknown, fallback: string): string {+ if (typeof val === "string" && val.trim()) return val.trim();+ return fallback;+}++const file = loadOvConf();+const serverCfg = (file.server ?? {}) as Record<string, unknown>;+const cc = (file.claude_code ?? {}) as Record<string, unknown>;++const host = str(serverCfg.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");+const port = Math.floor(num(serverCfg.port, 1933));++const config = {+ baseUrl: `http://${host}:${port}`,+ apiKey: str(serverCfg.root_api_key, ""),+ agentId: str(cc.agentId, "claude-code"),+ timeoutMs: Math.max(1000, Math.floor(num(cc.timeoutMs, 15000))),+ recallLimit: Math.max(1, Math.floor(num(cc.recallLimit, 6))),+ scoreThreshold: Math.min(1, Math.max(0, num(cc.scoreThreshold, 0.01))),+};++// ---------------------------------------------------------------------------+// OpenViking HTTP Client (ported from openclaw-plugin/client.ts)+// ---------------------------------------------------------------------------++const MEMORY_URI_PATTERNS = [+ /^viking:\/\/user\/(?:[^/]+\/)?memories(?:\/|$)/,+ /^viking:\/\/agent\/(?:[^/]+\/)?memories(?:\/|$)/,+];+const USER_STRUCTURE_DIRS = new Set(["memories"]);+const AGENT_STRUCTURE_DIRS = new Set(["memories", "skills", "instructions", "workspaces"]);++function md5Short(input: string): string {+ return createHash("md5").update(input).digest("hex").slice(0, 12);+}++function isMemoryUri(uri: string): boolean {+ return MEMORY_URI_PATTERNS.some((p) => p.test(uri));+}++class OpenVikingClient {+ private resolvedSpaceByScope: Partial<Record<ScopeName, string>> = {};+ private runtimeIdentity: { userId: string; agentId: string } | null = null;++ constructor(+ private readonly baseUrl: string,+ private readonly apiKey: string,+ private readonly agentId: string,+ private readonly timeoutMs: number,+ ) {}++ private async request<T>(path: string, init: RequestInit = {}): Promise<T> {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);+ try {+ const headers = new Headers(init.headers ?? {});+ if (this.apiKey) headers.set("X-API-Key", this.apiKey);+ if (this.agentId) headers.set("X-OpenViking-Agent", this.agentId);+ if (init.body && !headers.has("Content-Type")) headers.set("Content-Type", "application/json");++ const response = await fetch(`${this.baseUrl}${path}`, {+ ...init,+ headers,+ signal: controller.signal,+ });++ const payload = (await response.json().catch(() => ({}))) as {+ status?: string;+ result?: T;+ error?: { code?: string; message?: string };+ };++ if (!response.ok || payload.status === "error") {+ const code = payload.error?.code ? ` [${payload.error.code}]` : "";+ const message = payload.error?.message ?? `HTTP ${response.status}`;+ throw new Error(`OpenViking request failed${code}: ${message}`);+ }+ return (payload.result ?? payload) as T;+ } finally {+ clearTimeout(timer);+ }+ }++ async healthCheck(): Promise<boolean> {+ try {+ await this.request<{ status: string }>("/health");+ return true;+ } catch {+ return false;+ }+ }++ private async ls(uri: string): Promise<Array<Record<string, unknown>>> {+ return this.request<Array<Record<string, unknown>>>(+ `/api/v1/fs/ls?uri=${encodeURIComponent(uri)}&output=original`,+ );+ }++ private async getRuntimeIdentity(): Promise<{ userId: string; agentId: string }> {+ if (this.runtimeIdentity) return this.runtimeIdentity;+ const fallback = { userId: "default", agentId: this.agentId || "default" };+ try {+ const status = await this.request<{ user?: unknown }>("/api/v1/system/status");+ const userId =+ typeof status.user === "string" && status.user.trim() ? status.user.trim() : "default";+ this.runtimeIdentity = { userId, agentId: this.agentId || "default" };+ return this.runtimeIdentity;+ } catch {+ this.runtimeIdentity = fallback;+ return fallback;+ }+ }++ private async resolveScopeSpace(scope: ScopeName): Promise<string> {+ const cached = this.resolvedSpaceByScope[scope];+ if (cached) return cached;++ const identity = await this.getRuntimeIdentity();+ const fallbackSpace =+ scope === "user" ? identity.userId : md5Short(`${identity.userId}:${identity.agentId}`);+ const reservedDirs = scope === "user" ? USER_STRUCTURE_DIRS : AGENT_STRUCTURE_DIRS;++ try {+ const entries = await this.ls(`viking://${scope}`);+ const spaces = entries+ .filter((e) => e?.isDir === true)+ .map((e) => (typeof e.name === "string" ? e.name.trim() : ""))+ .filter((n) => n && !n.startsWith(".") && !reservedDirs.has(n));++ if (spaces.length > 0) {+ if (spaces.includes(fallbackSpace)) {+ this.resolvedSpaceByScope[scope] = fallbackSpace;+ return fallbackSpace;+ }+ if (scope === "user" && spaces.includes("default")) {+ this.resolvedSpaceByScope[scope] = "default";+ return "default";+ }+ if (spaces.length === 1) {+ this.resolvedSpaceByScope[scope] = spaces[0]!;+ return spaces[0]!;+ }+ }+ } catch { /* fall through */ }++ this.resolvedSpaceByScope[scope] = fallbackSpace;+ return fallbackSpace;+ }++ private async normalizeTargetUri(targetUri: string): Promise<string> {+ const trimmed = targetUri.trim().replace(/\/+$/, "");+ const match = trimmed.match(/^viking:\/\/(user|agent)(?:\/(.*))?$/);+ if (!match) return trimmed;++ const scope = match[1] as ScopeName;+ const rawRest = (match[2] ?? "").trim();+ if (!rawRest) return trimmed;++ const parts = rawRest.split("/").filter(Boolean);+ if (parts.length === 0) return trimmed;++ const reservedDirs = scope === "user" ? USER_STRUCTURE_DIRS : AGENT_STRUCTURE_DIRS;+ if (!reservedDirs.has(parts[0]!)) return trimmed;++ const space = await this.resolveScopeSpace(scope);+ return `viking://${scope}/${space}/${parts.join("/")}`;+ }++ async find(+ query: string,+ options: { targetUri: string; limit: number; scoreThreshold?: number },+ ): Promise<FindResult> {+ const normalizedTargetUri = await this.normalizeTargetUri(options.targetUri);+ return this.request<FindResult>("/api/v1/search/find", {+ method: "POST",+ body: JSON.stringify({+ query,+ target_uri: normalizedTargetUri,+ limit: options.limit,+ score_threshold: options.scoreThreshold,+ }),+ });+ }++ async read(uri: string): Promise<string> {+ return this.request<string>(`/api/v1/content/read?uri=${encodeURIComponent(uri)}`);+ }++ async createSession(): Promise<string> {+ const result = await this.request<{ session_id: string }>("/api/v1/sessions", {+ method: "POST",+ body: JSON.stringify({}),+ });+ return result.session_id;+ }++ async addSessionMessage(sessionId: string, role: string, content: string): Promise<void> {+ await this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`, {+ method: "POST",+ body: JSON.stringify({ role, content }),+ });+ }++ async extractSessionMemories(sessionId: string): Promise<Array<Record<string, unknown>>> {+ return this.request<Array<Record<string, unknown>>>(+ `/api/v1/sessions/${encodeURIComponent(sessionId)}/extract`,+ { method: "POST", body: JSON.stringify({}) },+ );+ }++ async deleteSession(sessionId: string): Promise<void> {+ await this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}`, { method: "DELETE" });+ }++ async deleteUri(uri: string): Promise<void> {+ await this.request(`/api/v1/fs?uri=${encodeURIComponent(uri)}&recursive=false`, {+ method: "DELETE",+ });+ }+}++// ---------------------------------------------------------------------------+// Memory ranking helpers (ported from openclaw-plugin/memory-ranking.ts)+// ---------------------------------------------------------------------------++function clampScore(value: number | undefined): number {+ if (typeof value !== "number" || Number.isNaN(value)) return 0;+ return Math.max(0, Math.min(1, value));+}++function normalizeDedupeText(text: string): string {+ return text.toLowerCase().replace(/\s+/g, " ").trim();+}++function getMemoryDedupeKey(item: FindResultItem): string {+ const abstract = normalizeDedupeText(item.abstract ?? item.overview ?? "");+ const category = (item.category ?? "").toLowerCase() || "unknown";+ if (abstract) return `abstract:${category}:${abstract}`;+ return `uri:${item.uri}`;+}++function postProcessMemories(+ items: FindResultItem[],+ options: { limit: number; scoreThreshold: number; leafOnly?: boolean },+): FindResultItem[] {+ const deduped: FindResultItem[] = [];+ const seen = new Set<string>();+ const sorted = [...items].sort((a, b) => clampScore(b.score) - clampScore(a.score));+ for (const item of sorted) {+ if (options.leafOnly && item.level !== 2) continue;+ if (clampScore(item.score) < options.scoreThreshold) continue;+ const key = getMemoryDedupeKey(item);+ if (seen.has(key)) continue;+ seen.add(key);+ deduped.push(item);+ if (deduped.length >= options.limit) break;+ }+ return deduped;+}++function formatMemoryLines(items: FindResultItem[]): string {+ return items+ .map((item, i) => {+ const score = clampScore(item.score);+ const abstract = item.abstract?.trim() || item.overview?.trim() || item.uri;+ const category = item.category ?? "memory";+ return `${i + 1}. [${category}] ${abstract} (${(score * 100).toFixed(0)}%)`;+ })+ .join("\n");+}++// Query-aware ranking (ported from openclaw-plugin/memory-ranking.ts)+const PREFERENCE_QUERY_RE = /prefer|preference|favorite|favourite|like|偏好|喜欢|爱好|更倾向/i;+const TEMPORAL_QUERY_RE =+ /when|what time|date|day|month|year|yesterday|today|tomorrow|last|next|什么时候|何时|哪天|几月|几年|昨天|今天|明天/i;+const QUERY_TOKEN_RE = /[a-z0-9]{2,}/gi;+const QUERY_TOKEN_STOPWORDS = new Set([+ "what","when","where","which","who","whom","whose","why","how","did","does",+ "is","are","was","were","the","and","for","with","from","that","this","your","you",+]);++function buildQueryProfile(query: string) {+ const text = query.trim();+ const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) ?? [];+ const tokens = allTokens.filter((t) => !QUERY_TOKEN_STOPWORDS.has(t));+ return {+ tokens,+ wantsPreference: PREFERENCE_QUERY_RE.test(text),+ wantsTemporal: TEMPORAL_QUERY_RE.test(text),+ };+}++function lexicalOverlapBoost(tokens: string[], text: string): number {+ if (tokens.length === 0 || !text) return 0;+ const haystack = ` ${text.toLowerCase()} `;+ let matched = 0;+ for (const token of tokens.slice(0, 8)) {+ if (haystack.includes(token)) matched += 1;+ }+ return Math.min(0.2, (matched / Math.min(tokens.length, 4)) * 0.2);+}++function rankForInjection(item: FindResultItem, query: ReturnType<typeof buildQueryProfile>): number {+ const baseScore = clampScore(item.score);+ const abstract = (item.abstract ?? item.overview ?? "").trim();+ const leafBoost = item.level === 2 ? 0.12 : 0;+ const cat = (item.category ?? "").toLowerCase();+ const eventBoost = query.wantsTemporal && (cat === "events" || item.uri.includes("/events/")) ? 0.1 : 0;+ const prefBoost = query.wantsPreference && (cat === "preferences" || item.uri.includes("/preferences/")) ? 0.08 : 0;+ const overlapBoost = lexicalOverlapBoost(query.tokens, `${item.uri} ${abstract}`);+ return baseScore + leafBoost + eventBoost + prefBoost + overlapBoost;+}++function pickMemoriesForInjection(items: FindResultItem[], limit: number, queryText: string): FindResultItem[] {+ if (items.length === 0 || limit <= 0) return [];+ const query = buildQueryProfile(queryText);+ const sorted = [...items].sort((a, b) => rankForInjection(b, query) - rankForInjection(a, query));++ const deduped: FindResultItem[] = [];+ const seen = new Set<string>();+ for (const item of sorted) {+ const key = (item.abstract ?? item.overview ?? "").trim().toLowerCase() || item.uri;+ if (seen.has(key)) continue;+ seen.add(key);+ deduped.push(item);+ }++ const leaves = deduped.filter((item) => item.level === 2);+ if (leaves.length >= limit) return leaves.slice(0, limit);++ const picked = [...leaves];+ const used = new Set(leaves.map((item) => item.uri));+ for (const item of deduped) {+ if (picked.length >= limit) break;+ if (used.has(item.uri)) continue;+ picked.push(item);+ }+ return picked;+}++// ---------------------------------------------------------------------------+// Shared search helpers+// ---------------------------------------------------------------------------++async function searchBothScopes(+ client: OpenVikingClient,+ query: string,+ limit: number,+): Promise<FindResultItem[]> {+ const [userSettled, agentSettled] = await Promise.allSettled([+ client.find(query, { targetUri: "viking://user/memories", limit, scoreThreshold: 0 }),+ client.find(query, { targetUri: "viking://agent/memories", limit, scoreThreshold: 0 }),+ ]);++ const userResult = userSettled.status === "fulfilled" ? userSettled.value : { memories: [] };+ const agentResult = agentSettled.status === "fulfilled" ? agentSettled.value : { memories: [] };++ const all = [...(userResult.memories ?? []), ...(agentResult.memories ?? [])];+ // Deduplicate by URI and keep only leaf memories+ const unique = all.filter((m, i, self) => i === self.findIndex((o) => o.uri === m.uri));+ return unique.filter((m) => m.level === 2);+}++// ---------------------------------------------------------------------------+// MCP Server+// ---------------------------------------------------------------------------++const client = new OpenVikingClient(config.baseUrl, config.apiKey, config.agentId, config.timeoutMs);++const server = new McpServer({+ name: "openviking-memory",+ version: "0.1.0",+});++// -- Tool: memory_recall --------------------------------------------------++server.tool(+ "memory_recall",+ "Search long-term memories from OpenViking. Use when you need past user preferences, facts, decisions, or any previously stored information.",+ {+ query: z.string().describe("Search query — describe what you want to recall"),+ limit: z.number().optional().describe("Max results to return (default: 6)"),+ score_threshold: z.number().optional().describe("Min relevance score 0-1 (default: 0.01)"),+ target_uri: z.string().optional().describe("Search scope URI, e.g. viking://user/memories"),+ },+ async ({ query, limit, score_threshold, target_uri }) => {+ const recallLimit = limit ?? config.recallLimit;+ const threshold = score_threshold ?? config.scoreThreshold;+ const candidateLimit = Math.max(recallLimit * 4, 20);++ let leafMemories: FindResultItem[];+ if (target_uri) {+ const result = await client.find(query, { targetUri: target_uri, limit: candidateLimit, scoreThreshold: 0 });+ leafMemories = (result.memories ?? []).filter((m) => m.level === 2);+ } else {+ leafMemories = await searchBothScopes(client, query, candidateLimit);+ }++ const processed = postProcessMemories(leafMemories, { limit: candidateLimit, scoreThreshold: threshold });+ const memories = pickMemoriesForInjection(processed, recallLimit, query);++ if (memories.length === 0) {+ return { content: [{ type: "text" as const, text: "No relevant memories found in OpenViking." }] };+ }++ // Read full content for leaf memories+ const lines = await Promise.all(+ memories.map(async (item) => {+ if (item.level === 2) {+ try {+ const content = await client.read(item.uri);+ if (content?.trim()) return `- [${item.category ?? "memory"}] ${content.trim()}`;+ } catch { /* fallback */ }+ }+ return `- [${item.category ?? "memory"}] ${item.abstract ?? item.uri}`;+ }),+ );++ return {+ content: [{+ type: "text" as const,+ text: `Found ${memories.length} relevant memories:\n\n${lines.join("\n")}\n\n---\n${formatMemoryLines(memories)}`,+ }],+ };+ },+);++// -- Tool: memory_store ---------------------------------------------------++server.tool(+ "memory_store",+ "Store information into OpenViking long-term memory. Use when the user says 'remember this', shares preferences, important facts, decisions, or any information worth persisting across sessions.",+ {+ text: z.string().describe("The information to store as memory"),+ role: z.string().optional().describe("Message role: 'user' (default) or 'assistant'"),+ },+ async ({ text, role }) => {+ const msgRole = role || "user";+ let sessionId: string | undefined;+ try {+ sessionId = await client.createSession();+ await client.addSessionMessage(sessionId, msgRole, text);+ const extracted = await client.extractSessionMemories(sessionId);++ if (extracted.length === 0) {+ return {+ content: [{+ type: "text" as const,+ text: "Memory stored but extraction returned 0 memories. The text may be too short or not contain extractable information. Check OpenViking server logs for details.",+ }],+ };+ }++ return {+ content: [{+ type: "text" as const,+ text: `Successfully extracted ${extracted.length} memory/memories from the provided text and stored them in OpenViking.`,+ }],+ };+ } finally {+ if (sessionId) {+ await client.deleteSession(sessionId).catch(() => {});+ }+ }+ },+);++// -- Tool: memory_forget --------------------------------------------------++server.tool(+ "memory_forget",+ "Delete a memory from OpenViking. Provide an exact URI for direct deletion, or a search query to find and delete matching memories.",+ {+ uri: z.string().optional().describe("Exact viking:// memory URI to delete"),+ query: z.string().optional().describe("Search query to find the memory to delete"),+ target_uri: z.string().optional().describe("Search scope URI (default: viking://user/memories)"),+ },+ async ({ uri, query, target_uri }) => {+ // Direct URI deletion+ if (uri) {+ if (!isMemoryUri(uri)) {+ return { content: [{ type: "text" as const, text: `Refusing to delete non-memory URI: ${uri}` }] };+ }+ await client.deleteUri(uri);+ return { content: [{ type: "text" as const, text: `Deleted memory: ${uri}` }] };+ }++ if (!query) {+ return { content: [{ type: "text" as const, text: "Please provide either a uri or query parameter." }] };+ }++ // Search then delete+ const candidateLimit = 20;+ let candidates: FindResultItem[];++ if (target_uri) {+ const result = await client.find(query, { targetUri: target_uri, limit: candidateLimit, scoreThreshold: 0 });+ candidates = postProcessMemories(result.memories ?? [], {+ limit: candidateLimit,+ scoreThreshold: config.scoreThreshold,+ leafOnly: true,+ }).filter((item) => isMemoryUri(item.uri));+ } else {+ const leafMemories = await searchBothScopes(client, query, candidateLimit);+ candidates = postProcessMemories(leafMemories, {+ limit: candidateLimit,+ scoreThreshold: config.scoreThreshold,+ leafOnly: true,+ }).filter((item) => isMemoryUri(item.uri));+ }++ if (candidates.length === 0) {+ return { content: [{ type: "text" as const, text: "No matching memories found. Try a more specific query." }] };+ }++ // Auto-delete if single strong match+ const top = candidates[0]!;+ if (candidates.length === 1 && clampScore(top.score) >= 0.85) {+ await client.deleteUri(top.uri);+ return { content: [{ type: "text" as const, text: `Deleted memory: ${top.uri}` }] };+ }++ // List candidates for confirmation+ const list = candidates+ .map((item) => `- ${item.uri} — ${item.abstract?.trim() || "?"} (${(clampScore(item.score) * 100).toFixed(0)}%)`)+ .join("\n");++ return {+ content: [{+ type: "text" as const,+ text: `Found ${candidates.length} candidate memories. Please specify the exact URI to delete:\n\n${list}`,+ }],+ };+ },+);++// -- Tool: memory_health --------------------------------------------------++server.tool(+ "memory_health",+ "Check whether the OpenViking memory server is reachable and healthy.",+ {},+ async () => {+ const ok = await client.healthCheck();+ return {+ content: [{+ type: "text" as const,+ text: ok+ ? `OpenViking is healthy (${config.baseUrl})`+ : `OpenViking is unreachable at ${config.baseUrl}. Please check if the server is running.`,+ }],+ };+ },+);++// ---------------------------------------------------------------------------+// Start+// ---------------------------------------------------------------------------++const transport = new StdioServerTransport();+await server.connect(transport);diff --git a/examples/claude-code-memory-plugin/tsconfig.json b/examples/claude-code-memory-plugin/tsconfig.jsonnew file mode 100644index 000000000..7f284c9a1--- /dev/null+++ b/examples/claude-code-memory-plugin/tsconfig.json@@ -0,0 +1,15 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "outDir": "./servers",+ "rootDir": "./src",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "declaration": false,+ "sourceMap": false+ },+ "include": ["src/**/*.ts"]+}diff --git a/examples/claude-memory-plugin/.claude-plugin/plugin.json b/examples/claude-memory-plugin/.claude-plugin/plugin.jsondeleted file mode 100644index 786842361..000000000--- a/examples/claude-memory-plugin/.claude-plugin/plugin.json+++ /dev/null@@ -1,5 +0,0 @@-{- "name": "openviking-memory",- "version": "0.1.0",- "description": "Persistent memory for Claude Code powered by OpenViking sessions"-}diff --git a/examples/claude-memory-plugin/README.md b/examples/claude-memory-plugin/README.mddeleted file mode 100644index 3961a97b0..000000000--- a/examples/claude-memory-plugin/README.md+++ /dev/null@@ -1,99 +0,0 @@-# OpenViking Claude Memory Plugin (Scheme B)--Claude Code memory plugin built on **OpenViking Session memory**.--- Session data is accumulated during a Claude session (`Stop` hook).-- At `SessionEnd`, plugin calls `session.commit()` to trigger OpenViking memory extraction.-- Memory recall is handled by `memory-recall` skill.--## Design choices in this version--- Mode: **auto switch**- - Try HTTP first (from `./ov.conf` `server.host` + `server.port`, health check `/health`)- - Fallback to embedded local mode if server is unreachable-- Config: **strict**- - Must have `./ov.conf` in project root-- Plugin state dir: `./.openviking/memory/`--## Structure--```text-examples/claude-memory-plugin/-├── .claude-plugin/-│ └── plugin.json-├── hooks/-│ ├── hooks.json-│ ├── common.sh-│ ├── session-start.sh-│ ├── user-prompt-submit.sh-│ ├── stop.sh-│ └── session-end.sh-├── scripts/-│ ├── ov_memory.py-│ └── run_e2e_claude_session.sh-└── skills/- └── memory-recall/- └── SKILL.md-```--## Hook behavior--- `SessionStart`- - Validate `./ov.conf`- - Auto-detect backend mode (http/local)- - Create a new OpenViking session and persist plugin state-- `UserPromptSubmit`- - Adds lightweight hint that memory is available-- `Stop` (async)- - Parse transcript last turn- - Summarize turn (uses `claude -p --model haiku` when available; fallback to local summary)- - Append user + assistant summary to OpenViking session- - Deduplicate by last user turn UUID-- `SessionEnd`- - Commit OpenViking session to extract long-term memories--## Skill behavior--`memory-recall` runs bridge command:--```bash-python3 .../ov_memory.py recall --query "<query>" --top-k 5-```--It searches:--- `viking://user/memories/`-- `viking://agent/memories/`--Then returns concise, source-linked memory summaries.--## One-click E2E--Run a real Claude headless session end-to-end using source config:--```bash-cd /Users/quemingjian/.codex/worktrees/6e45/OpenViking-bash /Users/quemingjian/.codex/worktrees/6e45/OpenViking/examples/claude-memory-plugin/scripts/run_e2e_claude_session.sh-```--Custom source config and prompt:--```bash-bash /Users/quemingjian/.codex/worktrees/6e45/OpenViking/examples/claude-memory-plugin/scripts/run_e2e_claude_session.sh \- /Users/quemingjian/Source/OpenViking/ov.conf \- "请只回复: CUSTOM_E2E_TOKEN"-```--What the script does:--- Creates a Python 3.11 virtual environment under `/tmp` (one-time dependency install).-- Generates a temporary project `./ov.conf` from source config and injects HTTP server fields.-- Starts OpenViking HTTP server, runs a real `claude -p` session with this plugin, then triggers deterministic Stop + SessionEnd validation.-- Verifies `session_state.json`, `ingested_turns >= 1`, and session archive file creation.-- Restores original `./ov.conf` when done.--## Notes--- This MVP does not modify OpenViking core.-- If `./ov.conf` is missing, hooks degrade safely and report status in systemMessage.-- State file: `./.openviking/memory/session_state.json`diff --git a/examples/claude-memory-plugin/hooks/common.sh b/examples/claude-memory-plugin/hooks/common.shdeleted file mode 100755index 661d928aa..000000000--- a/examples/claude-memory-plugin/hooks/common.sh+++ /dev/null@@ -1,96 +0,0 @@-#!/usr/bin/env bash-# Shared helpers for OpenViking Claude Code hooks.--set -euo pipefail--INPUT="$(cat || true)"--for p in "$HOME/.local/bin" "$HOME/.cargo/bin" "$HOME/bin" "/usr/local/bin"; do- [[ -d "$p" ]] && [[ ":$PATH:" != *":$p:"* ]] && export PATH="$p:$PATH"-done--SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"-PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$SCRIPT_DIR/.." && pwd)}"-PROJECT_DIR="${CLAUDE_PROJECT_DIR:-$(pwd)}"--STATE_DIR="$PROJECT_DIR/.openviking/memory"-STATE_FILE="$STATE_DIR/session_state.json"-OV_CONF="$PROJECT_DIR/ov.conf"-BRIDGE="$PLUGIN_ROOT/scripts/ov_memory.py"--if command -v python3 >/dev/null 2>&1; then- PYTHON_BIN="python3"-elif command -v python >/dev/null 2>&1; then- PYTHON_BIN="python"-else- PYTHON_BIN=""-fi--_json_val() {- local json="$1" key="$2" default="${3:-}"- local result=""-- if command -v jq >/dev/null 2>&1; then- result=$(printf '%s' "$json" | jq -r ".${key} // empty" 2>/dev/null) || true- elif [[ -n "$PYTHON_BIN" ]]; then- result=$(- "$PYTHON_BIN" -c '-import json, sys-obj = json.loads(sys.argv[1])-val = obj-for k in sys.argv[2].split("."):- if isinstance(val, dict):- val = val.get(k)- else:- val = None- break-if val is None:- print("")-elif isinstance(val, bool):- print("true" if val else "false")-else:- print(val)-' "$json" "$key" 2>/dev/null- ) || true- fi-- if [[ -z "$result" ]]; then- printf '%s' "$default"- else- printf '%s' "$result"- fi-}--_json_encode_str() {- local str="$1"- if command -v jq >/dev/null 2>&1; then- printf '%s' "$str" | jq -Rs .- return 0- fi- if [[ -n "$PYTHON_BIN" ]]; then- printf '%s' "$str" | "$PYTHON_BIN" -c 'import json,sys; print(json.dumps(sys.stdin.read()))'- return 0- fi- printf '"%s"' "$str"-}--ensure_state_dir() {- mkdir -p "$STATE_DIR"-}--run_bridge() {- if [[ -z "$PYTHON_BIN" ]]; then- echo '{"ok": false, "error": "python not found"}'- return 1- fi- if [[ ! -f "$BRIDGE" ]]; then- echo '{"ok": false, "error": "bridge script not found"}'- return 1- fi-- ensure_state_dir- "$PYTHON_BIN" "$BRIDGE" \- --project-dir "$PROJECT_DIR" \- --state-file "$STATE_FILE" \- "$@"-}diff --git a/examples/claude-memory-plugin/hooks/hooks.json b/examples/claude-memory-plugin/hooks/hooks.jsondeleted file mode 100644index bfaecf328..000000000--- a/examples/claude-memory-plugin/hooks/hooks.json+++ /dev/null@@ -1,50 +0,0 @@-{- "description": "OpenViking memory hooks for Claude Code",- "hooks": {- "SessionStart": [- {- "hooks": [- {- "type": "command",- "command": "bash ${CLAUDE_PLUGIN_ROOT}/hooks/session-start.sh",- "timeout": 12- }- ]- }- ],- "UserPromptSubmit": [- {- "hooks": [- {- "type": "command",- "command": "bash ${CLAUDE_PLUGIN_ROOT}/hooks/user-prompt-submit.sh",- "timeout": 8- }- ]- }- ],- "Stop": [- {- "hooks": [- {- "type": "command",- "command": "bash ${CLAUDE_PLUGIN_ROOT}/hooks/stop.sh",- "async": true,- "timeout": 120- }- ]- }- ],- "SessionEnd": [- {- "hooks": [- {- "type": "command",- "command": "bash ${CLAUDE_PLUGIN_ROOT}/hooks/session-end.sh",- "timeout": 20- }- ]- }- ]- }-}diff --git a/examples/claude-memory-plugin/hooks/session-end.sh b/examples/claude-memory-plugin/hooks/session-end.shdeleted file mode 100755index 3640517f3..000000000--- a/examples/claude-memory-plugin/hooks/session-end.sh+++ /dev/null@@ -1,20 +0,0 @@-#!/usr/bin/env bash-# SessionEnd hook: commit OpenViking session and extract long-term memories.--SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"-source "$SCRIPT_DIR/common.sh"--if [[ ! -f "$OV_CONF" || ! -f "$STATE_FILE" ]]; then- exit 0-fi--OUT="$(run_bridge session-end 2>/dev/null || true)"-STATUS="$(_json_val "$OUT" "status_line" "")"--if [[ -n "$STATUS" ]]; then- json_status=$(_json_encode_str "$STATUS")- echo "{\"systemMessage\": $json_status}"- exit 0-fi--exit 0diff --git a/examples/claude-memory-plugin/hooks/session-start.sh b/examples/claude-memory-plugin/hooks/session-start.shdeleted file mode 100755index 5811e8b2f..000000000--- a/examples/claude-memory-plugin/hooks/session-start.sh+++ /dev/null@@ -1,27 +0,0 @@-#!/usr/bin/env bash-# SessionStart hook: initialize OpenViking memory session.--SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"-source "$SCRIPT_DIR/common.sh"--if [[ ! -f "$OV_CONF" ]]; then- msg='[openviking-memory] ERROR: ./ov.conf not found (strict mode)'- json_msg=$(_json_encode_str "$msg")- echo "{\"systemMessage\": $json_msg}"- exit 0-fi--OUT="$(run_bridge session-start 2>/dev/null || true)"-OK="$(_json_val "$OUT" "ok" "false")"-STATUS="$(_json_val "$OUT" "status_line" "[openviking-memory] initialization failed")"-ADDL="$(_json_val "$OUT" "additional_context" "")"--json_status=$(_json_encode_str "$STATUS")--if [[ "$OK" == "true" && -n "$ADDL" ]]; then- json_addl=$(_json_encode_str "$ADDL")- echo "{\"systemMessage\": $json_status, \"hookSpecificOutput\": {\"hookEventName\": \"SessionStart\", \"additionalContext\": $json_addl}}"- exit 0-fi--echo "{\"systemMessage\": $json_status}"diff --git a/examples/claude-memory-plugin/hooks/stop.sh b/examples/claude-memory-plugin/hooks/stop.shdeleted file mode 100755index 67fb15e22..000000000--- a/examples/claude-memory-plugin/hooks/stop.sh+++ /dev/null@@ -1,26 +0,0 @@-#!/usr/bin/env bash-# Stop hook: ingest latest turn into OpenViking session memory.--SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"-source "$SCRIPT_DIR/common.sh"--STOP_HOOK_ACTIVE="$(_json_val "$INPUT" "stop_hook_active" "false")"-if [[ "$STOP_HOOK_ACTIVE" == "true" ]]; then- echo '{}'- exit 0-fi--if [[ ! -f "$OV_CONF" || ! -f "$STATE_FILE" ]]; then- echo '{}'- exit 0-fi--TRANSCRIPT_PATH="$(_json_val "$INPUT" "transcript_path" "")"-if [[ -z "$TRANSCRIPT_PATH" || ! -f "$TRANSCRIPT_PATH" ]]; then- echo '{}'- exit 0-fi--run_bridge ingest-stop --transcript-path "$TRANSCRIPT_PATH" >/dev/null 2>&1 || true--echo '{}'diff --git a/examples/claude-memory-plugin/hooks/user-prompt-submit.sh b/examples/claude-memory-plugin/hooks/user-prompt-submit.shdeleted file mode 100755index f5a080914..000000000--- a/examples/claude-memory-plugin/hooks/user-prompt-submit.sh+++ /dev/null@@ -1,18 +0,0 @@-#!/usr/bin/env bash-# UserPromptSubmit hook: lightweight memory availability hint.--SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"-source "$SCRIPT_DIR/common.sh"--PROMPT="$(_json_val "$INPUT" "prompt" "")"-if [[ -z "$PROMPT" || ${#PROMPT} -lt 10 ]]; then- echo '{}'- exit 0-fi--if [[ ! -f "$OV_CONF" || ! -f "$STATE_FILE" ]]; then- echo '{}'- exit 0-fi--echo '{"systemMessage":"[openviking-memory] Memory available (use memory-recall when historical context matters)"}'diff --git a/examples/claude-memory-plugin/scripts/ov_memory.py b/examples/claude-memory-plugin/scripts/ov_memory.pydeleted file mode 100755index a249c8e87..000000000--- a/examples/claude-memory-plugin/scripts/ov_memory.py+++ /dev/null@@ -1,717 +0,0 @@-#!/usr/bin/env python3-"""OpenViking memory bridge for Claude Code hooks.--This script provides a stable interface for hook scripts:-- session-start: detect backend mode and open an OpenViking session-- ingest-stop: parse transcript last turn and append to session-- session-end: commit session to trigger OpenViking memory extraction-- recall: search extracted memories for skill-based retrieval-"""--from __future__ import annotations--import argparse-import json-import os-import shutil-import subprocess-import time-from dataclasses import dataclass-from pathlib import Path-from typing import Any, Dict, List, Optional-from urllib import error, request---@dataclass-class BackendInfo:- mode: str # "http" | "local"- url: str = ""- api_key: str = ""- local_data_path: str = ""---def _load_json(path: Path) -> Dict[str, Any]:- with open(path, "r", encoding="utf-8") as f:- return json.load(f)---def _save_json(path: Path, data: Dict[str, Any]) -> None:- path.parent.mkdir(parents=True, exist_ok=True)- with open(path, "w", encoding="utf-8") as f:- json.dump(data, f, ensure_ascii=False, indent=2)---def _load_state(path: Path) -> Dict[str, Any]:- if not path.exists():- return {}- try:- return _load_json(path)- except Exception:- return {}---def _health_check(url: str, timeout: float = 1.2) -> bool:- try:- with request.urlopen(f"{url.rstrip('/')}/health", timeout=timeout) as resp:- if resp.status != 200:- return False- payload = json.loads(resp.read().decode("utf-8"))- return payload.get("status") == "ok"- except (error.URLError, error.HTTPError, TimeoutError, ValueError, OSError):- return False---def _resolve_local_data_path(project_dir: Path, ov_conf: Dict[str, Any]) -> str:- raw = ov_conf.get("storage", {}).get("vectordb", {}).get("path", "./data")- if not raw:- raw = "./data"- p = Path(str(raw)).expanduser()- if not p.is_absolute():- p = project_dir / p- return str(p)---def detect_backend(project_dir: Path, ov_conf: Dict[str, Any]) -> BackendInfo:- server_cfg = ov_conf.get("server", {}) if isinstance(ov_conf, dict) else {}- host = str(server_cfg.get("host", "")).strip()- port = server_cfg.get("port")- api_key = server_cfg.get("api_key") or ""-- if host and port:- if host in {"0.0.0.0", "::", "[::]"}:- host = "127.0.0.1"- if host.startswith("http://") or host.startswith("https://"):- base = host.rstrip("/")- url = f"{base}:{port}" if ":" not in base.split("//", 1)[-1] else base- else:- url = f"http://{host}:{port}"-- if _health_check(url):- return BackendInfo(mode="http", url=url, api_key=str(api_key))-- return BackendInfo(- mode="local",- local_data_path=_resolve_local_data_path(project_dir, ov_conf),- )---class OVClient:- def __init__(self, backend: BackendInfo, ov_conf_path: Path):- self.backend = backend- self.ov_conf_path = ov_conf_path- self.client: Any = None-- def __enter__(self) -> "OVClient":- if self.backend.mode == "http":- from openviking import SyncHTTPClient-- self.client = SyncHTTPClient(- url=self.backend.url,- api_key=self.backend.api_key or None,- )- self.client.initialize()- return self-- os.environ["OPENVIKING_CONFIG_FILE"] = str(self.ov_conf_path)- from openviking import SyncOpenViking-- self.client = SyncOpenViking(path=self.backend.local_data_path)- self.client.initialize()- return self-- def __exit__(self, exc_type, exc, tb) -> None:- if self.client is not None:- try:- self.client.close()- except Exception:- pass-- def create_session(self) -> Dict[str, Any]:- return self.client.create_session()-- def add_message(- self,- session_id: str,- role: str,- content: str | None = None,- parts: list[dict] | None = None,- ) -> Dict[str, Any]:- return self.client.add_message(session_id, role, content, parts)-- def commit_session(self, session_id: str) -> Dict[str, Any]:- return self.client.commit_session(session_id)-- def find(self, query: str, target_uri: str, limit: int) -> Any:- return self.client.find(query=query, target_uri=target_uri, limit=limit)-- def read(self, uri: str) -> str:- return self.client.read(uri)---def _as_text(value: Any) -> str:- if value is None:- return ""- if isinstance(value, str):- return value.strip()- return str(value).strip()---def _short(text: str, n: int) -> str:- t = " ".join(text.split())- if len(t) <= n:- return t- return t[: n - 3] + "..."---def _extract_text_parts(content: Any) -> str:- if isinstance(content, str):- return content.strip()- if not isinstance(content, list):- return ""-- chunks: List[str] = []- for block in content:- if not isinstance(block, dict):- continue- if block.get("type") == "text":- text = _as_text(block.get("text", ""))- if text:- chunks.append(text)- return "\n".join(chunks).strip()---def _extract_tool_result(content: Any) -> str:- if not isinstance(content, list):- return ""- if not content:- return ""-- first = content[0]- if not isinstance(first, dict) or first.get("type") != "tool_result":- return ""-- payload = first.get("content")- if isinstance(payload, str):- return _short(payload, 220)- if isinstance(payload, list):- buf: List[str] = []- for item in payload:- if isinstance(item, dict) and item.get("type") == "text":- t = _as_text(item.get("text", ""))- if t:- buf.append(t)- return _short("\n".join(buf), 220)- return _short(_as_text(payload), 220)---def _is_user_prompt(entry: Dict[str, Any]) -> bool:- if entry.get("type") != "user":- return False- msg = entry.get("message", {})- content = msg.get("content")- if _extract_tool_result(content):- return False- return bool(_extract_text_parts(content))---def _assistant_chunks(entry: Dict[str, Any]) -> List[str]:- if entry.get("type") != "assistant":- return []-- msg = entry.get("message", {})- content = msg.get("content")-- if isinstance(content, str):- text = _as_text(content)- return [text] if text else []-- if not isinstance(content, list):- return []-- chunks: List[str] = []- for block in content:- if not isinstance(block, dict):- continue- btype = block.get("type")-- if btype == "text":- text = _as_text(block.get("text", ""))- if text:- chunks.append(text)- elif btype == "tool_use":- name = _as_text(block.get("name", "tool"))- raw_input = block.get("input")- try:- inp = _short(json.dumps(raw_input, ensure_ascii=False), 180)- except Exception:- inp = _short(_as_text(raw_input), 180)- chunks.append(f"[tool-use] {name}({inp})")-- return chunks---def _read_jsonl(path: Path) -> List[Dict[str, Any]]:- rows: List[Dict[str, Any]] = []- with open(path, "r", encoding="utf-8") as f:- for line in f:- line = line.strip()- if not line:- continue- try:- obj = json.loads(line)- except json.JSONDecodeError:- continue- if isinstance(obj, dict):- rows.append(obj)- return rows---def extract_last_turn(transcript_path: Path) -> Optional[Dict[str, str]]:- rows = _read_jsonl(transcript_path)- if not rows:- return None-- last_user_idx = -1- for i, row in enumerate(rows):- if _is_user_prompt(row):- last_user_idx = i-- if last_user_idx < 0:- return None-- user_row = rows[last_user_idx]- user_text = _extract_text_parts(user_row.get("message", {}).get("content"))- turn_uuid = _as_text(user_row.get("uuid") or user_row.get("id"))-- chunks: List[str] = []- for row in rows[last_user_idx + 1 :]:- if _is_user_prompt(row):- break-- if row.get("type") == "assistant":- chunks.extend(_assistant_chunks(row))- continue-- if row.get("type") == "user":- tool_result = _extract_tool_result(row.get("message", {}).get("content"))- if tool_result:- chunks.append(f"[tool-result] {tool_result}")-- assistant_text = "\n".join([c for c in chunks if c]).strip()-- if not turn_uuid:- turn_uuid = str(abs(hash(user_text + assistant_text)))-- if not user_text and not assistant_text:- return None-- return {- "turn_uuid": turn_uuid,- "user_text": user_text,- "assistant_text": assistant_text,- }---def _summarize_with_claude(raw: str) -> str:- if not shutil.which("claude"):- return ""-- system_prompt = (- "You are a session memory writer. Output ONLY 3-6 bullet points. "- "Each line must start with '- '. Focus on decisions, fixes, and concrete changes. "- "No intro or outro."- )-- try:- proc = subprocess.run(- [- "claude",- "-p",- "--model",- "haiku",- "--no-session-persistence",- "--no-chrome",- "--system-prompt",- system_prompt,- ],- input=raw,- text=True,- capture_output=True,- timeout=45,- check=False,- )- except Exception:- return ""-- if proc.returncode != 0:- return ""- return proc.stdout.strip()---def _fallback_summary(turn: Dict[str, str]) -> str:- user = _short(turn.get("user_text", ""), 200)- assistant = _short(turn.get("assistant_text", ""), 360)- lines = []- if user:- lines.append(f"- User request: {user}")- if assistant:- lines.append(f"- Assistant response: {assistant}")- if not lines:- lines.append("- Captured a conversation turn.")- return "\n".join(lines)---def summarize_turn(turn: Dict[str, str]) -> str:- raw = (- "Summarize this conversation turn for long-term engineering memory.\n\n"- f"User:\n{turn.get('user_text', '')}\n\n"- f"Assistant:\n{turn.get('assistant_text', '')}\n"- )- summary = _summarize_with_claude(raw)- if summary:- return summary- return _fallback_summary(turn)---def _contexts_from_find_result(result: Any) -> List[Dict[str, Any]]:- contexts: List[Dict[str, Any]] = []-- def push(obj: Any) -> None:- if obj is None:- return- uri = _as_text(getattr(obj, "uri", "") if not isinstance(obj, dict) else obj.get("uri"))- if not uri:- return-- score = getattr(obj, "score", None) if not isinstance(obj, dict) else obj.get("score")- abstract = (- getattr(obj, "abstract", "") if not isinstance(obj, dict) else obj.get("abstract", "")- )- contexts.append(- {- "uri": uri,- "score": float(score or 0.0),- "abstract": _as_text(abstract),- }- )-- if isinstance(result, dict):- for key in ("memories", "resources", "skills"):- for row in result.get(key, []) or []:- push(row)- return contexts-- for key in ("memories", "resources", "skills"):- rows = getattr(result, key, []) or []- for row in rows:- push(row)-- return contexts---def _build_backend_from_state_or_detect(- state: Dict[str, Any], project_dir: Path, ov_conf: Dict[str, Any]-) -> BackendInfo:- mode = _as_text(state.get("mode"))- if mode == "http":- url = _as_text(state.get("url"))- if url:- return BackendInfo(- mode="http",- url=url,- api_key=_as_text(state.get("api_key")),- )- if mode == "local":- local_data_path = _as_text(state.get("local_data_path"))- if local_data_path:- return BackendInfo(mode="local", local_data_path=local_data_path)-- return detect_backend(project_dir, ov_conf)---def cmd_session_start(args: argparse.Namespace) -> Dict[str, Any]:- project_dir = Path(args.project_dir).resolve()- ov_conf_path = project_dir / "ov.conf"- state_file = Path(args.state_file)-- if not ov_conf_path.exists():- return {- "ok": False,- "status_line": "[openviking-memory] ERROR: ./ov.conf not found",- "error": "ov.conf not found",- }-- ov_conf = _load_json(ov_conf_path)- backend = detect_backend(project_dir, ov_conf)-- with OVClient(backend, ov_conf_path) as cli:- session = cli.create_session()- session_id = _as_text(session.get("session_id"))- if not session_id:- raise RuntimeError("Failed to create OpenViking session")-- state = {- "active": True,- "project_dir": str(project_dir),- "ov_conf": str(ov_conf_path),- "mode": backend.mode,- "url": backend.url,- "api_key": backend.api_key,- "local_data_path": backend.local_data_path,- "session_id": session_id,- "last_turn_uuid": "",- "ingested_turns": 0,- "started_at": int(time.time()),- }- _save_json(state_file, state)-- status = f"[openviking-memory] mode={backend.mode} session={session_id}"- if backend.mode == "http":- status += f" server={backend.url}"-- additional = (- "OpenViking memory is active. "- "For historical context, use the memory-recall skill when needed."- )-- return {- "ok": True,- "mode": backend.mode,- "session_id": session_id,- "status_line": status,- "additional_context": additional,- }---def cmd_ingest_stop(args: argparse.Namespace) -> Dict[str, Any]:- project_dir = Path(args.project_dir).resolve()- ov_conf_path = project_dir / "ov.conf"- state_file = Path(args.state_file)- transcript = Path(args.transcript_path)-- state = _load_state(state_file)- if not state.get("active"):- return {"ok": True, "ingested": False, "reason": "inactive session"}- if not state.get("session_id"):- return {"ok": True, "ingested": False, "reason": "missing session_id"}- if not transcript.exists():- return {"ok": True, "ingested": False, "reason": "transcript not found"}- if not ov_conf_path.exists():- return {"ok": True, "ingested": False, "reason": "ov.conf not found"}-- turn = extract_last_turn(transcript)- if not turn:- return {"ok": True, "ingested": False, "reason": "no turn parsed"}-- if _as_text(turn.get("turn_uuid")) == _as_text(state.get("last_turn_uuid")):- return {"ok": True, "ingested": False, "reason": "duplicate turn"}-- ov_conf = _load_json(ov_conf_path)- backend = _build_backend_from_state_or_detect(state, project_dir, ov_conf)-- summary = summarize_turn(turn)-- user_text = _as_text(turn.get("user_text"))- if not user_text:- user_text = "(No user prompt captured)"-- assistant_excerpt = _as_text(turn.get("assistant_text"))- assistant_msg = f"Turn summary:\n{summary}"- if assistant_excerpt:- assistant_msg += f"\n\nAssistant excerpt:\n{_short(assistant_excerpt, 1500)}"-- with OVClient(backend, ov_conf_path) as cli:- session_id = _as_text(state.get("session_id"))- cli.add_message(session_id, "user", user_text)- cli.add_message(session_id, "assistant", assistant_msg)-- state["mode"] = backend.mode- state["url"] = backend.url- state["api_key"] = backend.api_key- state["local_data_path"] = backend.local_data_path- state["last_turn_uuid"] = _as_text(turn.get("turn_uuid"))- state["ingested_turns"] = int(state.get("ingested_turns", 0)) + 1- state["last_ingested_at"] = int(time.time())- _save_json(state_file, state)-- return {- "ok": True,- "ingested": True,- "session_id": state.get("session_id"),- "turn_uuid": turn.get("turn_uuid"),- "ingested_turns": state.get("ingested_turns"),- }---def cmd_session_end(args: argparse.Namespace) -> Dict[str, Any]:- project_dir = Path(args.project_dir).resolve()- ov_conf_path = project_dir / "ov.conf"- state_file = Path(args.state_file)-- state = _load_state(state_file)- if not state.get("active") or not state.get("session_id"):- return {- "ok": True,- "committed": False,- "status_line": "[openviking-memory] no active session",- }-- if not ov_conf_path.exists():- return {- "ok": False,- "committed": False,- "status_line": "[openviking-memory] ERROR: ./ov.conf not found",- "error": "ov.conf not found",- }-- ov_conf = _load_json(ov_conf_path)- backend = _build_backend_from_state_or_detect(state, project_dir, ov_conf)-- with OVClient(backend, ov_conf_path) as cli:- result = cli.commit_session(_as_text(state.get("session_id")))-- state["active"] = False- state["committed_at"] = int(time.time())- state["commit_result"] = result- _save_json(state_file, state)-- extracted = int(result.get("memories_extracted", 0)) if isinstance(result, dict) else 0- status = (- "[openviking-memory] session committed"- f" id={state.get('session_id')}"- f" memories_extracted={extracted}"- )-- return {- "ok": True,- "committed": True,- "status_line": status,- "result": result,- }---def cmd_recall(args: argparse.Namespace) -> int:- project_dir = Path(args.project_dir).resolve()- ov_conf_path = project_dir / "ov.conf"- state_file = Path(args.state_file)- query = _as_text(args.query)-- if not query:- print("No relevant memories found.")- return 0-- if not ov_conf_path.exists():- print("Memory unavailable: ./ov.conf not found.")- return 0-- state = _load_state(state_file)- ov_conf = _load_json(ov_conf_path)- backend = _build_backend_from_state_or_detect(state, project_dir, ov_conf)-- roots = ["viking://user/memories/", "viking://agent/memories/"]- contexts: List[Dict[str, Any]] = []-- with OVClient(backend, ov_conf_path) as cli:- for root in roots:- try:- result = cli.find(query=query, target_uri=root, limit=max(args.top_k, 3))- except Exception:- continue- contexts.extend(_contexts_from_find_result(result))-- dedup: Dict[str, Dict[str, Any]] = {}- for item in contexts:- uri = item.get("uri", "")- if not uri:- continue- if uri not in dedup or float(item.get("score", 0.0)) > float(- dedup[uri].get("score", 0.0)- ):- dedup[uri] = item-- ranked = sorted(- dedup.values(),- key=lambda x: float(x.get("score", 0.0)),- reverse=True,- )[: args.top_k]-- if not ranked:- print("No relevant memories found.")- return 0-- output_lines = [f"Relevant memories for: {query}", ""]-- for i, item in enumerate(ranked, start=1):- uri = _as_text(item.get("uri"))- score = float(item.get("score", 0.0))- abstract = _as_text(item.get("abstract", ""))- try:- content = _as_text(cli.read(uri))- except Exception:- content = ""-- output_lines.append(f"{i}. [{score:.3f}] {uri}")- if abstract:- output_lines.append(f" abstract: {_short(abstract, 220)}")- if content:- output_lines.append(f" snippet: {_short(content, 420)}")- output_lines.append("")-- print("\n".join(output_lines).strip())- return 0---def _build_parser() -> argparse.ArgumentParser:- parser = argparse.ArgumentParser(description="OpenViking memory bridge")- parser.add_argument("--project-dir", required=True, help="Claude project directory")- parser.add_argument("--state-file", required=True, help="Plugin state file path")-- sub = parser.add_subparsers(dest="command", required=True)-- sub.add_parser("session-start", help="Start memory session")-- p_stop = sub.add_parser("ingest-stop", help="Ingest last transcript turn")- p_stop.add_argument("--transcript-path", required=True, help="Claude transcript path")-- sub.add_parser("session-end", help="Commit memory session")-- p_recall = sub.add_parser("recall", help="Search extracted memories")- p_recall.add_argument("--query", required=True, help="Recall query")- p_recall.add_argument("--top-k", type=int, default=5, help="Number of memories to return")-- return parser---def main() -> int:- parser = _build_parser()- args = parser.parse_args()-- try:- if args.command == "session-start":- print(json.dumps(cmd_session_start(args), ensure_ascii=False))- return 0-- if args.command == "ingest-stop":- print(json.dumps(cmd_ingest_stop(args), ensure_ascii=False))- return 0-- if args.command == "session-end":- print(json.dumps(cmd_session_end(args), ensure_ascii=False))- return 0-- if args.command == "recall":- return cmd_recall(args)-- parser.error(f"Unknown command: {args.command}")- return 2-- except Exception as exc: # noqa: BLE001- if args.command == "recall":- print(f"Memory recall failed: {exc}")- return 1- print(json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False))- return 1---if __name__ == "__main__":- raise SystemExit(main())diff --git a/examples/claude-memory-plugin/scripts/run_e2e_claude_session.sh b/examples/claude-memory-plugin/scripts/run_e2e_claude_session.shdeleted file mode 100755index 51aa30c01..000000000--- a/examples/claude-memory-plugin/scripts/run_e2e_claude_session.sh+++ /dev/null@@ -1,407 +0,0 @@-#!/usr/bin/env bash-# One-click E2E test runner for OpenViking Claude memory plugin.-#-# This script runs a real Claude Code headless session and validates:-# 1) SessionStart/UserPromptSubmit hooks executed-# 2) Stop hook ingested at least one turn-# 3) SessionEnd committed the OpenViking session-# 4) Session archive file was created-#-# Default source config:-# /Users/quemingjian/Source/OpenViking/ov.conf--set -euo pipefail--SOURCE_OV_CONF_DEFAULT="/Users/quemingjian/Source/OpenViking/ov.conf"-PROMPT_DEFAULT="请只回复: E2E_HTTP_OK"--SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"-PLUGIN_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"-PROJECT_ROOT="$(cd "$PLUGIN_DIR/../.." && pwd)"--SOURCE_OV_CONF="${1:-$SOURCE_OV_CONF_DEFAULT}"-PROMPT="${2:-$PROMPT_DEFAULT}"--if [[ ! -f "$SOURCE_OV_CONF" ]]; then- echo "ERROR: source ov.conf not found: $SOURCE_OV_CONF" >&2- exit 1-fi--if ! command -v claude >/dev/null 2>&1; then- echo "ERROR: claude CLI not found in PATH." >&2- exit 1-fi--PYTHON_BIN=""-for c in /opt/homebrew/bin/python3.11 python3.11 python3; do- if command -v "$c" >/dev/null 2>&1; then- PYTHON_BIN="$(command -v "$c")"- break- fi-done-if [[ -z "$PYTHON_BIN" ]]; then- echo "ERROR: Python not found." >&2- exit 1-fi--VENV_DIR="${TMPDIR:-/tmp}/ov-claude-e2e-venv-$(id -u)"-LOG_DIR="${TMPDIR:-/tmp}/ov-claude-e2e-logs"-mkdir -p "$LOG_DIR"-CLAUDE_DEBUG_LOG="$LOG_DIR/claude-plugin-e2e.log"-SERVER_LOG="$LOG_DIR/openviking-server.log"-STATE_FILE="$PROJECT_ROOT/.openviking/memory/session_state.json"-NOW_TS="$(date +%s)"-TEST_PLUGIN_DIR="${TMPDIR:-/tmp}/ov-plugin-e2e-${NOW_TS}"-TMP_DATA_DIR="${TMPDIR:-/tmp}/ov-claude-e2e-data-${NOW_TS}"-mkdir -p "$TMP_DATA_DIR"-SERVER_OV_CONF="${LOG_DIR}/ov-server-${NOW_TS}.conf.json"--cleanup() {- local code=$?- if [[ -n "${SERVER_PID:-}" ]]; then- kill "${SERVER_PID}" >/dev/null 2>&1 || true- wait "${SERVER_PID}" >/dev/null 2>&1 || true- fi-- if [[ -n "${ORIG_OV_CONF_BACKUP:-}" && -f "${ORIG_OV_CONF_BACKUP}" ]]; then- mv -f "${ORIG_OV_CONF_BACKUP}" "$PROJECT_ROOT/ov.conf"- elif [[ -f "$PROJECT_ROOT/ov.conf" && -n "${CREATED_OV_CONF:-}" ]]; then- python3 - <<'PY' "$PROJECT_ROOT/ov.conf"-import os, sys-try:- os.unlink(sys.argv[1])-except FileNotFoundError:- pass-except OSError:- pass-PY- fi-- if [[ -n "${ENGINE_LINK_CREATED:-}" ]]; then- python3 - <<'PY' "$PROJECT_ROOT/openviking/storage/vectordb/engine.so"-import os, sys-p = sys.argv[1]-if os.path.islink(p):- os.unlink(p)-PY- fi-- if [[ -n "${AGFS_LINK_CREATED:-}" ]]; then- python3 - <<'PY' "$PROJECT_ROOT/openviking/bin/agfs-server"-import os, sys-p = sys.argv[1]-if os.path.islink(p):- os.unlink(p)-PY- fi-- if [[ $code -ne 0 ]]; then- echo- echo "E2E FAILED. Debug files:"- echo " Claude log: $CLAUDE_DEBUG_LOG"- echo " Server log: $SERVER_LOG"- echo " State file: $STATE_FILE"- fi-- if [[ -d "$TEST_PLUGIN_DIR" ]]; then- python3 - <<'PY' "$TEST_PLUGIN_DIR"-import shutil, sys-shutil.rmtree(sys.argv[1], ignore_errors=True)-PY- fi- exit $code-}-trap cleanup EXIT--echo "==> Preparing Python environment: $VENV_DIR"-if [[ ! -d "$VENV_DIR" ]]; then- "$PYTHON_BIN" -m venv "$VENV_DIR"-fi-source "$VENV_DIR/bin/activate"-python --version--if ! python - <<'PY' >/dev/null 2>&1-import yaml, pydantic, httpx, typer, pyagfs-PY-then- echo "==> Installing runtime dependencies (first run may take a few minutes)"- pip install --upgrade pip setuptools wheel >/dev/null- pip install \- pyyaml pydantic httpx typer requests tabulate jinja2 fastapi uvicorn \- openai markdownify readabilipy pdfplumber python-docx python-pptx openpyxl \- ebooklib json-repair apscheduler volcengine "volcengine-python-sdk[ark]" \- xxhash urllib3 protobuf "pdfminer-six>=20231228" >/dev/null- pip install "$PROJECT_ROOT/third_party/agfs/agfs-sdk/python" >/dev/null-fi--echo "==> Ensuring local build artifacts are available"-SOURCE_REPO_DIR="$(cd "$(dirname "$SOURCE_OV_CONF")" && pwd)"-ENGINE_TARGET="$PROJECT_ROOT/openviking/storage/vectordb/engine.so"-SOURCE_ENGINE="$SOURCE_REPO_DIR/openviking/storage/vectordb/engine.so"-if [[ ! -f "$ENGINE_TARGET" && -f "$SOURCE_ENGINE" ]]; then- ln -sf "$SOURCE_ENGINE" "$ENGINE_TARGET"- ENGINE_LINK_CREATED=1-fi--mkdir -p "$PROJECT_ROOT/openviking/bin"-AGFS_TARGET="$PROJECT_ROOT/openviking/bin/agfs-server"-SOURCE_AGFS="$SOURCE_REPO_DIR/openviking/bin/agfs-server"-if [[ ! -f "$AGFS_TARGET" && -f "$SOURCE_AGFS" ]]; then- ln -sf "$SOURCE_AGFS" "$AGFS_TARGET"- AGFS_LINK_CREATED=1-fi--if [[ ! -f "$ENGINE_TARGET" ]]; then- echo "ERROR: engine.so missing at $ENGINE_TARGET and no fallback found." >&2- exit 1-fi-if [[ ! -f "$AGFS_TARGET" ]]; then- echo "ERROR: agfs-server missing at $AGFS_TARGET and no fallback found." >&2- exit 1-fi--PORT_JSON="$(-python - <<'PY'-import socket, json-def free_port():- s = socket.socket()- s.bind(("127.0.0.1", 0))- p = s.getsockname()[1]- s.close()- return p-print(json.dumps({"ov_port": free_port(), "agfs_port": free_port()}))-PY-)"-OV_PORT="$(python - <<'PY' "$PORT_JSON"-import json,sys-print(json.loads(sys.argv[1])["ov_port"])-PY-)"-AGFS_PORT="$(python - <<'PY' "$PORT_JSON"-import json,sys-print(json.loads(sys.argv[1])["agfs_port"])-PY-)"--echo "==> Generating configs for test (HTTP mode on 127.0.0.1:$OV_PORT)"-if [[ -e "$PROJECT_ROOT/ov.conf" ]]; then- ORIG_OV_CONF_BACKUP="$PROJECT_ROOT/ov.conf.e2e.bak.${NOW_TS}"- mv "$PROJECT_ROOT/ov.conf" "$ORIG_OV_CONF_BACKUP"-fi--python - <<'PY' "$SOURCE_OV_CONF" "$PROJECT_ROOT/ov.conf" "$SERVER_OV_CONF" "$OV_PORT" "$AGFS_PORT" "$TMP_DATA_DIR"-import json, sys, copy, os-src, plugin_cfg_path, server_cfg_path, ov_port, agfs_port, data_dir = sys.argv[1:]-with open(src, "r", encoding="utf-8") as f:- cfg = json.load(f)--base = copy.deepcopy(cfg)-base["storage"] = {- "vectordb": {- "name": "context",- "backend": "local",- "path": data_dir,- },- "agfs": {- "backend": "local",- "path": data_dir,- "port": int(agfs_port),- "log_level": "warn",- },-}--# Plugin config: includes server hint for HTTP auto-detection in hooks.-plugin_cfg = copy.deepcopy(base)-plugin_cfg["server"] = {- "host": "127.0.0.1",- "port": int(ov_port),- "api_key": None,-}--os.makedirs(os.path.dirname(plugin_cfg_path), exist_ok=True)-with open(plugin_cfg_path, "w", encoding="utf-8") as f:- json.dump(plugin_cfg, f, ensure_ascii=False, indent=2)--# Server config: must NOT include unknown top-level fields like "server".-with open(server_cfg_path, "w", encoding="utf-8") as f:- json.dump(base, f, ensure_ascii=False, indent=2)--print(plugin_cfg_path)-print(server_cfg_path)-PY-CREATED_OV_CONF=1--echo "==> Starting OpenViking HTTP server"-PYTHONPATH="$PROJECT_ROOT" python -m openviking.server.bootstrap \- --host 127.0.0.1 \- --port "$OV_PORT" \- --config "$SERVER_OV_CONF" \- >"$SERVER_LOG" 2>&1 &-SERVER_PID=$!--for i in {1..60}; do- if curl -fsS "http://127.0.0.1:${OV_PORT}/health" >/dev/null 2>&1; then- break- fi- sleep 0.5- if [[ $i -eq 60 ]]; then- echo "ERROR: OpenViking server did not become healthy." >&2- exit 1- fi-done--echo "==> Running real Claude headless session"-mkdir -p "$PROJECT_ROOT/.openviking/memory"-rm -f "$STATE_FILE"--echo "==> Preparing deterministic test plugin copy (Stop hook sync)"-cp -R "$PLUGIN_DIR" "$TEST_PLUGIN_DIR"-python - <<'PY' "$TEST_PLUGIN_DIR/hooks/hooks.json"-import json, sys-p = sys.argv[1]-with open(p, "r", encoding="utf-8") as f:- d = json.load(f)-stop = d["hooks"]["Stop"][0]["hooks"][0]-stop.pop("async", None)-with open(p, "w", encoding="utf-8") as f:- json.dump(d, f, ensure_ascii=False, indent=2)-PY--PATH="$VENV_DIR/bin:$PATH" PYTHONPATH="$PROJECT_ROOT" \-claude -p \- --plugin-dir "$TEST_PLUGIN_DIR" \- --debug hooks \- --debug-file "$CLAUDE_DEBUG_LOG" \- "$PROMPT" >/tmp/ov-claude-e2e-response.txt--if [[ ! -f "$STATE_FILE" ]]; then- # SessionEnd can finish shortly after claude -p returns. Wait briefly for state.- for i in {1..60}; do- [[ -f "$STATE_FILE" ]] && break- sleep 0.5- done-fi-if [[ ! -f "$STATE_FILE" ]]; then- echo "ERROR: state file not found: $STATE_FILE" >&2- exit 1-fi--STATE_SNAPSHOT="$(-python - <<'PY' "$STATE_FILE"-import json,sys-with open(sys.argv[1], "r", encoding="utf-8") as f:- d=json.load(f)-print(f"{d.get('session_id','')}\t{d.get('ingested_turns',0)}\t{str(d.get('active',True)).lower()}\t{d.get('committed_at','')}")-PY-)"-IFS=$'\t' read -r SESSION_ID INGESTED_TURNS ACTIVE_FLAG COMMITTED_AT <<<"$STATE_SNAPSHOT"--# Poll a short time window for commit completion to avoid flaky false negatives.-for i in {1..80}; do- if [[ -n "$SESSION_ID" && "${INGESTED_TURNS:-0}" -ge 1 && "$ACTIVE_FLAG" == "false" ]]; then- break- fi- sleep 0.5- STATE_SNAPSHOT="$(- python - <<'PY' "$STATE_FILE"-import json,sys-with open(sys.argv[1], "r", encoding="utf-8") as f:- d=json.load(f)-print(f"{d.get('session_id','')}\t{d.get('ingested_turns',0)}\t{str(d.get('active',True)).lower()}\t{d.get('committed_at','')}")-PY- )"- IFS=$'\t' read -r SESSION_ID INGESTED_TURNS ACTIVE_FLAG COMMITTED_AT <<<"$STATE_SNAPSHOT"-done--find_latest_transcript() {-python - <<'PY' "$HOME/.claude/projects" "$PROJECT_ROOT" "$PROMPT"-import json, sys-from pathlib import Path--base = Path(sys.argv[1]).expanduser()-cwd = sys.argv[2]-prompt = sys.argv[3]-best = None-best_mtime = -1.0--if base.exists():- for p in base.rglob("*.jsonl"):- if "/subagents/" in str(p):- continue- try:- mt = p.stat().st_mtime- if mt < best_mtime:- continue- hit_cwd = False- hit_prompt = False- with open(p, "r", encoding="utf-8") as f:- for line in f:- line = line.strip()- if not line:- continue- try:- obj = json.loads(line)- except Exception:- continue- if obj.get("cwd") == cwd:- hit_cwd = True- if obj.get("type") == "user":- content = obj.get("message", {}).get("content", "")- if isinstance(content, str) and prompt in content:- hit_prompt = True- if hit_cwd and hit_prompt:- best = str(p)- best_mtime = mt- except Exception:- pass--print(best or "")-PY-}--LATEST_TRANSCRIPT=""-for i in {1..40}; do- LATEST_TRANSCRIPT="$(find_latest_transcript)"- if [[ -n "$LATEST_TRANSCRIPT" && -f "$LATEST_TRANSCRIPT" ]]; then- break- fi- sleep 0.5-done--if [[ -z "$SESSION_ID" ]]; then- echo "ERROR: session_id missing in state file." >&2- exit 1-fi-if [[ "${INGESTED_TURNS}" -lt 1 ]]; then- echo "ERROR: expected ingested_turns >= 1, got $INGESTED_TURNS" >&2- exit 1-fi-if [[ "$ACTIVE_FLAG" != "false" ]]; then- echo "ERROR: expected state active=false after session-end, got $ACTIVE_FLAG" >&2- exit 1-fi-if [[ -z "$LATEST_TRANSCRIPT" || ! -f "$LATEST_TRANSCRIPT" ]]; then- echo "ERROR: Could not locate transcript for prompt: $PROMPT" >&2- exit 1-fi--ARCHIVE_FILE="$TMP_DATA_DIR/viking/session/${SESSION_ID}/history/archive_001/messages.jsonl"-for i in {1..40}; do- [[ -f "$ARCHIVE_FILE" ]] && break- sleep 0.5-done-if [[ ! -f "$ARCHIVE_FILE" ]]; then- echo "ERROR: archive file missing: $ARCHIVE_FILE" >&2- exit 1-fi--echo "==> E2E PASSED"-echo "Claude response: $(cat /tmp/ov-claude-e2e-response.txt)"-echo "Session ID: $SESSION_ID"-echo "Ingested turns: $INGESTED_TURNS"-echo "State file: $STATE_FILE"-echo "Transcript: $LATEST_TRANSCRIPT"-echo "Archive: $ARCHIVE_FILE"-echo "Claude debug log: $CLAUDE_DEBUG_LOG"-echo "Server log: $SERVER_LOG"-echo "Temp data dir: $TMP_DATA_DIR"diff --git a/examples/claude-memory-plugin/skills/memory-recall/SKILL.md b/examples/claude-memory-plugin/skills/memory-recall/SKILL.mddeleted file mode 100644index fc776ef0e..000000000--- a/examples/claude-memory-plugin/skills/memory-recall/SKILL.md+++ /dev/null@@ -1,37 +0,0 @@-----name: memory-recall-description: Recall relevant long-term memories extracted by OpenViking Session memory. Use when the user asks about past decisions, prior fixes, historical context, or what was done in earlier sessions.-context: fork-allowed-tools: Bash------You are a memory retrieval sub-agent for OpenViking memory.--## Goal-Find the most relevant historical memories for: $ARGUMENTS--## Steps--1. Resolve the memory bridge script path.-```bash-PROJECT_DIR="${CLAUDE_PROJECT_DIR:-$PWD}"-STATE_FILE="$PROJECT_DIR/.openviking/memory/session_state.json"-BRIDGE="${CLAUDE_PLUGIN_ROOT:-}/scripts/ov_memory.py"--if [ ! -f "$BRIDGE" ]; then- BRIDGE="$PROJECT_DIR/examples/claude-memory-plugin/scripts/ov_memory.py"-fi-```--2. Run memory recall search.-```bash-python3 "$BRIDGE" --project-dir "$PROJECT_DIR" --state-file "$STATE_FILE" recall --query "$ARGUMENTS" --top-k 5-```--3. Evaluate results and keep only truly relevant memories.-4. Return a concise curated summary to the main agent.--## Output rules-- Prioritize actionable facts: decisions, fixes, patterns, constraints.-- Include source URIs for traceability.-- If nothing useful appears, respond exactly: `No relevant memories found.`