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
Refactor memory extract (#952)
chenjw55a0c0ea15d5
diff --git a/bot/README.md b/bot/README.mdindex 46708024e..a7d994797 100644--- a/bot/README.md+++ b/bot/README.md@@ -89,12 +89,13 @@ uv pip install -e ".[bot,bot-langfuse,bot-telegram]"**1. Initialize configuration**```bash-vikingbot gateway+openviking-server --with-bot```This will automatically:- Create a default config at `~/.openviking/ov.conf`- Create bot startup files in the OpenViking workspace, default path is `~/.openviking/data/bot/`+- Start the OpenViking server with bot integration**2. Configure via ov.conf**@@ -104,16 +105,13 @@ Edit `~/.openviking/ov.conf` to add your provider API keys (OpenRouter, OpenAI,```bash# Send a single message directly-vikingbot chat -m "What is 2+2?"+ov chat -m "What is 2+2?"# Enter interactive chat mode (supports multi-turn conversations)-vikingbot chat+ov chat# Show plain-text replies (no Markdown rendering)-vikingbot chat --no-markdown--# Show runtime logs during chat (useful for debugging)-vikingbot chat --logs+ov chat --no-format```That's it! You have a working AI assistant in 2 minutes.@@ -548,29 +546,6 @@ which nodejs| Command | Description ||---------|-------------|-| `vikingbot chat -m "..."` | Chat with the agent |-| `vikingbot chat` | Interactive chat mode |-| `vikingbot chat --no-markdown` | Show plain-text replies |-| `vikingbot chat --logs` | Show runtime logs during chat |-| `vikingbot gateway` | Start the gateway |-| `vikingbot status` | Show status |-| `vikingbot channels login` | Link WhatsApp (scan QR) |-| `vikingbot channels status` | Show channel status |---<details>-<summary><b>Scheduled Tasks (Cron)</b></summary>--```bash-# Add a job-vikingbot cron add --name "daily" --message "Good morning!" --cron "0 9 * * *"-vikingbot cron add --name "hourly" --message "Check status" --every 3600--# List jobs-vikingbot cron list--# Remove a job-vikingbot cron remove <job_id>-```--</details>+| `ov chat -m "..."` | Send a single message to the agent |+| `ov chat` | Interactive chat mode |+| `ov chat --no-format` | Show plain-text replies (no Markdown) |diff --git a/bot/README_CN.md b/bot/README_CN.mdindex 209ebea0a..ce679b485 100644--- a/bot/README_CN.md+++ b/bot/README_CN.md@@ -90,12 +90,13 @@ uv pip install -e ".[bot,bot-langfuse,bot-telegram]"**1. 初始化配置**```bash-vikingbot gateway+openviking-server --with-bot```这将自动:- 在 `~/.openviking/ov.conf` 创建默认配置- 在 openviking的工作空间下创建bot启动文件。默认路径为 `~/.openviking/data/bot/`+- 启动 OpenViking 服务器并集成 bot**2. 通过 ov.conf 配置**@@ -105,16 +106,13 @@ vikingbot gateway```bash# 直接发送单条消息-vikingbot chat -m "What is 2+2?"+ov chat -m "What is 2+2?"# 进入交互式聊天模式(支持多轮对话)-vikingbot chat+ov chat# 显示纯文本回复(不渲染 Markdown)-vikingbot chat --no-markdown--# 聊天时显示运行时日志(便于调试)-vikingbot chat --logs+ov chat --no-format```就这么简单!您只需 2 分钟就能拥有一个可用的 AI 助手。@@ -550,31 +548,9 @@ which nodejs| 命令 | 描述 ||---------|-------------|-| `vikingbot chat -m "..."` | 与代理聊天 |-| `vikingbot chat` | 交互式聊天模式 |-| `vikingbot chat --no-markdown` | 显示纯文本回复 |-| `vikingbot chat --logs` | 聊天期间显示运行时日志 |-| `vikingbot gateway` | 启动网关 |-| `vikingbot status` | 显示状态 |-| `vikingbot channels login` | 链接 WhatsApp(扫描二维码) |-| `vikingbot channels status` | 显示渠道状态 |+| `ov chat -m "..."` | 发送单条消息 |+| `ov chat` | 交互式聊天模式 |+| `ov chat --no-format` | 显示纯文本回复(无 Markdown) |交互模式退出:`exit`、`quit`、`/exit`、`/quit`、`:q` 或 `Ctrl+D`。-<details>-<summary><b>定时任务(Cron)</b></summary>--```bash-# 添加任务-vikingbot cron add --name "daily" --message "Good morning!" --cron "0 9 * * *"-vikingbot cron add --name "hourly" --message "Check status" --every 3600--# 列出任务-vikingbot cron list--# 移除任务-vikingbot cron remove <job_id>-```--</details>-diff --git a/crates/ov_cli/src/commands/chat.rs b/crates/ov_cli/src/commands/chat.rsindex 6c15f1b4f..a89fca88b 100644--- a/crates/ov_cli/src/commands/chat.rs+++ b/crates/ov_cli/src/commands/chat.rs@@ -42,7 +42,7 @@ pub struct ChatCommand {pub sender: String,/// Non-interactive mode (single message)- #[arg(short = 'M', long)]+ #[arg(short, long)]pub message: Option<String>,/// Stream the response (default: true)diff --git a/openviking/session/compressor_v2.py b/openviking/session/compressor_v2.pyindex 617acb2b0..027fb4fcb 100644--- a/openviking/session/compressor_v2.py+++ b/openviking/session/compressor_v2.py@@ -14,13 +14,14 @@ from typing import List, Optionalfrom openviking.core.context import Contextfrom openviking.message import Messagefrom openviking.server.identity import RequestContext-from openviking.session.memory import MemoryReAct, MemoryTypeRegistry, MemoryUpdaterfrom openviking.storage import VikingDBManagerfrom openviking.storage.viking_fs import get_viking_fsfrom openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils import get_loggerfrom openviking_cli.utils.config import get_openviking_config+from openviking.session.memory import MemoryReAct, MemoryUpdater, MemoryTypeRegistry+logger = get_logger(__name__)@@ -75,7 +76,7 @@ class SessionCompressorV2:if self._memory_updater is not None:return self._memory_updater- self._memory_updater = MemoryUpdater(registry=self._registry)+ self._memory_updater = MemoryUpdater(registry=self._registry, vikingdb=self.vikingdb)return self._memory_updaterasync def extract_long_term_memories(diff --git a/openviking/session/memory/memory_react.py b/openviking/session/memory/memory_react.pyindex bc427a30d..9f85838cc 100644--- a/openviking/session/memory/memory_react.py+++ b/openviking/session/memory/memory_react.py@@ -426,6 +426,34 @@ How to use edit_overview_uris:- Provide overview field with the new content (string or patch format)- Example: {{"memory_type": "profile", "overview": "User profile overview..."}}+## Overview Format Requirements (IMPORTANT)+When generating overview content for edit_overview_uris, you MUST follow this structure:++1. **Title (H1)**: Directory name (e.g., "# skills")+2. **Brief Description (plain text paragraph, 50-150 words)**:+ - Immediately following the title, without any H2 heading+ - Explain what this directory is about+ - Include core keywords for easy searching+3. **Quick Navigation (H2)**: Decision Tree style+ - Use "What do you want to learn?" or "What do you want to do?"+ - Use markdown links with relative paths: [description](./filename.md)+4. **Detailed Description (H2)**: One H3 subsection for each file++Example:+# skills++Python async programming, Go concurrency, and System design skills for backend developers.++## Quick Navigation+- Want to learn async programming → [Python Async](./python_async.md)+- Want to learn concurrency → [Go Concurrency](./go_concurrency.md)++## Detailed Description+### Python Async+...++Total length: 400-800 words+## Final Output FormatOutputs will be a complete JSON object with the following fields (Don't have '```json' appear and do not use '//' to omit content)diff --git a/openviking/session/memory/memory_updater.py b/openviking/session/memory/memory_updater.pyindex b038b2ae6..005b42f51 100644--- a/openviking/session/memory/memory_updater.py+++ b/openviking/session/memory/memory_updater.py@@ -75,9 +75,10 @@ class MemoryUpdater:No function calls are used for write/edit/delete - these are executed directly."""- def __init__(self, registry: Optional[MemoryTypeRegistry] = None):+ def __init__(self, registry: Optional[MemoryTypeRegistry] = None, vikingdb=None):self._viking_fs = Noneself._registry = registry+ self._vikingdb = vikingdbdef set_registry(self, registry: MemoryTypeRegistry) -> None:"""Set the memory type registry for URI resolution."""@@ -173,6 +174,9 @@ class MemoryUpdater:logger.error(f"Failed to delete memory {uri}: {e}")result.add_error(uri, e)+ # Vectorize written and edited memories+ await self._vectorize_memories(result, ctx)+logger.info(f"Memory operations applied: {result.summary()}")return result@@ -358,6 +362,50 @@ class MemoryUpdater:await viking_fs.write_file(uri, new_overview, ctx=ctx)logger.debug(f"Edited overview: {uri}")+ # Extract and write .abstract.md+ await self._write_abstract_from_overview(uri, new_overview, ctx)++ def _extract_abstract_from_overview(self, overview_content: str) -> str:+ """Extract abstract from overview.md - same logic as SemanticProcessor."""+ lines = overview_content.split("\n")++ # Skip header lines (starting with #)+ content_lines = []+ in_header = True++ for line in lines:+ if in_header and line.startswith("#"):+ continue+ elif in_header and line.strip():+ in_header = False++ if not in_header:+ # Stop at first ##+ if line.startswith("##"):+ break+ if line.strip():+ content_lines.append(line.strip())++ return "\n".join(content_lines).strip()++ async def _write_abstract_from_overview(+ self, overview_uri: str, overview_content: str, ctx: RequestContext+ ) -> None:+ """Extract abstract from overview and write to .abstract.md."""+ viking_fs = self._get_viking_fs()++ # Extract abstract from overview+ abstract = self._extract_abstract_from_overview(overview_content)++ # Convert overview_uri (e.g., skills/.overview.md) to abstract path+ abstract_uri = overview_uri.replace("/.overview.md", "/.abstract.md")++ try:+ await viking_fs.write_file(abstract_uri, abstract, ctx=ctx)+ logger.debug(f"Wrote abstract: {abstract_uri}")+ except Exception as e:+ logger.warning(f"Failed to write abstract {abstract_uri}: {e}")+def _print_diff(self, uri: str, old_content: str, new_content: str) -> None:"""Print a diff of the memory edit using diff_match_patch."""try:@@ -396,3 +444,68 @@ class MemoryUpdater:logger.debug(f"diff_match_patch not available, skipping diff for {uri}")except Exception as e:logger.debug(f"Failed to print diff for {uri}: {e}")++ async def _vectorize_memories(+ self,+ result: MemoryUpdateResult,+ ctx: RequestContext,+ ) -> None:+ """Vectorize written and edited memory files.++ Args:+ result: MemoryUpdateResult with written_uris and edited_uris+ ctx: Request context+ """+ if not self._vikingdb:+ logger.debug("VikingDB not available, skipping vectorization")+ return++ viking_fs = self._get_viking_fs()++ # Collect all URIs to vectorize (skip .overview.md and .abstract.md - they are handled separately)+ uris_to_vectorize = []+ for uri in result.written_uris + result.edited_uris:+ if not uri.endswith("/.overview.md") and not uri.endswith("/.abstract.md"):+ uris_to_vectorize.append(uri)++ if not uris_to_vectorize:+ logger.debug("No memory files to vectorize")+ return++ for uri in uris_to_vectorize:+ try:+ # Read the memory file to get content+ content = await viking_fs.read_file(uri, ctx=ctx) or ""++ # Extract abstract (first 200 chars or first paragraph)+ abstract = content[:200].split("\n\n")[0] if content else ""++ # Get parent URI+ from openviking_cli.utils.uri import VikingURI++ parent_uri = VikingURI(uri).parent.uri++ # Create Context for vectorization+ from openviking.core.context import Context, ContextLevel, Vectorize+ from openviking.storage.queuefs.embedding_msg_converter import EmbeddingMsgConverter++ memory_context = Context(+ uri=uri,+ parent_uri=parent_uri,+ is_leaf=True,+ abstract=abstract,+ context_type="memory",+ level=ContextLevel.DETAIL,+ user=ctx.user,+ account_id=ctx.account_id,+ )+ memory_context.set_vectorize(Vectorize(text=content))++ # Convert to embedding msg and enqueue+ embedding_msg = EmbeddingMsgConverter.from_context(memory_context)+ if embedding_msg:+ await self._vikingdb.enqueue_embedding_msg(embedding_msg)+ logger.debug(f"Enqueued memory for vectorization: {uri}")++ except Exception as e:+ logger.warning(f"Failed to vectorize memory {uri}: {e}")diff --git a/tests/integration/test_compressor_v2_xiaomei.py b/tests/integration/test_compressor_v2_xiaomei.pyindex a83fa7d54..13508195b 100644--- a/tests/integration/test_compressor_v2_xiaomei.py+++ b/tests/integration/test_compressor_v2_xiaomei.py@@ -1,29 +1,34 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-+#!/usr/bin/env python3"""-OpenViking Memory Demo Test - User: 小美 (Xiaomei)--Integration test using the demo conversation from the user.-Tests memory extraction and recall for a realistic conversation.+OpenViking 记忆演示脚本 — 用户: 小美(日常生活记录)"""-from dataclasses import asdict-import pytest-import pytest_asyncio+import argparse+import time-from openviking.message import TextPart-from openviking_cli.client.http import AsyncHTTPClient-from openviking_cli.utils import get_logger+from rich import box+from rich.console import Console+from rich.panel import Panel+from rich.table import Table-logger = get_logger(__name__)+import openviking as ov++# ── 常量 ───────────────────────────────────────────────────────────────────-# Server URL - user starts openviking-server separately-SERVER_URL = "http://127.0.0.1:1933"DISPLAY_NAME = "小美"+DEFAULT_URL = "http://localhost:1933"+PANEL_WIDTH = 78+DEFAULT_API_KEY = "1cf407c39990e5dc874ccc697942da4892208a86a44c4781396dfdc57aa5c98d"+DEFAULT_AGENT_ID = "test"+DEFAULT_SESSION_ID = "xiaomei-demo"+-# ── Conversation data (10 turns user + assistant) ─────────────────────────+console = Console()++# ── 对话数据 (10 轮 user + assistant 模拟) ─────────────────────────────────+# user 消息取自原始 demo,assistant 消息为模拟回复(用于填充 session 上下文)+CONVERSATION = [{"user": "嗨!我是小美,刚毕业不久,现在在一家互联网公司做运营。我想找个能帮我记录日常生活的小助手,比如记一下每天发生的事情、我的想法、还有想做的事情。你能帮帮我吗?",@@ -67,7 +72,8 @@ CONVERSATION = [},]-# ── Verification queries ──────────────────────────────────────────────────+# ── 验证查询 ──────────────────────────────────────────────────────────────+VERIFY_QUERIES = [{"query": "小美的工作情况",@@ -92,163 +98,203 @@ VERIFY_QUERIES = []-@pytest_asyncio.fixture(scope="function")-async def http_client():- """Create AsyncHTTPClient connected to local server"""- client = AsyncHTTPClient(url=SERVER_URL)- await client.initialize()-- yield client-- await client.close()---class TestXiaomeiMemoryDemo:- """Integration test for Xiaomei memory demo"""-- @pytest.mark.integration- @pytest.mark.asyncio- async def test_xiaomei_memory_extraction_and_recall(- self, http_client: AsyncHTTPClient- ):- """- Test full flow:- 1. Create session and add conversation messages- 2. Commit session (triggers memory extraction)- 3. Wait for processing- 4. Verify memory recall with queries- """- client = http_client-- print("\n" + "=" * 80)- print(f"OpenViking Memory Demo Test — {DISPLAY_NAME}")- print(f"Server: {SERVER_URL}")- print("=" * 80)-- # Get user/agent space names- user_space = client._user.user_space_name()- agent_space = client._user.agent_space_name()- print(f"\nUser space: {user_space}")- print(f"Agent space: {agent_space}")-- # Phase 1: Create session and add messages- print("\n" + "-" * 40)- print(f"Phase 1: Ingest conversation ({len(CONVERSATION)} turns)")- print("-" * 40)-- result = await client.create_session()- assert "session_id" in result- session_id = result["session_id"]- print(f"\nCreated session: {session_id}")-- # Add conversation messages- total = len(CONVERSATION)- for i, turn in enumerate(CONVERSATION, 1):- print(f" [{i}/{total}] Adding user + assistant message...")- # Add user message- parts = [TextPart(turn["user"])]- parts_dicts = [asdict(p) for p in parts]- await client.add_message(session_id, "user", parts=parts_dicts)- # Add assistant message- parts = [TextPart(turn["assistant"])]- parts_dicts = [asdict(p) for p in parts]- await client.add_message(session_id, "assistant", parts=parts_dicts)-- print(f"\n Added {total * 2} messages")-- # Commit session- print("\n Committing session...")- commit_result = await client.commit_session(session_id)- assert commit_result["status"] == "committed"- print(f" Commit result: {commit_result}")-- # Wait for processing- print("\n Waiting for processing...")- await client.wait_processed()- print(" Processing complete!")-- # Phase 2: Verify memory recall- print("\n" + "-" * 40)- print(f"Phase 2: Verify memory recall ({len(VERIFY_QUERIES)} queries)")- print("-" * 40)-- total_hits = 0- total_queries = len(VERIFY_QUERIES)-- for i, item in enumerate(VERIFY_QUERIES, 1):- query = item["query"]- expected = item["expected_keywords"]-- print(f"\n [{i}/{total_queries}] Query: {query}")- print(f" Expected keywords: {', '.join(expected)}")-- try:- results = await client.find(query, limit=5)-- # Collect all recall texts- recall_texts = []- count = 0-- if hasattr(results, "memories") and results.memories:- for m in results.memories:- text = getattr(m, "content", "") or getattr(m, "text", "") or str(m)- recall_texts.append(text)- uri = getattr(m, "uri", "")- score = getattr(m, "score", 0)- print(f" Memory: {uri} (score: {score:.4f})")- print(f" {text[:100]}..." if len(text) > 100 else f" {text}")- count += len(results.memories)-- if hasattr(results, "resources") and results.resources:- for r in results.resources:- text = getattr(r, "content", "") or getattr(r, "text", "") or str(r)- recall_texts.append(text)- print(f" Resource: {r.uri} (score: {r.score:.4f})")- count += len(results.resources)-- # Check keyword hits- all_text = " ".join(recall_texts)- hits = [kw for kw in expected if kw in all_text]- hit_str = ", ".join(hits) if hits else "None"-- print(f" Recalled: {count}, Hits: {hit_str}")- total_hits += len(hits)-- except Exception as e:- print(f" ERROR: {e}")-- # List memory files- print("\n" + "-" * 40)- print("Memory files created:")- print("-" * 40)+# ── Phase 1: 写入对话并提交 ────────────────────────────────────────────────- try:- user_memories = await client.ls(f"viking://user/{user_space}/memories", recursive=True)- print(f"\nUser memories ({len(user_memories)} entries):")- for entry in user_memories[:20]:- print(f" - {entry['name']} ({'dir' if entry['isDir'] else 'file'})")- except Exception as e:- print(f"Could not list user memories: {e}")++def run_ingest(client: ov.SyncHTTPClient, session_id: str, wait_seconds: float):+ console.print()+ console.rule(f"[bold]Phase 1: 写入对话 — {DISPLAY_NAME} ({len(CONVERSATION)} 轮)[/bold]")++ # 获取 session;若不存在则由服务端按 session_id 自动创建+ session= client.create_session()+ session_id = session.get('session_id')+ print(f'session_id={session_id}')+ console.print(f" Session: [bold cyan]{session_id}[/bold cyan]")+ console.print()++ # 逐轮添加消息+ total = len(CONVERSATION)+ for i, turn in enumerate(CONVERSATION, 1):+ console.print(f" [dim][{i}/{total}][/dim] 添加 user + assistant 消息...")+ client.add_message(session_id, role="user", parts=[{"type": "text", "text": turn["user"]}])+ client.add_message(session_id, role="assistant", parts=[{"type": "text", "text": turn["assistant"]}])++ console.print()+ console.print(f" 共添加 [bold]{total * 2}[/bold] 条消息")++ # 提交 session — 触发记忆抽取+ console.print()+ console.print(" [yellow]提交 Session(触发记忆抽取)...[/yellow]")+ commit_result = client.commit_session(session_id)+ task_id = commit_result.get("task_id")+ console.print(f" Commit 结果: {commit_result}")++ # 轮询后台任务直到完成+ if task_id:+ now = time.time()+ console.print(f" [yellow]等待记忆提取完成 (task_id={task_id})...[/yellow]")+ while True:+ task = client.get_task(task_id)+ if not task or task.get("status") in ("completed", "failed"):+ break+ time.sleep(1)+ elapsed = time.time() - now+ status = task.get("status", "unknown") if task else "not found"+ console.print(f" [green]任务 {status},耗时 {elapsed:.2f}s[/green]")+ console.print(f" Task 详情: {task}")++ # 等待向量化队列处理完成+ console.print(f" [yellow]等待向量化完成...[/yellow]")+ client.wait_processed()+++ if wait_seconds > 0:+ console.print(f" [dim]额外等待 {wait_seconds:.0f}s...[/dim]")+ time.sleep(wait_seconds)+++ session_info = client.get_session(session_id)+ console.print(f" Session 详情: {session_info}")++ return session_id+++# ── Phase 2: 验证记忆召回 ─────────────────────────────────────────────────+++def run_verify(client: ov.SyncHTTPClient):+ console.print()+ console.rule(+ f"[bold]Phase 2: 验证记忆召回 — {DISPLAY_NAME} ({len(VERIFY_QUERIES)} 条查询)[/bold]"+ )++ results_table = Table(+ title=f"记忆召回验证 — {DISPLAY_NAME}",+ box=box.ROUNDED,+ show_header=True,+ header_style="bold",+ )+ results_table.add_column("#", style="bold", width=4)+ results_table.add_column("查询", style="cyan", max_width=30)+ results_table.add_column("召回数", justify="center", width=8)+ results_table.add_column("命中关键词", style="green")++ total = len(VERIFY_QUERIES)+ for i, item in enumerate(VERIFY_QUERIES, 1):+ query = item["query"]+ expected = item["expected_keywords"]++ console.print(f"\n [dim][{i}/{total}][/dim] 搜索: [cyan]{query}[/cyan]")+ console.print(f" [dim]期望关键词: {', '.join(expected)}[/dim]")try:- agent_memories = await client.ls(f"viking://agent/{agent_space}/memories", recursive=True)- print(f"\nAgent memories ({len(agent_memories)} entries):")- for entry in agent_memories[:20]:- print(f" - {entry['name']} ({'dir' if entry['isDir'] else 'file'})")+ results = client.find(query, limit=5)++ # 收集所有召回内容+ recall_texts = []+ count = 0+ if hasattr(results, "memories") and results.memories:+ for m in results.memories:+ text = getattr(m, "content", "") or getattr(m, "text", "") or str(m)+ recall_texts.append(text)+ uri = getattr(m, "uri", "")+ score = getattr(m, "score", 0)+ console.print(f" [green]Memory:[/green] {uri} (score: {score:.4f})")+ console.print(f" [dim]{text[:120]}...[/dim]" if len(text) > 120 else f" [dim]{text}[/dim]")+ count += len(results.memories)++ if hasattr(results, "resources") and results.resources:+ for r in results.resources:+ text = getattr(r, "content", "") or getattr(r, "text", "") or str(r)+ recall_texts.append(text)+ console.print(+ f" [blue]Resource:[/blue] {r.uri} (score: {r.score:.4f})"+ )+ count += len(results.resources)++ if hasattr(results, "skills") and results.skills:+ count += len(results.skills)++ # 检查关键词命中+ all_text = " ".join(recall_texts)+ hits = [kw for kw in expected if kw in all_text]+ hit_str = ", ".join(hits) if hits else "[dim]无[/dim]"++ results_table.add_row(str(i), query, str(count), hit_str)+except Exception as e:- print(f"Could not list agent memories: {e}")-- print("\n" + "=" * 80)- print(f"Test completed! Total keyword hits: {total_hits}/{total_queries * len(VERIFY_QUERIES[0]['expected_keywords'])}")- print("=" * 80)-- # Test passes if no exception is thrown- assert True-- @pytest.mark.integration- @pytest.mark.asyncio- async def test_server_health(self, http_client: AsyncHTTPClient):- """Verify server is healthy"""- result = await http_client.health()- assert result is True- print(f"Server at {SERVER_URL} is healthy")\ No newline at end of file+ console.print(f" [red]ERROR: {e}[/red]")+ results_table.add_row(str(i), query, "[red]ERR[/red]", str(e)[:40])++ console.print()+ console.print(results_table)+++# ── 入口 ───────────────────────────────────────────────────────────────────+++def main():+ parser = argparse.ArgumentParser(description=f"OpenViking 记忆演示 — {DISPLAY_NAME}")+ parser.add_argument("--url", default=DEFAULT_URL, help=f"Server URL (默认: {DEFAULT_URL})")+ parser.add_argument("--api-key", default=DEFAULT_API_KEY, help="API key")+ parser.add_argument("--agent-id", default=DEFAULT_AGENT_ID, help="Agent ID")+ parser.add_argument(+ "--phase",+ choices=["all", "ingest", "verify"],+ default="all",+ help="all=全部, ingest=仅写入, verify=仅验证 (默认: all)",+ )+ parser.add_argument(+ "--session-id", default=DEFAULT_SESSION_ID, help=f"Session ID (默认: {DEFAULT_SESSION_ID})"+ )+ parser.add_argument(+ "--wait", type=float, default=5.0, help="提交后额外等待秒数 (默认: 5)"+ )+ args = parser.parse_args()++ console.print(+ Panel(+ f"[bold]OpenViking 记忆演示 — {DISPLAY_NAME}[/bold]\n"+ f"Server: {args.url} | Phase: {args.phase}",+ style="magenta",+ width=PANEL_WIDTH,+ )+ )++ client = ov.SyncHTTPClient(+ url=args.url, api_key=args.api_key, agent_id=args.agent_id,+ timeout=180+ )++ try:+ client.initialize()+ console.print(f" [green]已连接[/green] {args.url}")++ if args.phase in ("all", "ingest"):+ run_ingest(client, session_id=args.session_id, wait_seconds=args.wait)++ if args.phase in ("all", "verify"):+ run_verify(client)++ console.print(+ Panel(+ "[bold green]演示完成[/bold green]",+ style="green",+ width=PANEL_WIDTH,+ )+ )++ except Exception as e:+ console.print(+ Panel(f"[bold red]Error:[/bold red] {e}", style="red", width=PANEL_WIDTH)+ )+ import traceback++ traceback.print_exc()++ finally:+ client.close()+++if __name__ == "__main__":+ main()\ No newline at end of filediff --git a/tests/session/memory/test_compressor_v2.py b/tests/session/memory/test_compressor_v2.pyindex 4e4246ce4..eeacc1102 100644--- a/tests/session/memory/test_compressor_v2.py+++ b/tests/session/memory/test_compressor_v2.py@@ -10,7 +10,6 @@ import loggingfrom types import SimpleNamespacefrom typing import Any, Dict, Listfrom unittest.mock import patch-import pytestfrom openviking.message import Message, TextPart@@ -266,6 +265,7 @@ def create_test_conversation() -> List[Message]:class TestCompressorV2:"""Tests for SessionCompressorV2."""+@pytest.mark.asyncioasync def test_extract_long_term_memories_includes_latest_archive_overview(self):"""Latest archive overview should be prepended to the v2 conversation context."""@@ -315,6 +315,7 @@ class TestCompressorV2:assert "LATEST OVERVIEW" in captured["conversation"]assert "[user]: Current task" in captured["conversation"]+@pytest.mark.integration@pytest.mark.asyncioasync def test_extract_long_term_memories(self):