Skip to content

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

feat(examples): add Claude memory plugin example for OpenViking (#246)

Mingjian Que4e0f35e46021
diff --git a/examples/claude-memory-plugin/.claude-plugin/plugin.json b/examples/claude-memory-plugin/.claude-plugin/plugin.json
new file mode 100644
index 000000000..786842361
--- /dev/null
+++ b/examples/claude-memory-plugin/.claude-plugin/plugin.json
@@ -0,0 +1,5 @@
+{
+ "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.md
new file mode 100644
index 000000000..3961a97b0
--- /dev/null
+++ b/examples/claude-memory-plugin/README.md
@@ -0,0 +1,99 @@
+# 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.sh
new file mode 100755
index 000000000..661d928aa
--- /dev/null
+++ b/examples/claude-memory-plugin/hooks/common.sh
@@ -0,0 +1,96 @@
+#!/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.json
new file mode 100644
index 000000000..bfaecf328
--- /dev/null
+++ b/examples/claude-memory-plugin/hooks/hooks.json
@@ -0,0 +1,50 @@
+{
+ "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.sh
new file mode 100755
index 000000000..3640517f3
--- /dev/null
+++ b/examples/claude-memory-plugin/hooks/session-end.sh
@@ -0,0 +1,20 @@
+#!/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 0
diff --git a/examples/claude-memory-plugin/hooks/session-start.sh b/examples/claude-memory-plugin/hooks/session-start.sh
new file mode 100755
index 000000000..5811e8b2f
--- /dev/null
+++ b/examples/claude-memory-plugin/hooks/session-start.sh
@@ -0,0 +1,27 @@
+#!/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.sh
new file mode 100755
index 000000000..67fb15e22
--- /dev/null
+++ b/examples/claude-memory-plugin/hooks/stop.sh
@@ -0,0 +1,26 @@
+#!/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.sh
new file mode 100755
index 000000000..f5a080914
--- /dev/null
+++ b/examples/claude-memory-plugin/hooks/user-prompt-submit.sh
@@ -0,0 +1,18 @@
+#!/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.py
new file mode 100755
index 000000000..f5976827d
--- /dev/null
+++ b/examples/claude-memory-plugin/scripts/ov_memory.py
@@ -0,0 +1,714 @@
+#!/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 sys
+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) -> Dict[str, Any]:
+ return self.client.add_message(session_id, role, content)
+
+ 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.sh
new file mode 100755
index 000000000..51aa30c01
--- /dev/null
+++ b/examples/claude-memory-plugin/scripts/run_e2e_claude_session.sh
@@ -0,0 +1,407 @@
+#!/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.md
new file mode 100644
index 000000000..fc776ef0e
--- /dev/null
+++ b/examples/claude-memory-plugin/skills/memory-recall/SKILL.md
@@ -0,0 +1,37 @@
+---
+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.`