Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(memory): 引入 User/Peer 记忆隔离模型 (#2236)
Qin Haojieff258768c273
diff --git a/.github/workflows/api_test.yml b/.github/workflows/api_test.ymlindex 2347bd967..33b6aaf28 100644--- a/.github/workflows/api_test.yml+++ b/.github/workflows/api_test.yml@@ -444,6 +444,7 @@ jobs:run: |cd tests/api_testexport OPENVIKING_API_KEY=test-root-api-key+ export OPENVIKING_ROOT_API_KEY=test-root-api-keyexport SERVER_URL=http://127.0.0.1:${{ env.SERVER_PORT }}if [ "${{ env.HAS_SECRETS }}" = "true" ]; then@@ -478,6 +479,7 @@ jobs:run: |cd tests/api_test$env:OPENVIKING_API_KEY = "test-root-api-key"+ $env:OPENVIKING_ROOT_API_KEY = "test-root-api-key"$env:SERVER_URL = "http://127.0.0.1:${{ env.SERVER_PORT }}"if ($env:HAS_SECRETS -eq "true") {@@ -519,8 +521,7 @@ jobs:export OPENVIKING_CLI_BIN="${OPENVIKING_CLI_BIN}"export OPENVIKING_URL="http://127.0.0.1:${{ env.SERVER_PORT }}"export OPENVIKING_API_KEY="test-root-api-key"- export OPENVIKING_ACCOUNT="test-account"- export OPENVIKING_USER="test-user"+ export OPENVIKING_ROOT_API_KEY="test-root-api-key"echo "Running CLI compatibility tests (serial)..."uv run python -m pytest test_cli_compatibility.py -v --tb=short -m cli_remote || true@@ -539,8 +540,7 @@ jobs:export OPENVIKING_CLI_BIN="${OPENVIKING_CLI_BIN}"export OPENVIKING_URL="http://127.0.0.1:${{ env.SERVER_PORT }}"export OPENVIKING_API_KEY="test-root-api-key"- export OPENVIKING_ACCOUNT="test-account"- export OPENVIKING_USER="test-user"+ export OPENVIKING_ROOT_API_KEY="test-root-api-key"echo "Running CLI integration tests (serial to avoid resource conflicts)..."uv run python -m pytest \diff --git a/benchmark/custom/session_contention_benchmark.py b/benchmark/custom/session_contention_benchmark.pyindex fa48f88e5..f2f7ea251 100644--- a/benchmark/custom/session_contention_benchmark.py+++ b/benchmark/custom/session_contention_benchmark.py@@ -79,7 +79,6 @@ class BenchmarkConfig:api_key: Optional[str]account: Optional[str]user: Optional[str]- agent_id: Optional[str]timeout: floatadapters: List[str]profile: str@@ -108,11 +107,6 @@ class BenchmarkConfig:find_limit: int-def direct_http_agent_id(config: BenchmarkConfig) -> str:- """Avoid loading the user's global ovcli.conf when agent_id is unset."""- return config.agent_id or ""--@dataclassclass AdapterResult:success: bool@@ -266,7 +260,6 @@ class AsyncHTTPAdapter(LoadAdapter):api_key=self._config.api_key,account=self._config.account,user=self._config.user,- agent_id=direct_http_agent_id(self._config),timeout=self._config.timeout,extra_headers={},)@@ -541,7 +534,6 @@ class BenchmarkRunner:api_key=self.config.api_key,account=self.config.account,user=self.config.user,- agent_id=direct_http_agent_id(self.config),timeout=self.config.timeout,extra_headers={},)@@ -573,7 +565,6 @@ class BenchmarkRunner:api_key=self.config.api_key,account=self.config.account,user=self.config.user,- agent_id=direct_http_agent_id(self.config),timeout=self.config.timeout,extra_headers={},)@@ -1255,7 +1246,6 @@ def build_cli_config_payload(config: BenchmarkConfig) -> Dict[str, Any]:"api_key": config.api_key,"account": config.account,"user": config.user,- "agent_id": config.agent_id,"timeout": config.timeout,"extra_headers": None,}@@ -1858,7 +1848,6 @@ def parse_args(argv: Optional[List[str]] = None) -> BenchmarkConfig:parser.add_argument("--api-key", default=os.getenv("OPENVIKING_API_KEY", "test-root-api-key"))parser.add_argument("--account", default=os.getenv("OPENVIKING_ACCOUNT", "default"))parser.add_argument("--user", default=os.getenv("OPENVIKING_USER", "default"))- parser.add_argument("--agent-id", default=os.getenv("OPENVIKING_AGENT_ID"))parser.add_argument("--timeout", type=float, default=60.0)parser.add_argument("--adapters",@@ -1921,7 +1910,6 @@ def parse_args(argv: Optional[List[str]] = None) -> BenchmarkConfig:api_key=args.api_key or None,account=args.account or None,user=args.user or None,- agent_id=args.agent_id or None,timeout=max(0.1, args.timeout),adapters=adapters,profile=args.profile,diff --git a/benchmark/locomo/README.md b/benchmark/locomo/README.mdindex 86d870fa6..cd4827b0f 100644--- a/benchmark/locomo/README.md+++ b/benchmark/locomo/README.md@@ -242,7 +242,7 @@ python import_to_ov.py [选项]- `--sessions`: 指定会话范围,如 `1-4`- `--question-index`: 根据 question 的 evidence 自动推断需要的 session- `--force-ingest`: 强制重新导入-- `--no-user-agent-id`: 不传入 user_id 和 agent_id 给 OpenViking 客户端+- `--no-user-id`: 不传入 user_id 给 OpenViking 客户端- `--openviking-url`: OpenViking 服务地址,默认 `http://localhost:1933`- `--success-csv`: 成功记录 CSV 路径,默认 `./result/import_success.csv`- `--error-log`: 错误日志路径,默认 `./result/import_errors.log`@@ -252,8 +252,8 @@ python import_to_ov.py [选项]# 导入所有数据(跳过已导入的)python import_to_ov.py-# 强制重新导入,不使用 user/agent id-python import_to_ov.py --force-ingest --no-user-agent-id+# 强制重新导入,不使用 user id+python import_to_ov.py --force-ingest --no-user-id# 只导入第 0 个 samplepython import_to_ov.py --sample 0diff --git a/benchmark/locomo/claudecode/README.md b/benchmark/locomo/claudecode/README.mdindex 158886302..e36ab31f5 100644--- a/benchmark/locomo/claudecode/README.md+++ b/benchmark/locomo/claudecode/README.md@@ -6,7 +6,7 @@ exercising a different way of giving Claude Code long-term memory.| Mode | Ingest path | OV namespace | Entry point ||---|---|---|---|| **Prompted** | `claude -p` per session, CC writes `MEMORY.md` | — (no OpenViking) | `run_prompted.sh` |-| **SDK iso** | OpenViking Python SDK direct import | per-sample `agent_id` | `run_sdk_iso.sh` |+| **SDK iso** | OpenViking Python SDK direct import | per-sample user | `run_sdk_iso.sh` || **SDK no-iso** | OpenViking Python SDK direct import | shared (default) | `run_sdk_noiso.sh` || **e2e** | `claude -p` stream-json multi-turn, auto-capture into OV | shared | `run_e2e.sh` |@@ -75,8 +75,8 @@ and saved to `.tmp/result-<mode>/summary.txt`. Per-question CSVs land in- `ingest.py` — feeds each LoCoMo session as a `claude -p` invocation;CC's vanilla auto-memory writes `MEMORY.md` inside the project dir.- `import_to_ov.py` — uses the OpenViking Python SDK to push LoCoMo- conversations directly into OV. Per-sample namespace by default; pass- `--no-user-agent-id` for shared namespace.+ conversations directly into OV. Per-sample user namespace by default; pass+ `--no-user-id` for shared namespace.- `ingest_e2e.py` — opens one `claude -p` per LoCoMo session in`--input-format stream-json` mode and streams the messages one at a timethrough stdin. The plugin's Stop hook auto-captures per turn; SessionEnddiff --git a/benchmark/locomo/claudecode/config/ov-mcp.json b/benchmark/locomo/claudecode/config/ov-mcp.jsonindex 6611ca1d8..4fe6e00e8 100644--- a/benchmark/locomo/claudecode/config/ov-mcp.json+++ b/benchmark/locomo/claudecode/config/ov-mcp.json@@ -4,8 +4,7 @@"type": "http","url": "http://127.0.0.1:1933/mcp","headers": {- "X-OpenViking-User": "${OPENVIKING_USER:-}",- "X-OpenViking-Agent": "${OPENVIKING_AGENT_ID:-}"+ "X-OpenViking-User": "${OPENVIKING_USER:-}"}}}diff --git a/benchmark/locomo/claudecode/eval.py b/benchmark/locomo/claudecode/eval.pyindex 629f9a9b2..7f7e39893 100644--- a/benchmark/locomo/claudecode/eval.py+++ b/benchmark/locomo/claudecode/eval.py@@ -303,7 +303,7 @@ def run_claude_code(mcp_config: Optional[str] = None,ov_config: Optional[str] = None,ov_cli_config: Optional[str] = None,- ov_agent_id: Optional[str] = None,+ ov_user_id: Optional[str] = None,) -> dict:"""Run claude -p with retries on TIMEOUT/ERROR."""env = os.environ.copy()@@ -320,9 +320,8 @@ def run_claude_code(env["OPENVIKING_DEBUG"] = "1"if ov_cli_config:env["OPENVIKING_CLI_CONFIG_FILE"] = ov_cli_config- if ov_agent_id:- env["OPENVIKING_AGENT_ID"] = ov_agent_id- env["OPENVIKING_USER"] = ov_agent_id+ if ov_user_id:+ env["OPENVIKING_USER"] = ov_user_id# Disable detached-worker write path (subprocess.run reaps the worker# before persistence). Strip any inherited prod URL/auth that the parent# shell's `claude` shell function exports from the default ovcli.conf.@@ -415,7 +414,7 @@ def process_question(mcp_config=mcp_config,ov_config=ov_config,ov_cli_config=ov_cli_config,- ov_agent_id=(ov_shared_id if ov_shared_id is not None else sample_id),+ ov_user_id=(ov_shared_id if ov_shared_id is not None else sample_id),)elapsed = time.perf_counter() - t0@@ -557,7 +556,7 @@ def main():parser.add_argument("--ov-shared-id",default=None,- help="If set, use this single agent_id/user for all samples (no per-sample isolation). Empty string '' means do NOT set OPENVIKING_AGENT_ID at all (server falls back to 'default').",+ help="If set, use this single OpenViking user for all samples (no per-sample isolation). Empty string '' means do not set OPENVIKING_USER.",)parser.add_argument("--ov-preamble",diff --git a/benchmark/locomo/claudecode/ingest.py b/benchmark/locomo/claudecode/ingest.pyindex 4dbc0ad80..80677922f 100644--- a/benchmark/locomo/claudecode/ingest.py+++ b/benchmark/locomo/claudecode/ingest.py@@ -6,8 +6,7 @@ to Claude Code via `claude -p`, letting its auto-memory system extract and persimemories. Each session is a separate `claude -p` invocation (independent conversation).All samples share one isolated project directory so Claude Code accumulates memories-from all sessions into a single memory store — matching how openclaw uses one agent-namespace per user.+from all sessions into a single memory store.Usage:python ingest.pydiff --git a/benchmark/locomo/claudecode/ingest_e2e.py b/benchmark/locomo/claudecode/ingest_e2e.pyindex ab580b6a4..dd8e1756a 100644--- a/benchmark/locomo/claudecode/ingest_e2e.py+++ b/benchmark/locomo/claudecode/ingest_e2e.py@@ -48,7 +48,7 @@ def _build_env(api_url: Optional[str],ov_config: Optional[str],ov_cli_config: Optional[str],- ov_agent_id: Optional[str],+ ov_user_id: Optional[str],) -> dict:env = os.environ.copy()env["HOME"] = home_dir@@ -64,9 +64,8 @@ def _build_env(env["OPENVIKING_DEBUG"] = "1"if ov_cli_config:env["OPENVIKING_CLI_CONFIG_FILE"] = ov_cli_config- if ov_agent_id:- env["OPENVIKING_AGENT_ID"] = ov_agent_id- env["OPENVIKING_USER"] = ov_agent_id+ if ov_user_id:+ env["OPENVIKING_USER"] = ov_user_idenv["OPENVIKING_WRITE_PATH_ASYNC"] = "0"env.pop("OPENVIKING_URL", None)env.pop("OPENVIKING_BASE_URL", None)@@ -393,9 +392,9 @@ def main():os.makedirs(os.path.join(args.home, ".claude"), exist_ok=True)record = load_ingest_record(args.record) if not args.force else {}- ov_agent_id = args.ov_shared_id if (args.ov_shared_id and args.ov_shared_id != "") else None+ ov_user_id = args.ov_shared_id if (args.ov_shared_id and args.ov_shared_id != "") else Noneenv = _build_env(- args.home, api_key, auth_token, api_url, args.ov_config, args.ov_cli_config, ov_agent_id+ args.home, api_key, auth_token, api_url, args.ov_config, args.ov_cli_config, ov_user_id)work = []diff --git a/benchmark/locomo/claudecode/run_sdk_iso.sh b/benchmark/locomo/claudecode/run_sdk_iso.shindex ba780f5ab..e0bf0b7e9 100755--- a/benchmark/locomo/claudecode/run_sdk_iso.sh+++ b/benchmark/locomo/claudecode/run_sdk_iso.sh@@ -2,7 +2,7 @@## LoCoMo evaluation: SDK pre-ingest + per-sample namespace isolation.#-# Each LoCoMo sample (conv-XX) gets its own OpenViking user/agent_id.+# Each LoCoMo sample (conv-XX) gets its own OpenViking user.# Ingest goes straight to the OV server via the openviking Python SDK# (import_to_ov.py); no Claude Code is involved at ingest time.# QA uses Claude Code with the plugin's auto-recall hook + MCP, talking to@@ -47,7 +47,7 @@ uv run python "$SCRIPT_DIR/import_to_ov.py" \--error-log "$RESULT_DIR/ingest_errors.log" \"${SAMPLE_ARG[@]}"-echo "[2/4] running QA (per-sample agent_id from sample_id)..."+echo "[2/4] running QA (per-sample user from sample_id)..."uv run python "$SCRIPT_DIR/eval.py" \--input "$INPUT" \--output "$RESULT_DIR/qa_results.csv" \diff --git a/benchmark/locomo/claudecode/run_sdk_noiso.sh b/benchmark/locomo/claudecode/run_sdk_noiso.shindex 1964e9c98..34ac95d69 100755--- a/benchmark/locomo/claudecode/run_sdk_noiso.sh+++ b/benchmark/locomo/claudecode/run_sdk_noiso.sh@@ -2,7 +2,7 @@## LoCoMo evaluation: SDK pre-ingest + SHARED OpenViking namespace.#-# All 10 LoCoMo samples are imported into the same OV user/agent (no+# All 10 LoCoMo samples are imported into the same OV user (no# per-sample isolation). QA at recall time relies on semantic retrieval to# pick the right conv's memories out of the shared pool.#@@ -30,12 +30,12 @@ fiecho '{}' > "$PROJECT_ROOT/sample_mapping.json"-echo "[1/4] SDK pre-ingest (shared namespace, --no-user-agent-id)..."+echo "[1/4] SDK pre-ingest (shared namespace, --no-user-id)..."uv run python "$SCRIPT_DIR/import_to_ov.py" \--input "$INPUT" \--success-csv "$RESULT_DIR/ingest_success.csv" \--error-log "$RESULT_DIR/ingest_errors.log" \- --no-user-agent-id \+ --no-user-id \"${SAMPLE_ARG[@]}"echo "[2/4] running QA (shared OV namespace via --ov-shared-id \"\")..."diff --git a/benchmark/locomo/hermes/README.md b/benchmark/locomo/hermes/README.mdindex 708678611..0815c7999 100644--- a/benchmark/locomo/hermes/README.md+++ b/benchmark/locomo/hermes/README.md@@ -22,7 +22,7 @@ cd benchmark/locomo/hermes- LoCoMo dataset at `../data/locomo10.json`, or set `LOCOMO_JSON=/path/to/locomo10.json`.- Judge model credentials through `JUDGE_TOKEN` or `ARK_API_KEY`.-The default OpenViking benchmark setup is local and does not require an API key. For non-default namespaces or authenticated servers, set `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, `OPENVIKING_AGENT`, and `OPENVIKING_API_KEY` consistently for import and eval.+The default OpenViking benchmark setup is local and does not require an API key. For non-default namespaces or authenticated servers, set `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, and `OPENVIKING_API_KEY` consistently for import and eval.## Fresh Runsdiff --git a/benchmark/locomo/hermes/eval.py b/benchmark/locomo/hermes/eval.pyindex d59122ddb..a27c5110a 100644--- a/benchmark/locomo/hermes/eval.py+++ b/benchmark/locomo/hermes/eval.py@@ -58,7 +58,6 @@ def openviking_headers() -> dict[str, str]:headers = {"X-OpenViking-Account": os.getenv("OPENVIKING_ACCOUNT", "default"),"X-OpenViking-User": os.getenv("OPENVIKING_USER", "default"),- "X-OpenViking-Agent": os.getenv("OPENVIKING_AGENT", "hermes"),}api_key = os.getenv("OPENVIKING_API_KEY", "")if api_key:diff --git a/benchmark/locomo/hermes/import_e2e.py b/benchmark/locomo/hermes/import_e2e.pyindex f572c27b8..1824f72e8 100644--- a/benchmark/locomo/hermes/import_e2e.py+++ b/benchmark/locomo/hermes/import_e2e.py@@ -67,7 +67,6 @@ def openviking_headers(*, content_type: bool = False) -> dict[str, str]:headers = {"X-OpenViking-Account": os.getenv("OPENVIKING_ACCOUNT", "default"),"X-OpenViking-User": os.getenv("OPENVIKING_USER", "default"),- "X-OpenViking-Agent": os.getenv("OPENVIKING_AGENT", "hermes"),}api_key = os.getenv("OPENVIKING_API_KEY", "")if api_key:diff --git a/benchmark/locomo/hermes/import_to_ov.py b/benchmark/locomo/hermes/import_to_ov.pyindex e30533b84..8a94c08b1 100644--- a/benchmark/locomo/hermes/import_to_ov.py+++ b/benchmark/locomo/hermes/import_to_ov.py@@ -35,7 +35,6 @@ DEFAULT_IMPORT_ERROR_RETRIES = int(os.getenv("IMPORT_ERROR_RETRIES", "2"))DEFAULT_SESSION_PREFIX = "locomo-ovpreingest"DEFAULT_OPENVIKING_ACCOUNT = os.getenv("OPENVIKING_ACCOUNT", "default")DEFAULT_OPENVIKING_USER = os.getenv("OPENVIKING_USER", "default")-DEFAULT_OPENVIKING_AGENT = os.getenv("OPENVIKING_AGENT", "hermes")DEFAULT_OPENVIKING_API_KEY = os.getenv("OPENVIKING_API_KEY", "")DEFAULT_DATASET_LOCATION = "benchmark/locomo/data/locomo10.json"@@ -302,7 +301,6 @@ async def viking_ingest(replace_session: bool = False,account: str = DEFAULT_OPENVIKING_ACCOUNT,user: str = DEFAULT_OPENVIKING_USER,- agent: str = DEFAULT_OPENVIKING_AGENT,api_key: str = DEFAULT_OPENVIKING_API_KEY,) -> Dict[str, Any]:base_datetime = _parse_locomo_session_datetime(session_time or "")@@ -314,7 +312,6 @@ async def viking_ingest(api_key=api_key or None,account=account,user=user,- agent_id=agent,)await client.initialize()@@ -339,7 +336,7 @@ async def viking_ingest(role=msg["role"],parts=[{"type": "text", "text": msg["text"]}],created_at=msg_created_at,- role_id=msg.get("role_id"),+ peer_id=msg.get("peer_id"),)result = await client.commit_session(resolved_session_id, telemetry=True)@@ -512,7 +509,6 @@ async def process_single_session(replace_session=replace_session,account=args.account,user=args.user,- agent=args.agent,api_key=args.api_key,)token_usage = result["token_usage"]@@ -813,9 +809,6 @@ def main():"--account", default=DEFAULT_OPENVIKING_ACCOUNT, help="OpenViking account namespace")parser.add_argument("--user", default=DEFAULT_OPENVIKING_USER, help="OpenViking user namespace")- parser.add_argument(- "--agent", default=DEFAULT_OPENVIKING_AGENT, help="OpenViking agent namespace"- )parser.add_argument("--api-key", default=DEFAULT_OPENVIKING_API_KEY, help="OpenViking API key")parser.add_argument("--sample", type=int, default=None, help="Sample index (0-based)")parser.add_argument(diff --git a/benchmark/locomo/hermes/run_full_eval.sh b/benchmark/locomo/hermes/run_full_eval.shindex 6453932b0..b61dde6ca 100755--- a/benchmark/locomo/hermes/run_full_eval.sh+++ b/benchmark/locomo/hermes/run_full_eval.sh@@ -50,7 +50,7 @@ Environment:IMPORT_ERROR_RETRIES, QA_ERROR_RETRIES, JUDGE_ERROR_RETRIES, QUEUE_MAX_WAIT_SECPYTHON, HERMES_STATE_DB, OPENVIKING_CONFIG_FILE, OPENVIKING_STATE_SOURCE, SNAPSHOT_ROOT, RESULT_DIRE2E_PREFLIGHT, SKIP_IMPORT, IMPORT_CSV_OVERRIDE- OPENVIKING_ACCOUNT, OPENVIKING_USER, OPENVIKING_AGENT, OPENVIKING_API_KEY+ OPENVIKING_ACCOUNT, OPENVIKING_USER, OPENVIKING_API_KEYDataset:By default this expects ../data/locomo10.json from benchmark/locomo/hermes.@@ -66,7 +66,6 @@ HERMES_MODEL="${HERMES_MODEL:-hermes-agent}"OPENVIKING_URL="${OPENVIKING_URL:-http://127.0.0.1:1933}"OPENVIKING_ACCOUNT="${OPENVIKING_ACCOUNT:-default}"OPENVIKING_USER="${OPENVIKING_USER:-default}"-OPENVIKING_AGENT="${OPENVIKING_AGENT:-hermes}"OPENVIKING_API_KEY="${OPENVIKING_API_KEY:-}"JUDGE_BASE_URL="${JUDGE_BASE_URL:-https://ark.cn-beijing.volces.com/api/v3}"JUDGE_TOKEN="${JUDGE_TOKEN:-${ARK_API_KEY:-}}"@@ -223,7 +222,7 @@ SNAPSHOT_DIR="${SNAPSHOT_RUN_DIR}/openviking_workspace"SNAPSHOT_MANIFEST="${SNAPSHOT_RUN_DIR}/manifest.txt"RESULT_MANIFEST="${RESULT_DIR}/openviking_checkpoint_manifest.txt"RESOLVED_OPENVIKING_CONFIG_FILE=""-export OPENVIKING_ACCOUNT OPENVIKING_USER OPENVIKING_AGENT OPENVIKING_API_KEY+export OPENVIKING_ACCOUNT OPENVIKING_USER OPENVIKING_API_KEYif [[ ! -f "$LOCOMO_JSON" ]]; thenecho "Error: LoCoMo dataset not found: $LOCOMO_JSON" >&2@@ -614,7 +613,6 @@ resolved_session_id = response.headers.get("X-Hermes-Session-Id") or session_idov_headers = {"X-OpenViking-Account": os.environ.get("OPENVIKING_ACCOUNT", "default"),"X-OpenViking-User": os.environ.get("OPENVIKING_USER", "default"),- "X-OpenViking-Agent": os.environ.get("OPENVIKING_AGENT", "hermes"),}api_key = os.environ.get("OPENVIKING_API_KEY", "")if api_key:@@ -665,7 +663,7 @@ fail("Hermes completed the probe, but the configured OpenViking target did not receive it. "f"Expected OPENVIKING_URL={openviking_url}, session={resolved_session_id}, "f"namespace={ov_headers.get('X-OpenViking-Account')}/"- f"{ov_headers.get('X-OpenViking-User')}/{ov_headers.get('X-OpenViking-Agent')}; "+ f"{ov_headers.get('X-OpenViking-User')}; "f"last observed: {last_observed}")PY@@ -733,8 +731,8 @@ write_run_command() {"$IMPORT_PARALLEL" "$QA_PARALLEL" "$JUDGE_PARALLEL"printf 'IMPORT_ERROR_RETRIES=%q QA_ERROR_RETRIES=%q JUDGE_ERROR_RETRIES=%q QUEUE_MAX_WAIT_SEC=%q ' \"$IMPORT_ERROR_RETRIES" "$QA_ERROR_RETRIES" "$JUDGE_ERROR_RETRIES" "$QUEUE_MAX_WAIT_SEC"- printf 'OPENVIKING_ACCOUNT=%q OPENVIKING_USER=%q OPENVIKING_AGENT=%q E2E_PREFLIGHT=%q ' \- "$OPENVIKING_ACCOUNT" "$OPENVIKING_USER" "$OPENVIKING_AGENT" "$E2E_PREFLIGHT"+ printf 'OPENVIKING_ACCOUNT=%q OPENVIKING_USER=%q E2E_PREFLIGHT=%q ' \+ "$OPENVIKING_ACCOUNT" "$OPENVIKING_USER" "$E2E_PREFLIGHT"[[ -n "${HERMES_STATE_DB:-}" ]] && printf 'HERMES_STATE_DB=%q ' "$HERMES_STATE_DB"printf './run_full_eval.sh --suite %q' "$SUITE_LABEL"[[ "$CHECKPOINT_OPENVIKING" == "1" ]] && printf ' -cp'@@ -815,7 +813,6 @@ else--openviking-url "$OPENVIKING_URL"--account "$OPENVIKING_ACCOUNT"--user "$OPENVIKING_USER"- --agent "$OPENVIKING_AGENT"--parallel "$IMPORT_PARALLEL"--error-retries "$IMPORT_ERROR_RETRIES"--queue-max-wait-sec "$QUEUE_MAX_WAIT_SEC"diff --git a/benchmark/locomo/openclaw/import_to_ov.py b/benchmark/locomo/openclaw/import_to_ov.pyindex 7e5973124..ea3413aeb 100644--- a/benchmark/locomo/openclaw/import_to_ov.py+++ b/benchmark/locomo/openclaw/import_to_ov.py@@ -245,7 +245,6 @@ async def viking_ingest(openviking_url: str,session_time: Optional[str] = None,user_id: Optional[str] = None,- agent_id: Optional[str] = None,) -> Dict[str, int]:"""Save messages to OpenViking via OpenViking SDK client.Returns token usage dict with embedding and vlm token counts.@@ -255,7 +254,6 @@ async def viking_ingest(openviking_url: OpenViking service URLsession_time: Session time string (e.g., "9:36 am on 2 April, 2023")user_id: User identifier for separate userspace (e.g., "conv-26")- agent_id: Agent identifier for separate agentspace (e.g., "conv-26")"""# 解析 session_time - 为每条消息计算递增的时间戳base_datetime = None@@ -269,8 +267,6 @@ async def viking_ingest(client_kwargs = {"url": openviking_url}if user_id is not None:client_kwargs["user"] = user_id- if agent_id is not None:- client_kwargs["agent_id"] = agent_idclient = ov.AsyncHTTPClient(**client_kwargs)await client.initialize()@@ -348,15 +344,12 @@ async def process_single_session("""处理单个会话的导入任务"""started_at = time.perf_counter()try:- # 根据参数决定是否使用 sample_id 作为 user_id 和 agent_id- user_id = str(sample_id) if not args.no_user_agent_id else None- agent_id = str(sample_id) if not args.no_user_agent_id else None+ user_id = str(sample_id) if not args.no_user_id else Noneresult = await viking_ingest(messages,args.openviking_url,meta.get("date_time"),user_id=user_id,- agent_id=agent_id,)elapsed_seconds = time.perf_counter() - started_attoken_usage = result["token_usage"]@@ -654,10 +647,11 @@ def main():help="Force re-import even if already recorded as completed",)parser.add_argument(- "--no-user-agent-id",+ "--no-user-id",+ dest="no_user_id",action="store_true",default=False,- help="Do not pass user_id and agent_id to OpenViking client",+ help="Do not pass user_id to OpenViking client",)args = parser.parse_args()diff --git a/benchmark/locomo/openclaw/run_full_eval.sh b/benchmark/locomo/openclaw/run_full_eval.shindex 92be8d953..9236a3fa8 100755--- a/benchmark/locomo/openclaw/run_full_eval.sh+++ b/benchmark/locomo/openclaw/run_full_eval.sh@@ -80,7 +80,7 @@ if [ "$SKIP_IMPORT" = false ]; thenecho "[1/5] 导入数据到 OpenViking 和 OpenClaw..."# 后台运行 OpenViking 导入- python "$SCRIPT_DIR/import_to_ov.py" --no-user-agent-id --input "$INPUT_FILE" $FORCE_INGEST_ARG $SAMPLE_ARG > "$RESULT_DIR/import_ov.log" 2>&1 &+ python "$SCRIPT_DIR/import_to_ov.py" --no-user-id --input "$INPUT_FILE" $FORCE_INGEST_ARG $SAMPLE_ARG > "$RESULT_DIR/import_ov.log" 2>&1 &PID_OV=$!# 后台运行 OpenClaw 导入@@ -91,7 +91,7 @@ if [ "$SKIP_IMPORT" = false ]; thenwait $PID_OV $PID_CLAWelseecho "[1/5] 导入数据到 OpenViking..."- python "$SCRIPT_DIR/import_to_ov.py" --no-user-agent-id --input "$INPUT_FILE" $FORCE_INGEST_ARG $SAMPLE_ARG+ python "$SCRIPT_DIR/import_to_ov.py" --no-user-id --input "$INPUT_FILE" $FORCE_INGEST_ARG $SAMPLE_ARGfielsediff --git a/benchmark/locomo/vikingbot/import_to_ov.py b/benchmark/locomo/vikingbot/import_to_ov.pyindex 6bbc6441c..a54eb4955 100644--- a/benchmark/locomo/vikingbot/import_to_ov.py+++ b/benchmark/locomo/vikingbot/import_to_ov.py@@ -20,7 +20,7 @@ import timeimport tracebackfrom datetime import datetime, timedeltafrom pathlib import Path-from typing import List, Dict, Any, Tuple, Optional+from typing import Any, Dict, List, Optional, Tupleimport openviking as ov@@ -84,8 +84,8 @@ def build_session_messages(Each dict represents a session with multiple messages (user/assistant role).Args:- group_chat: If True (default), group-chat mode — role_id=speaker.- If False, single-chat mode — no role_id/speaker on messages.+ group_chat: If True (default), group-chat mode — peer_id=speaker.+ If False, single-chat mode — no peer_id/speaker on messages."""conv = item["conversation"]speakers = f"{conv['speaker_a']} & {conv['speaker_b']}"@@ -269,9 +269,7 @@ def _parse_token_usage(commit_result: Dict[str, Any]) -> Dict[str, int]:llm_input = llm.get("input", llm.get("prompt_tokens", 0))llm_output = llm.get("output", llm.get("completion_tokens", 0))cache_tokens = llm.get("cached_tokens", llm.get("prompt_cached", 0))- reasoning_tokens = llm.get(- "reasoning_tokens", llm.get("completion_reasoning", 0)- )+ reasoning_tokens = llm.get("reasoning_tokens", llm.get("completion_reasoning", 0))return {"embedding": embed_total,"vlm": llm_input,@@ -302,7 +300,6 @@ async def viking_ingest(openviking_url: str,session_time: Optional[str] = None,user_id: Optional[str] = None,- agent_id: Optional[str] = None,account: str = "default",api_key: Optional[str] = None,) -> Dict[str, int]:@@ -314,7 +311,6 @@ async def viking_ingest(openviking_url: OpenViking service URLsession_time: Session time string (e.g., "9:36 am on 2 April, 2023")user_id: User identifier for separate userspace (e.g., "conv-26")- agent_id: Agent identifier for separate agentspace (e.g., "conv-26")account: OpenViking account identifierapi_key: Optional API key for OpenViking client authentication"""@@ -330,7 +326,6 @@ async def viking_ingest(client = ov.AsyncHTTPClient(url=openviking_url,user=user_id,- agent_id=agent_id,account=account,api_key=api_key,timeout=600,@@ -355,7 +350,7 @@ async def viking_ingest(role=msg["role"],parts=[{"type": "text", "text": msg["text"]}],created_at=msg_created_at,- role_id=msg.get("speaker"),+ peer_id=msg.get("speaker"),)# Commit@@ -371,7 +366,7 @@ async def viking_ingest(if task_id:# 轮询任务状态直到完成max_attempts = 2400 # 最多等待40分钟- for attempt in range(max_attempts):+ for _attempt in range(max_attempts):task = await client.get_task(task_id)status = task.get("status") if task else "unknown"if status == "completed":@@ -381,7 +376,9 @@ async def viking_ingest(raise RuntimeError(f"Task {task_id} {status}, trace_id={trace_id}: {task}")await asyncio.sleep(2)else:- raise RuntimeError(f"Task {task_id} timed out after {max_attempts} attempts, trace_id={trace_id}")+ raise RuntimeError(+ f"Task {task_id} timed out after {max_attempts} attempts, trace_id={trace_id}"+ )else:token_usage = {"embedding": 0, "vlm": 0, "total": 0}@@ -418,14 +415,12 @@ async def process_single_session(try:started_at = time.perf_counter()user_id = str(sample_id) if args.separate_user_by_sample else ""- agent_id = str(sample_id) if args.separate_user_by_sample else ""account = args.account if args.separate_user_by_sample else ""result = await viking_ingest(messages,args.openviking_url,meta.get("date_time"),user_id=user_id,- agent_id=agent_id,account=account,api_key=args.api_key,)@@ -499,9 +494,11 @@ def parse_retry_wrong_csv(csv_path: str) -> Dict[str, set]:"""with open(csv_path, "r", encoding="utf-8") as f:reader = csv.DictReader(f)- wrong_items = [row for row in reader- if row.get("is_invalid", "").lower() != "true"- and row.get("result") == "WRONG"]+ wrong_items = [+ row+ for row in reader+ if row.get("is_invalid", "").lower() != "true" and row.get("result") == "WRONG"+ ]if not wrong_items:print(f"[retry-wrong] No valid wrong questions found in {csv_path}", file=sys.stderr)@@ -581,7 +578,7 @@ async def run_import(args: argparse.Namespace) -> None:if args.clear_ingest_record:ingest_record = {}save_ingest_record(ingest_record)- print(f"[INFO] All existing ingest records cleared", file=sys.stderr)+ print("[INFO] All existing ingest records cleared", file=sys.stderr)else:ingest_record = load_ingest_record()@@ -637,7 +634,14 @@ async def run_import(args: argparse.Namespace) -> None:# 为每个 sample 创建独立的处理协程async def process_sample(item, sample_index):- nonlocal success_count, error_count, total_embedding_tokens, total_vlm_tokens, total_cache_tokens, total_reasoning_tokens, total_llm_output_tokens+ nonlocal \+ success_count, \+ error_count, \+ total_embedding_tokens, \+ total_vlm_tokens, \+ total_cache_tokens, \+ total_reasoning_tokens, \+ total_llm_output_tokenssample_id = item["sample_id"]display_id = f"sample_{sample_index}"@@ -648,7 +652,9 @@ async def run_import(args: argparse.Namespace) -> None:if sess_nums:sample_session_range = (min(sess_nums), max(sess_nums))- sessions = build_session_messages(item, sample_session_range, group_chat=args.group_chat)+ sessions = build_session_messages(+ item, sample_session_range, group_chat=args.group_chat+ )print(f"\n=== Sample {display_id} ({sample_id}) ===", file=sys.stderr)print(f" {len(sessions)} session(s) to import", file=sys.stderr)@@ -709,7 +715,9 @@ async def run_import(args: argparse.Namespace) -> None:for idx, item in enumerate(samples)]else:- tasks = [asyncio.create_task(process_sample(item, idx)) for idx, item in enumerate(samples)]+ tasks = [+ asyncio.create_task(process_sample(item, idx)) for idx, item in enumerate(samples)+ ]else:# Plain text format@@ -725,7 +733,7 @@ async def run_import(args: argparse.Namespace) -> None:"txt", session_key, ingest_record, success_keys):print(- f" [SKIP] already imported (use --force-ingest to reprocess)", file=sys.stderr+ " [SKIP] already imported (use --force-ingest to reprocess)", file=sys.stderr)skipped_count += 1continue@@ -779,12 +787,12 @@ async def run_import(args: argparse.Namespace) -> None:# Final summarytotal_processed = success_count + error_count + skipped_count- print(f"\n=== Import summary ===", file=sys.stderr)+ print("\n=== Import summary ===", file=sys.stderr)print(f"Total sessions: {total_processed}", file=sys.stderr)print(f"Successfully imported: {success_count}", file=sys.stderr)print(f"Failed: {error_count}", file=sys.stderr)print(f"Skipped (already imported): {skipped_count}", file=sys.stderr)- print(f"\n=== Token usage summary ===", file=sys.stderr)+ print("\n=== Token usage summary ===", file=sys.stderr)print(f"Total Embedding tokens: {total_embedding_tokens}", file=sys.stderr)print(f"Total VLM tokens: {total_vlm_tokens}", file=sys.stderr)print(f"Total Cache tokens: {total_cache_tokens}", file=sys.stderr)@@ -796,7 +804,9 @@ async def run_import(args: argparse.Namespace) -> None:file=sys.stderr,)print(f"Average VLM per session: {total_vlm_tokens / success_count:.1f}", file=sys.stderr)- print(f"Average Cache per session: {total_cache_tokens / success_count:.1f}", file=sys.stderr)+ print(+ f"Average Cache per session: {total_cache_tokens / success_count:.1f}", file=sys.stderr+ )print(f"Average Reasoning per session: {total_reasoning_tokens / success_count:.1f}",file=sys.stderr,@@ -805,7 +815,7 @@ async def run_import(args: argparse.Namespace) -> None:f"Average Completion per session: {total_llm_output_tokens / success_count:.1f}",file=sys.stderr,)- print(f"\nResults saved to:", file=sys.stderr)+ print("\nResults saved to:", file=sys.stderr)print(f" - Success records: {args.success_csv}", file=sys.stderr)print(f" - Error logs: {args.error_log}", file=sys.stderr)@@ -872,7 +882,7 @@ def main():"--separate-user-by-sample",action=argparse.BooleanOptionalAction,default=True,- help="Whether to isolate OpenViking user/agent IDs by sample (default: true). Use --no-separate-user-by-sample to use empty user/agent while keeping --account unchanged.",+ help="Whether to isolate OpenViking users by sample (default: true). Use --no-separate-user-by-sample to use an empty user while keeping --account unchanged.",)parser.add_argument("--parallel-samples",@@ -890,7 +900,7 @@ def main():"--group-chat",action="store_true",default=False,- help="Group-chat mode: set role_id/speaker on messages. Default is group-chat mode.",+ help="Group-chat mode: set peer_id/speaker on messages. Default is group-chat mode.",)parser.add_argument("--clear-ingest-record",diff --git a/benchmark/locomo/vikingbot/run_eval.py b/benchmark/locomo/vikingbot/run_eval.pyindex 0e2991b3d..4ddbd457a 100644--- a/benchmark/locomo/vikingbot/run_eval.py+++ b/benchmark/locomo/vikingbot/run_eval.py@@ -1,11 +1,10 @@import argparse-import json-import subprocess-import timeimport csv+import jsonimport os-import re+import subprocessimport threading+import timefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom datetime import datetimefrom pathlib import Path@@ -153,7 +152,7 @@ def load_locomo_qa(else:samples = data- for s_idx, sample in enumerate(samples):+ for sample in samples:original_id = sample.get("sample_id", "")# Find the sample's index in the full datasetif sample_index is not None:@@ -244,15 +243,17 @@ def run_vikingbot_chat(new_cmd = ["vikingbot", "chat"]if config:new_cmd.extend(["--config", config])- new_cmd.extend([- "-m",- "/new",- "-e",- "--sender",- sample_id,- "--session",- question_id,- ])+ new_cmd.extend(+ [+ "-m",+ "/new",+ "-e",+ "--sender",+ sample_id,+ "--session",+ question_id,+ ]+ )if memory_users:for user in memory_users:new_cmd.extend(["--memory-user", user])@@ -273,7 +274,7 @@ def run_vikingbot_chat(if config:cmd.extend(["--config", config])cmd.extend(["-m", input, "-e"])- # 添加 --sender 作为 user_id,--session 作为 agent_id,实现访问独立 userspace+ # 添加 --sender 作为 user_id,--session 作为会话隔离标识if sample_id:cmd.extend(["--sender", sample_id, "--session", question_id])# 添加 --memory-user 参数,指定检索哪些用户的记忆@@ -298,7 +299,7 @@ def run_vikingbot_chat(time_cost = resp_json.get("time_cost", time_cost)iteration = resp_json.get("iteration", 0)tools_used_names = resp_json.get("tools_used_names", [])- except (json.JSONDecodeError, ValueError) as e:+ except (json.JSONDecodeError, ValueError):response = f"[PARSE ERROR] {output}"token_usage = {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}iteration = 0@@ -336,6 +337,8 @@ def load_processed_questions(output_path: str, skip_done: bool = False) -> set[sif question:processed_questions.add(question)return processed_questions++def append_row_to_csv(output_path: str, fieldnames: list[str], row: dict) -> None:"""追加单行结果到 CSV。"""file_exists = os.path.exists(output_path)@@ -450,7 +453,9 @@ def main():if row.get("result") == "WRONG":retry_wrong_questions.add(row["question"])retry_wrong_samples.add(row["sample_id"])- print(f"[retry-wrong] Found {len(retry_wrong_questions)} valid wrong questions from {args.retry_wrong}")+ print(+ f"[retry-wrong] Found {len(retry_wrong_questions)} valid wrong questions from {args.retry_wrong}"+ )if retry_wrong_samples:print(f"[retry-wrong] Affected samples: {', '.join(sorted(retry_wrong_samples))}")@@ -522,7 +527,6 @@ def main():answer = qa_item["answer"]question_time = qa_item.get("question_time")# 使用 question_id 作为 session_id,实现完全独立并行- sample_id = qa_item.get("sample_id")question_id = qa_item.get("question_id")speakers = qa_item.get("speakers", [])print(f"Processing {idx}/{total_count}: {question[:60]}...")diff --git a/benchmark/locomo/vikingbot/run_full_eval.sh b/benchmark/locomo/vikingbot/run_full_eval.shindex c446df113..b3efc13d6 100755--- a/benchmark/locomo/vikingbot/run_full_eval.sh+++ b/benchmark/locomo/vikingbot/run_full_eval.sh@@ -25,7 +25,7 @@ for arg in "$@"; doecho ""echo "开关参数:"echo " --skip-import 跳过导入步骤,直接使用已导入的数据进行评测"- echo " --group-chat 群聊模式,设置 role_id/speaker,传 --memory-user"+ echo " --group-chat 群聊模式,设置 peer_id/speaker,传 --memory-user"echo " --auto-commit 自动提交未提交的代码变更,结果文件名带 commit id 和时间戳"echo " --retry-wrong CSV 只重跑指定结果文件中的有效错题(导入相关对话+重新问答)"exit 0diff --git a/benchmark/tau2/llm/config/baseline.yaml b/benchmark/tau2/llm/config/baseline.yamlindex f4fd0091f..97d74185d 100644--- a/benchmark/tau2/llm/config/baseline.yaml+++ b/benchmark/tau2/llm/config/baseline.yaml@@ -47,7 +47,6 @@ model:openviking:url: ${OPENVIKING_URL:-http://localhost:1933}account: ${OPENVIKING_ACCOUNT:-default}- agent_id: ${OPENVIKING_AGENT_ID:-tau2-openviking-agent}reuse_corpus_across_runs: trueretrieval_top_k: 4prewrite_retrieval_top_k: 6diff --git a/benchmark/tau2/llm/scripts/run_eval.py b/benchmark/tau2/llm/scripts/run_eval.pyindex c4aaf4a50..2454a9f0f 100755--- a/benchmark/tau2/llm/scripts/run_eval.py+++ b/benchmark/tau2/llm/scripts/run_eval.py@@ -199,8 +199,8 @@ def _memory_corpus_dir(config: dict[str, Any], configured_run_id: str, corpus_kereturn output_dir(config, configured_run_id) / "memory_corpora" / corpus_key-def _search_uri(agent_id: str, search_memory_type: str) -> str:- return f"viking://agent/{agent_id}/memories/{search_memory_type}"+def _search_uri(search_memory_type: str) -> str:+ return f"viking://user/memories/{search_memory_type}"def _train_transcript_format(strategy: dict[str, Any]) -> str:@@ -227,7 +227,7 @@ def _manifest_openviking_identity(corpus_dir: Path) -> dict[str, str] | None:except json.JSONDecodeError:return Noneopenviking = manifest.get("openviking") or {}- required = ("account", "user", "agent_id", "search_uri")+ required = ("account", "user", "search_uri")if not all(openviking.get(key) for key in required):return Nonereturn {key: str(openviking[key]) for key in required}@@ -291,17 +291,14 @@ def _tau2_command(reuse_identity = _manifest_openviking_identity(corpus_dir)if reuse_identity is not None:account = reuse_identity["account"]- agent_id = reuse_identity["agent_id"]user = reuse_identity["user"]search_uri = ""elif openviking.get("reuse_corpus_across_runs", False):account = f"{openviking['account']}-{corpus_key}"- agent_id = f"{openviking['agent_id']}-{domain}-{corpus_id}"user = f"tau2-{domain}-{corpus_id}"search_uri = ""else:account = f"{openviking['account']}-{configured_run_id}-{domain}-{corpus_id}"- agent_id = f"{openviking['agent_id']}-{domain}-{corpus_id}"user = f"tau2-{domain}-{corpus_id}"search_uri = ""search_memory_type = str(strategy.get("search_memory_type", "experiences"))@@ -310,7 +307,7 @@ def _tau2_command(f"Unsupported search_memory_type for {strategy['id']}: {search_memory_type}")if not search_uri:- search_uri = _search_uri(agent_id, search_memory_type)+ search_uri = _search_uri(search_memory_type)budget = _retrieval_budget(config, strategy)command = [sys.executable,@@ -349,8 +346,6 @@ def _tau2_command(account,"--openviking-user",user,- "--openviking-agent-id",- agent_id,"--search-uri",search_uri,"--retrieval-top-k",diff --git a/benchmark/tau2/llm/scripts/run_memory_v2_eval.py b/benchmark/tau2/llm/scripts/run_memory_v2_eval.pyindex 900181e57..827dfd8ac 100644--- a/benchmark/tau2/llm/scripts/run_memory_v2_eval.py+++ b/benchmark/tau2/llm/scripts/run_memory_v2_eval.py@@ -429,7 +429,6 @@ def _client(args: argparse.Namespace):url=args.openviking_url,api_key=None,user=args.openviking_user,- agent_id=args.openviking_agent_id,account=args.openviking_account,timeout=args.openviking_timeout,extra_headers={},@@ -632,7 +631,6 @@ def _train(args: argparse.Namespace, train_results: Path, corpus_manifest: Path)"url": args.openviking_url,"account": args.openviking_account,"user": args.openviking_user,- "agent_id": args.openviking_agent_id,"search_uri": args.search_uri,},"train_transcript_format": args.train_transcript_format,@@ -941,7 +939,6 @@ def main() -> int:parser.add_argument("--openviking-url")parser.add_argument("--openviking-account")parser.add_argument("--openviking-user")- parser.add_argument("--openviking-agent-id")parser.add_argument("--openviking-timeout", type=float, default=600.0)parser.add_argument("--openviking-wait-timeout", type=int, default=600)parser.add_argument("--search-uri")@@ -1020,7 +1017,6 @@ def main() -> int:"openviking_url","openviking_account","openviking_user",- "openviking_agent_id","search_uri",)if not getattr(args, name)diff --git a/benchmark/tau2/vikingbot/.gitignore b/benchmark/tau2/vikingbot/.gitignoreindex c7821be79..220159bec 100644--- a/benchmark/tau2/vikingbot/.gitignore+++ b/benchmark/tau2/vikingbot/.gitignore@@ -1,4 +1,5 @@# Generated eval artifacts+.generated/result/result_*/trajectory/diff --git a/benchmark/tau2/vikingbot/README.md b/benchmark/tau2/vikingbot/README.mdindex 1ba38708b..27700f538 100644--- a/benchmark/tau2/vikingbot/README.md+++ b/benchmark/tau2/vikingbot/README.md@@ -70,6 +70,27 @@ Then start the OpenViking server with the bot enabled:openviking-server --config "${OPENVIKING_CONFIG_FILE}" --with-bot```+### Provision a benchmark user++The benchmark runner should not use a root/admin key for runtime memory access. Use a+provisioning key only to create a synthetic benchmark user and generate a user-key config:++```bash+export OPENVIKING_PROVISION_API_KEY="<root-or-admin-key>"++python benchmark/tau2/vikingbot/scripts/provision_openviking_user.py \+ --account default \+ --user tau2_airline_v0 \+ --base-config "${OPENVIKING_CONFIG_FILE}" \+ --out benchmark/tau2/vikingbot/.generated/tau2_airline_v0.ov.conf+```++The generated config stores the returned user key in `bot.ov_server.root_api_key` with+`bot.ov_server.api_key_type="user"`. That field name is historical VikingBot config shape; at+runtime it is a user key, not a root key. The provision key is not written into the runtime config.++Use a different generated config for each isolated benchmark user. If all domains run with the+same user-key config, they intentionally share the same OpenViking user memory.---@@ -79,7 +100,11 @@ Run one epoch — **1 train run + 8 test runs in parallel** (`--test-repeats`, devaluate (test accuracy is averaged over the repeats) and commit the train trajectories to memory:```bash-bash benchmark/tau2/vikingbot/run_full_test.sh --domain airline --epoch 0 --result-dir result+bash benchmark/tau2/vikingbot/run_full_test.sh \+ --domain airline \+ --epoch 0 \+ --result-dir result \+ --config benchmark/tau2/vikingbot/.generated/tau2_airline_v0.ov.conf```The async memory commit happens on the server, so wait for it to@@ -89,6 +114,7 @@ finish before starting the next epoch. The per-domain report is appended toMulti-epoch examples (cold start → memory-augmented epochs):```bash+TAU2_VIKINGBOT_CONFIG=benchmark/tau2/vikingbot/.generated/tau2_airline_v0.ov.conf \bash benchmark/tau2/vikingbot/run_airline_2epochs.sh```@@ -111,13 +137,15 @@ averaged. The one-click `run_full_test.sh` does all of this for you (`--test-rep# train: a single run (try 0)bash scripts/run_tau2_domain.sh \--domain airline --split train --epoch 0 --try-no 0 \- --result-dir result --concurrency 5 --use-continue --agent-id airline_v0+ --result-dir result --concurrency 5 --use-continue \+ --config .generated/tau2_airline_v0.ov.conf# test: 8 independent runs (try 0..7)for t in 0 1 2 3 4 5 6 7; dobash scripts/run_tau2_domain.sh \--domain airline --split test --epoch 0 --try-no "$t" \- --result-dir result --concurrency 5 --use-continue --agent-id airline_v0+ --result-dir result --concurrency 5 --use-continue \+ --config .generated/tau2_airline_v0.ov.confdone```@@ -133,15 +161,15 @@ bash scripts/run_eval_reward.sh result/airline_test 0 0### 3) Commit trajectories to memory-> VikingBot natively commits a task's trajectory into memory automatically as soon as that task finishes.+> VikingBot natively commits a task's trajectory into memory automatically as soon as that task finishes.> For these experiments that auto-commit is **disabled**, so that all-> tasks within an epoch (train + test, run in parallel) execute under identical memory conditions — no run sees memory written by a sibling run mid-experiment.+> tasks within an epoch (train + test, run in parallel) execute under identical memory conditions — no run sees memory written by a sibling run mid-experiment.> Instead, the commit is performed explicitly as a separate, controlled step via the script below (run once between epochs).```bashpython scripts/commit_trajectory_to_memory.py \--input result/airline_train \- --domain airline_v0 \+ --config .generated/tau2_airline_v0.ov.conf \--pattern "*_0_0_trajectory.json" \--include-eval-result```@@ -159,6 +187,10 @@ Adaptation happens in two places:experience-memory recall mode tau2 needs. **No core code edits required.** See[Required `ov.conf` flags for tau2](#required-ovconf-flags-for-tau2) below.+VikingBot runtime does not receive deprecated agent identity, peer identity, or a synthetic user+override; it only consumes the configured authenticated user. Per-domain isolation is achieved by+provisioning a separate user-key config before the run.+### Runner-level adaptations:- **Tool registry swap** — the tau2 environment tools are injected into VikingBot's `ToolRegistry`@@ -175,6 +207,21 @@ Adaptation happens in two places:- **Epoch-based memory commit** — `commit_trajectory_to_memory.py` writes train trajectories(optionally only failed ones, via `--only-wrong`) into OpenViking memory between epochs.+### Identity model++The benchmark does not pass identity through VikingBot. A provisioned user-key config determines+the OpenViking runtime identity:++```+provision_openviking_user.py -> .generated/tau2_airline_v0.ov.conf+run_full_test.sh --config .generated/tau2_airline_v0.ov.conf+ -> VikingBot uses that user key+ -> OpenViking resolves user=tau2_airline_v0+ -> memory is stored under viking://user/tau2_airline_v0/memories/+```++The provision key is control-plane only. It creates or refreshes the benchmark user key through the+Admin API, then leaves the runtime path.### Required `ov.conf` flags for tau2@@ -183,9 +230,9 @@ Two VikingBot behaviours need to change for tau2 self-improvement:1. **Per-domain workspace isolation** — each tau2 domain (airline, retail, …) must read andwrite its own OpenViking namespace so experiences learned on one domain don't leak intoanother.-2. **Recall *agent experience* instead of *user* memory** — by default VikingBot pulls user- memory into every turn. For tau2 we want the agent's own accumulated **experience** memory,- pulled once per task, with a larger character budget per experience.+2. **Recall experience memory once per task** — by default VikingBot pulls user memory into every+ turn. For tau2 we want accumulated **experience** memory pulled once per task, with a larger+ character budget per experience.Both are now controlled by config — set these three flags in the `bot.ov_server` section of the`ov.conf` pointed to by `OPENVIKING_CONFIG_FILE`:@@ -194,7 +241,7 @@ Both are now controlled by config — set these three flags in the `bot.ov_serve{"bot": {"ov_server": {- "recall_exp_first_round_only": true, // skip per-turn user/agent recall; inject exp once on the first user turn+ "recall_exp_first_round_only": true, // skip per-turn recall; inject exp once on the first user turn"exp_recall_limit": 2, // fetch 2 experiences per task (default: 5)"exp_recall_max_chars": 10000 // character budget for the injected experience block (default: 2000)}@@ -205,53 +252,16 @@ Both are now controlled by config — set these three flags in the `bot.ov_serveWhat each flag does:- **`recall_exp_first_round_only`** — when `true`, `ContextBuilder._build_user_memory` skips the- default `get_viking_memory_context` (user + agent memory, every turn) and instead calls- `get_viking_experience_context` once, on the first user-turn of the session. The runner only- ever sends one user turn per task, so this becomes "fetch experience once per task."+ default per-turn memory recall and instead calls `get_viking_experience_context` once, on the+ first user-turn of the session. The runner only ever sends one user turn per task, so this+ becomes "fetch experience once per task."- **`exp_recall_limit`** — how many experiences to retrieve. tau2 prefers **fewer but longer**(2) over many shallow hits (5).- **`exp_recall_max_chars`** — total character budget for the formatted experience block. Bumpedto **10000** so each of the 2 experiences gets room for full context (default 2000 truncates).-Workspace isolation does not need a config flag: it follows automatically from `--agent-id`-plumbing, described below.---#### How `--agent-id` flows from the runner into the core--The `--agent-id airline_v0` you pass on the command line is threaded all the way down into the-OpenViking client, and resolves to `viking://agent/airline_v0/memories/experiences/`:--```-run_full_test.sh AGENT_ID=${DOMAIN}_v0 # e.g. airline_v0, retail_v0- └─ run_tau2_domain.sh --agent-id airline_v0- └─ vikingbot_tau2_runner.py- build_messages(..., agent_id=agent_id) # explicit agent_id param- └─ context.py _build_user_memory- exp_workspace_id = agent_id or _get_workspace_id(session_key)- └─ memory.py get_viking_experience_context(query, exp_workspace_id)- └─ VikingClient.create(agent_id=exp_workspace_id)- └─ ov_server.py VikingClient.__init__ / search_experiences- viking://agent/airline_v0/memories/experiences/-```--Isolation holds in **both** `local` and `remote` `bot.ov_server.mode` (no patching required):--- `VikingClient.__init__` — in `remote` mode (root api-key, account/user auth) the incoming- `agent_id` is *always* threaded into the HTTP client, so per-domain isolation already holds.- In `local` mode (no auth, account/user fixed to `default`) the client used to hardcode- `agent_id="default"` — collapsing every domain into one namespace — and now opens against the- given `agent_id` whenever it isn't a session key (contains no `__`), giving local runs the same- isolation as remote.-- `search_experiences` — in both modes, prefers the per-instance `self.agent_id` (a non-session- id, e.g. `airline_v0`) over the global `openviking_config.agent_id`.--So `--agent-id airline_v0` ⇒ the agent reads/writes `viking://agent/airline_v0/...`, giving each-domain an isolated workspace.--> Verified end-to-end in both modes: after committing a trajectory under `airline_v0`, the-> experience is recalled **only** when querying with `--agent-id airline_v0`, and never leaks to-> a different agent id (a control id with nothing written returns zero hits).+Workspace isolation does not need a legacy namespace flag. The generated user-key config is the+runtime identity, so each domain reads and writes `viking://user/<domain_user>/...`.---@@ -263,6 +273,7 @@ domain an isolated workspace.- `run_airline_2epochs.sh` — multi-epoch example (cold start → memory-augmented epochs)- `tau2_env/` — tau2 environment integration (`tau2_environment.py`, `tau2_tool_provider.py`)- `scripts/`+ - `provision_openviking_user.py` — create/refresh a benchmark user and write a user-key config- `vikingbot_tau2_runner.py` — runs a single tau2 task through the VikingBot agent loop- `run_tau2_domain.sh` — runs all tasks in a `{domain}_{split}` slice with bounded concurrency- `run_eval_reward.sh` — average reward over a result folderdiff --git a/benchmark/tau2/vikingbot/run_airline_2epochs.sh b/benchmark/tau2/vikingbot/run_airline_2epochs.shindex 6971c2148..915eb9e65 100755--- a/benchmark/tau2/vikingbot/run_airline_2epochs.sh+++ b/benchmark/tau2/vikingbot/run_airline_2epochs.sh@@ -11,6 +11,9 @@ source "${SCRIPT_DIR}/setup_env.sh"CONCURRENCY=5DOMAIN=airlineRESULT_DIR=result+CONFIG="${TAU2_VIKINGBOT_CONFIG:-}"+CONFIG_FLAG=""+[[ -n "${CONFIG}" ]] && CONFIG_FLAG="--config ${CONFIG}"log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "${LOG_FILE}"; }@@ -22,7 +25,8 @@ bash "${SCRIPT_DIR}/run_full_test.sh" \--domain "${DOMAIN}" \--epoch 0 \--concurrency "${CONCURRENCY}" \- --result-dir "${RESULT_DIR}"+ --result-dir "${RESULT_DIR}" \+ ${CONFIG_FLAG}log ">>> Epoch 0 done"# Wait for OpenViking server to finish async memory processing@@ -37,7 +41,8 @@ bash "${SCRIPT_DIR}/run_full_test.sh" \--domain "${DOMAIN}" \--epoch 1 \--concurrency "${CONCURRENCY}" \- --result-dir "${RESULT_DIR}"+ --result-dir "${RESULT_DIR}" \+ ${CONFIG_FLAG}log ">>> Epoch 1 done"log "===== All done. Results in: ${SCRIPT_DIR}/${RESULT_DIR} ====="diff --git a/benchmark/tau2/vikingbot/run_full_test.sh b/benchmark/tau2/vikingbot/run_full_test.shindex 0e0fa4c2f..1468f2d86 100755--- a/benchmark/tau2/vikingbot/run_full_test.sh+++ b/benchmark/tau2/vikingbot/run_full_test.sh@@ -7,7 +7,7 @@ set -euo pipefail# so averaging repeats gives a more confident accuracy estimate)# Then evaluate rewards and commit the train trajectories to memory.# Usage:-# bash run_full_test.sh --domain airline [--epoch 0] [--test-repeats 8] [--result-dir result] [--concurrency N] [--commit|--no-commit]+# bash run_full_test.sh --domain airline [--epoch 0] [--test-repeats 8] [--result-dir result] [--concurrency N] [--config PATH] [--commit|--no-commit]CUR_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"SCRIPTS_DIR="${CUR_DIR}/scripts"@@ -45,6 +45,7 @@ TEST_REPEATS=8RESULT_DIR="result"CONCURRENCY=1DO_COMMIT=1+CONFIG=""while [[ $# -gt 0 ]]; docase "$1" in@@ -58,12 +59,14 @@ while [[ $# -gt 0 ]]; doRESULT_DIR="$2"; shift 2 ;;--concurrency)CONCURRENCY="$2"; shift 2 ;;+ --config)+ CONFIG="$2"; shift 2 ;;--no-commit)DO_COMMIT=0; shift ;;--commit)DO_COMMIT=1; shift ;;-h|--help)- echo "Usage: bash run_full_test.sh --domain DOMAIN [--epoch N] [--test-repeats N] [--result-dir DIR] [--concurrency N] [--commit|--no-commit]"+ echo "Usage: bash run_full_test.sh --domain DOMAIN [--epoch N] [--test-repeats N] [--result-dir DIR] [--concurrency N] [--config PATH] [--commit|--no-commit]"exit 0 ;;*)echo "Unknown argument: $1" >&2; exit 1 ;;@@ -89,8 +92,8 @@ elsefiTRAIN_DIR="${OUTPUT_ROOT}/${DOMAIN}_train"TEST_DIR="${OUTPUT_ROOT}/${DOMAIN}_test"-AGENT_ID=${DOMAIN}_v0-AGENT_ID_FLAG="--agent-id ${AGENT_ID}"+CONFIG_FLAG=""+[[ -n "${CONFIG}" ]] && CONFIG_FLAG="--config ${CONFIG}"# train runs once per epoch; test repeats are averaged.TRAIN_TRY_NO=0@@ -105,7 +108,7 @@ bash "${SCRIPTS_DIR}/run_tau2_domain.sh" \--result-dir "${RESULT_DIR}" \--concurrency "${CONCURRENCY}" \${KEEP_DEFAULT_TOOLS_FLAG} \- --use-continue ${AGENT_ID_FLAG} &+ --use-continue ${CONFIG_FLAG} &PIDS+=("$!")# test: TEST_REPEATS independent runs (try-no 0 .. TEST_REPEATS-1), averaged at eval time@@ -118,7 +121,7 @@ for ((t=0; t<TEST_REPEATS; t++)); do--result-dir "${RESULT_DIR}" \--concurrency "${CONCURRENCY}" \${KEEP_DEFAULT_TOOLS_FLAG} \- --use-continue ${AGENT_ID_FLAG} &+ --use-continue ${CONFIG_FLAG} &PIDS+=("$!")done@@ -159,9 +162,9 @@ if [[ "${DO_COMMIT}" -eq 1 ]]; thenecho "[run_full_test] Commit train trajectories to memory..."python "${SCRIPTS_DIR}/commit_trajectory_to_memory.py" \--input "${TRAIN_DIR}" \- --domain "${AGENT_ID}" \--pattern "*_${EPOCH}_${TRAIN_TRY_NO}_trajectory.json" \--include-eval-result \+ ${CONFIG_FLAG} \${ONLY_WRONG_FLAG}elseecho "[run_full_test] Skip commit (--no-commit)"diff --git a/benchmark/tau2/vikingbot/scripts/commit_trajectory_to_memory.py b/benchmark/tau2/vikingbot/scripts/commit_trajectory_to_memory.pyindex c8af81da9..d4d7853dd 100644--- a/benchmark/tau2/vikingbot/scripts/commit_trajectory_to_memory.py+++ b/benchmark/tau2/vikingbot/scripts/commit_trajectory_to_memory.py@@ -17,7 +17,7 @@ import jsonfrom pathlib import Pathfrom typing import Any, Iterable-from vikingbot.config.loader import load_config+from vikingbot.config.loader import ensure_configfrom vikingbot.openviking_mount.ov_server import VikingClient@@ -127,7 +127,7 @@ async def main_async() -> int:parser.add_argument("--user-id",default=None,- help="User id for commit (default: ov.conf admin_user_id)",+ help="Optional explicit user id. Normally omitted when using a user-key benchmark config.",)parser.add_argument("--session-prefix",@@ -135,9 +135,9 @@ async def main_async() -> int:help="Prefix to prepend to session_id",)parser.add_argument(- "--domain",- default="telecom",- help="Use as agent_id when creating VikingClient",+ "--config",+ default=None,+ help="ov.conf path for the benchmark runtime user",)parser.add_argument("--dry-run",@@ -161,16 +161,10 @@ async def main_async() -> int:print(f"Input not found: {root}")return 1- config = load_config()- user_id = args.user_id or config.ov_server.admin_user_id- if not user_id:- print("Missing user_id (pass --user-id or set ov.conf admin_user_id)")- return 1+ if args.config:+ ensure_config(Path(args.config).expanduser())- client = await VikingClient.create(args.domain)- print(client.agent_id)- print(client.get_agent_space_name("default"))- print(client.client._agent_id)+ client = await VikingClient.create()files = list(_iter_files(root, args.pattern))if not files:print("No files matched.")@@ -181,7 +175,7 @@ async def main_async() -> int:_, success, msg = await _commit_single(client,path,- user_id=user_id,+ user_id=args.user_id,session_prefix=args.session_prefix,dry_run=args.dry_run,only_wrong=args.only_wrong,diff --git a/benchmark/tau2/vikingbot/scripts/provision_openviking_user.py b/benchmark/tau2/vikingbot/scripts/provision_openviking_user.pynew file mode 100644index 000000000..4bbd77849--- /dev/null+++ b/benchmark/tau2/vikingbot/scripts/provision_openviking_user.py@@ -0,0 +1,216 @@+#!/usr/bin/env python3+"""Provision a benchmark runtime user and write a VikingBot user-key config."""++from __future__ import annotations++import argparse+import json+import os+from pathlib import Path+from typing import Any+from urllib.error import HTTPError+from urllib.parse import quote+from urllib.request import Request, urlopen++SCRIPT_DIR = Path(__file__).resolve().parent+BENCHMARK_DIR = SCRIPT_DIR.parent+++class AdminAPIError(RuntimeError):+ def __init__(self, status: int, body: str):+ super().__init__(f"Admin API returned HTTP {status}: {body}")+ self.status = status+ self.body = body+++def _load_json(path: Path | None) -> dict[str, Any]:+ if path is None or not path.exists():+ return {}+ return json.loads(path.read_text(encoding="utf-8"))+++def _infer_server_url(config: dict[str, Any], explicit: str | None) -> str:+ if explicit:+ return explicit.rstrip("/")++ bot_server = config.get("bot", {}).get("ov_server", {})+ if isinstance(bot_server, dict) and bot_server.get("server_url"):+ return str(bot_server["server_url"]).rstrip("/")++ server = config.get("server", {})+ if isinstance(server, dict):+ host = server.get("host") or "127.0.0.1"+ port = server.get("port") or 1933+ return f"http://{host}:{port}".rstrip("/")++ return "http://127.0.0.1:1933"+++def _request_json(+ method: str,+ url: str,+ api_key: str,+ payload: dict[str, Any] | None = None,+) -> dict[str, Any]:+ data = None+ headers = {+ "Accept": "application/json",+ "X-API-Key": api_key,+ }+ if payload is not None:+ data = json.dumps(payload).encode("utf-8")+ headers["Content-Type"] = "application/json"++ request = Request(url, data=data, headers=headers, method=method)+ try:+ with urlopen(request, timeout=30) as response: # noqa: S310+ raw = response.read().decode("utf-8")+ except HTTPError as exc:+ body = exc.read().decode("utf-8", errors="replace")+ raise AdminAPIError(exc.code, body) from exc++ return json.loads(raw) if raw else {}+++def _extract_user_key(response: dict[str, Any]) -> str:+ result = response.get("result")+ if not isinstance(result, dict):+ raise RuntimeError(f"Admin API response missing result object: {response}")+ user_key = result.get("user_key")+ if not isinstance(user_key, str) or not user_key:+ raise RuntimeError(+ "Admin API did not return a user_key. "+ "Provisioning user-key configs is only supported in api_key mode."+ )+ return user_key+++def _provision_user(+ *,+ server_url: str,+ provision_api_key: str,+ account: str,+ user: str,+ role: str,+) -> str:+ account_path = quote(account, safe="")+ user_path = quote(user, safe="")+ users_url = f"{server_url}/api/v1/admin/accounts/{account_path}/users"++ try:+ response = _request_json(+ "POST",+ users_url,+ provision_api_key,+ {"user_id": user, "role": role},+ )+ return _extract_user_key(response)+ except AdminAPIError as exc:+ already_exists = exc.status in {400, 409} and "exist" in exc.body.lower()+ if not already_exists:+ raise++ regenerate_url = f"{users_url}/{user_path}/key"+ response = _request_json("POST", regenerate_url, provision_api_key)+ return _extract_user_key(response)+++def _write_runtime_config(+ *,+ base_config: dict[str, Any],+ output: Path,+ server_url: str,+ account: str,+ user: str,+ user_key: str,+) -> None:+ config = dict(base_config)+ server = dict(config.get("server") or {})+ if "root_api_key" in server:+ server["root_api_key"] = ""+ config["server"] = server++ bot = dict(config.get("bot") or {})+ ov_server = dict(bot.get("ov_server") or {})+ ov_server.update(+ {+ "mode": "remote",+ "api_key_type": "user",+ "server_url": server_url,+ # Historical VikingBot field name: in user-key mode this stores the user key.+ "root_api_key": user_key,+ "account_id": account,+ "admin_user_id": user,+ }+ )+ bot["ov_server"] = ov_server+ config["bot"] = bot++ output.parent.mkdir(parents=True, exist_ok=True)+ output.write_text(+ json.dumps(config, ensure_ascii=False, indent=2) + "\n",+ encoding="utf-8",+ )+++def main() -> None:+ parser = argparse.ArgumentParser(+ description="Create an OpenViking benchmark user and write a user-key ov.conf."+ )+ parser.add_argument(+ "--user",+ required=True,+ help="Benchmark runtime user id, e.g. tau2_airline_v0",+ )+ parser.add_argument("--account", default="default", help="OpenViking account id")+ parser.add_argument("--role", default="user", help="Role for newly registered users")+ parser.add_argument("--server-url", default=None, help="OpenViking server URL")+ parser.add_argument(+ "--provision-api-key",+ default=os.environ.get("OPENVIKING_PROVISION_API_KEY"),+ help="Root/admin key used only for Admin API provisioning",+ )+ parser.add_argument(+ "--base-config",+ default=os.environ.get("OPENVIKING_CONFIG_FILE"),+ help="Base ov.conf to copy non-identity bot settings from",+ )+ parser.add_argument(+ "--out",+ default=None,+ help="Output ov.conf path. Default: benchmark/tau2/vikingbot/.generated/<user>.ov.conf",+ )+ args = parser.parse_args()++ if not args.provision_api_key:+ raise SystemExit("Missing --provision-api-key or OPENVIKING_PROVISION_API_KEY")++ base_config_path = Path(args.base_config).expanduser() if args.base_config else None+ base_config = _load_json(base_config_path)+ server_url = _infer_server_url(base_config, args.server_url)+ output = (+ Path(args.out).expanduser()+ if args.out+ else BENCHMARK_DIR / ".generated" / f"{args.user}.ov.conf"+ )++ user_key = _provision_user(+ server_url=server_url,+ provision_api_key=args.provision_api_key,+ account=args.account,+ user=args.user,+ role=args.role,+ )+ _write_runtime_config(+ base_config=base_config,+ output=output,+ server_url=server_url,+ account=args.account,+ user=args.user,+ user_key=user_key,+ )+ print(output)+++if __name__ == "__main__":+ main()diff --git a/benchmark/tau2/vikingbot/scripts/run_tau2_domain.sh b/benchmark/tau2/vikingbot/scripts/run_tau2_domain.shindex 9be4bc79b..a15559bfa 100755--- a/benchmark/tau2/vikingbot/scripts/run_tau2_domain.sh+++ b/benchmark/tau2/vikingbot/scripts/run_tau2_domain.sh@@ -4,7 +4,7 @@ set -euo pipefail# Run VikingBot tau2 runner for all tasks in {domain}_{train|test} split.# Usage:# bash run_tau2_domain.sh --domain telecom --split train --epoch 0 --try-no 0 \-# --keep-default-tools --result-dir result --use-continue --concurrency 5+# --keep-default-tools --result-dir result --use-continue --config .generated/telecom_v0.ov.conf --concurrency 5SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"@@ -18,7 +18,7 @@ TRY_NO=0KEEP_DEFAULT_TOOLS=0RESULT_DIR="result"USE_CONTINUE=0-AGENT_ID=""+CONFIG=""CONCURRENCY=1while [[ $# -gt 0 ]]; do@@ -37,19 +37,19 @@ while [[ $# -gt 0 ]]; doRESULT_DIR="$2"; shift 2 ;;--use-continue)USE_CONTINUE=1; shift 1 ;;- --agent-id)- AGENT_ID="$2"; shift 2 ;;+ --config)+ CONFIG="$2"; shift 2 ;;--concurrency)CONCURRENCY="$2"; shift 2 ;;-h|--help)- echo "Usage: bash run_tau2_domain.sh --domain DOMAIN --split train|test --epoch N --try-no N --keep-default-tools --result-dir DIR --use-continue --agent-id ID --concurrency N"; exit 0 ;;+ echo "Usage: bash run_tau2_domain.sh --domain DOMAIN --split train|test --epoch N --try-no N --keep-default-tools --result-dir DIR --use-continue --config PATH --concurrency N"; exit 0 ;;*)echo "Unknown argument: $1" >&2; exit 1 ;;esacdoneif [[ -z "${DOMAIN}" || ( "${SPLIT}" != "train" && "${SPLIT}" != "test" ) ]]; then- echo "Usage: bash run_tau2_domain.sh --domain DOMAIN --split train|test --epoch N --try-no N --keep-default-tools --result-dir DIR --use-continue --agent-id ID --concurrency N" >&2+ echo "Usage: bash run_tau2_domain.sh --domain DOMAIN --split train|test --epoch N --try-no N --keep-default-tools --result-dir DIR --use-continue --config PATH --concurrency N" >&2exit 1fi@@ -85,10 +85,10 @@ echo "${DOMAIN}_${SPLIT} task count: ${TASK_COUNT}, concurrency: ${CONCURRENCY}"# build reusable flagsKEEP_DEFAULT_TOOLS_FLAG=""CONTINUE_FLAG=""-AGENT_ID_FLAG=""+CONFIG_FLAG=""[[ "${KEEP_DEFAULT_TOOLS}" == "1" ]] && KEEP_DEFAULT_TOOLS_FLAG="--keep-default-tools"[[ "${USE_CONTINUE}" == "1" ]] && CONTINUE_FLAG="--continue"-[[ -n "${AGENT_ID}" ]] && AGENT_ID_FLAG="--agent-id ${AGENT_ID}"+[[ -n "${CONFIG}" ]] && CONFIG_FLAG="--config ${CONFIG}"# Use a tmpdir as a semaphore: each running task holds a slot file.SEM_DIR=$(mktemp -d)@@ -109,7 +109,7 @@ for ((task_no=0; task_no < TASK_COUNT; task_no++)); dopython "${RUNNER}" \--data-split "${DOMAIN}_${SPLIT}" \--task-no "${task_no}" \- --output "${out_path}" ${AGENT_ID_FLAG} ${KEEP_DEFAULT_TOOLS_FLAG} ${CONTINUE_FLAG} \+ --output "${out_path}" ${CONFIG_FLAG} ${KEEP_DEFAULT_TOOLS_FLAG} ${CONTINUE_FLAG} \|| echo "[WARN] task_no=${task_no} failed, skipping"rm -f "${SLOT}") &diff --git a/benchmark/tau2/vikingbot/scripts/vikingbot_tau2_runner.py b/benchmark/tau2/vikingbot/scripts/vikingbot_tau2_runner.pyindex 3f17985df..8cb13e935 100644--- a/benchmark/tau2/vikingbot/scripts/vikingbot_tau2_runner.py+++ b/benchmark/tau2/vikingbot/scripts/vikingbot_tau2_runner.py@@ -7,6 +7,7 @@ Key points:3) We register Tau2 tools into VikingBot ToolRegistry and let the agent decide."""+# ruff: noqa: E402from __future__ import annotationsimport argparse@@ -130,15 +131,12 @@ def _extract_memory_content(content: str) -> str | None:return content[start:end]--async def _run_agent(agent: AgentLoop,system_prompt: str,user_prompt: str,session_key: SessionKey,sender_id: str | None,- agent_id: str | None,keep_default_tools: bool,messages_output_path: Path | None,) -> tuple[str | None, str | None, dict[str, int], int, str | None]:@@ -149,7 +147,6 @@ async def _run_agent(ov_tools_enable=keep_default_tools,media=None,profile_user_list=[],- agent_id=agent_id,)if system_prompt:messages.insert(1, {"role": "system", "content": system_prompt})@@ -194,7 +191,6 @@ def main() -> None:help="If output file exists, skip running and exit",)parser.add_argument("--sender", default="tau2_user")- parser.add_argument("--agent-id", default="", help="airline_v0 domain split workspace")parser.add_argument("--session", default=None)parser.add_argument("--config", default=None, help="ov.conf path (optional)")parser.add_argument(@@ -234,7 +230,7 @@ def main() -> None:for tool_name in list(agent.tools.tool_names):# print(tool_name)agent.tools.unregister(tool_name)-+agent.tools.unregister("openviking_memory_commit")for schema in provider.list_openai_tools():agent.tools.register(Tau2Tool(schema, provider))@@ -244,11 +240,15 @@ def main() -> None:instructions.append(policy)instructions.append("Use the provided tools to interact with the environment.")if args.keep_default_tools:- instructions.append("Before you attend to customer, you MUST read relevant agent memory that stores experiences distilled from similar tasks and carefully learn them.")+ instructions.append(+ "Before you attend to customer, you MUST read relevant agent memory that stores experiences distilled from similar tasks and carefully learn them."+ )instructions.append("If you need to communicate with the user, you MUST call tool `communicate_with_user`.")- instructions.append("When the task is finished or terminated, call tool `done` first and output an ending content without using any tool calling for the next round to exit.")+ instructions.append(+ "When the task is finished or terminated, call tool `done` first and output an ending content without using any tool calling for the next round to exit."+ )system_prompt = "\n".join(instructions)user_prompt = user_query@@ -258,16 +258,17 @@ def main() -> None:messages_output_path = _derive_messages_path(output_path)- final_content, final_reasoning_content, tools_used, token_usage, iteration, memory_content = asyncio.run(- _run_agent(- agent,- system_prompt,- user_prompt,- session_key,- args.sender,- args.agent_id,- args.keep_default_tools,- messages_output_path,+ final_content, final_reasoning_content, tools_used, token_usage, iteration, memory_content = (+ asyncio.run(+ _run_agent(+ agent,+ system_prompt,+ user_prompt,+ session_key,+ args.sender,+ args.keep_default_tools,+ messages_output_path,+ )))diff --git a/benchmark/tau2/vikingbot/setup_env.sh b/benchmark/tau2/vikingbot/setup_env.shindex 8d9536074..42c039fda 100755--- a/benchmark/tau2/vikingbot/setup_env.sh+++ b/benchmark/tau2/vikingbot/setup_env.sh@@ -25,7 +25,7 @@# TAU2_BENCH_REPO git URL to clone tau2-bench (default sierra-research/tau2-bench)# TAU2_BENCH_REF git ref/branch/tag to check out after clone (default: repo default)# VIKINGBOT_ROOT vikingbot package dir (default REPO_ROOT/bot)-# OPENVIKING_CONFIG_FILE, OPENAI_API_KEY / ARK_API_KEY, OPENAI_API_BASE+# OPENVIKING_CONFIG_FILE, OPENVIKING_PROVISION_API_KEY, OPENAI_API_KEY / ARK_API_KEY, OPENAI_API_BASESCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"# OpenViking repo root (this folder lives at benchmark/tau2/vikingbot/).diff --git a/bot/docs/vikingbot-openviking-context-plan.md b/bot/docs/vikingbot-openviking-context-plan.mdindex 6bdf6491f..282b21acf 100644--- a/bot/docs/vikingbot-openviking-context-plan.md+++ b/bot/docs/vikingbot-openviking-context-plan.md@@ -125,7 +125,7 @@ OpenViking 的 `get_session_context()` 返回的不是纯摘要,而是:第一版建议:- 请求继续使用当前合法的 bot/account/user 身份-- 每条消息的真实说话人通过 `role_id` 记录+- 每条消息的真实说话人通过 `peer_id` 记录不要把“当前 `sender_id`”直接等同于每次请求的 OpenViking user 身份,否则会和现有权限/命名空间语义冲突。@@ -266,12 +266,12 @@ OpenViking 的 `get_session_context()` 返回的不是纯摘要,而是:- 一个聊天房间对应一个稳定 `ov_session_id`- OpenViking request identity 继续按当前 bot/account 配置走-- 每条 user/assistant message 的实际说话者写入 `role_id`+- 每条 user/assistant message 的实际说话者写入 `peer_id`建议映射:-- user message: `role="user"`, `role_id=<真实 sender_id>`-- assistant message: `role="assistant"`, `role_id=<bot/agent id 或默认 assistant 标识>`+- user message: `role="user"`, `peer_id=<真实 sender_id>`+- assistant message: `role="assistant"`, `peer_id=<bot/agent id 或默认 assistant 标识>`这样可以同时满足:@@ -288,7 +288,7 @@ OpenViking 的 `get_session_context()` 返回的不是纯摘要,而是:建议新增或重构为以下接口:- `ensure_session(session_id: str) -> dict`-- `append_messages(session_id: str, messages: list[dict], role_id_resolver=...) -> dict`+- `append_messages(session_id: str, messages: list[dict], peer_id_resolver=...) -> dict`- `get_session(session_id: str) -> dict`- `get_session_context(session_id: str, token_budget: int) -> dict`- `commit_session(session_id: str, keep_recent_count: int = 0) -> dict`@@ -449,9 +449,9 @@ OpenViking 的 `get_session_context()` 返回的不是纯摘要,而是:### 3. 群聊身份映射风险-如果直接把 `sender_id` 当作每次 OV 请求 user 身份,容易与当前 account/user/agent 权限语义冲突。+如果直接把 `sender_id` 当作每次 OV 请求 user 身份,容易与当前 account/user/peer 权限语义冲突。-应优先通过 `role_id` 保留真实说话人。+应优先通过 `peer_id` 保留真实说话人。### 4. 提取异步性的认知风险diff --git a/bot/tests/test_agent_loop_outcome.py b/bot/tests/test_agent_loop_outcome.pyindex 889140413..6588bb38c 100644--- a/bot/tests/test_agent_loop_outcome.py+++ b/bot/tests/test_agent_loop_outcome.py@@ -55,11 +55,11 @@ class _FakeOVClient:self,session_id,messages,- default_user_role_id=None,+ default_user_peer_id=None,session_user_id=None,):self.append_calls.append(- (session_id, list(messages), default_user_role_id, session_user_id)+ (session_id, list(messages), default_user_peer_id, session_user_id))return {"session_id": session_id, "added": len(messages), "message_count": len(messages)}diff --git a/bot/tests/test_openviking_api_key_type.py b/bot/tests/test_openviking_api_key_type.pyindex c3d2b4e82..a5cf2aac5 100644--- a/bot/tests/test_openviking_api_key_type.py+++ b/bot/tests/test_openviking_api_key_type.py@@ -96,7 +96,6 @@ def _make_config(api_key_type: str, mode: str = "remote", **ov_overrides):root_api_key="root-key",account_id="acct",admin_user_id="admin",- agent_id="",**ov_overrides,)return SimpleNamespace(@@ -113,19 +112,18 @@ def _patch_http_client(monkeypatch):def test_viking_client_init_root_mode_sets_account_and_user(monkeypatch):monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))- client = VikingClient(agent_id="workspace#channel")+ client = VikingClient()first = _DummyHTTPClient.instances[0]assert client.api_key_type == "root"assert first.kwargs["account"] == "acct"assert first.kwargs["user"] == "admin"- assert first.kwargs["agent_id"] == "workspace"def test_viking_client_init_user_mode_does_not_set_user_or_account(monkeypatch):monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("user"))- client = VikingClient(agent_id="workspace")+ client = VikingClient()first = _DummyHTTPClient.instances[0]assert client.api_key_type == "user"@@ -136,7 +134,7 @@ def test_viking_client_init_user_mode_does_not_set_user_or_account(monkeypatch):@pytest.mark.asyncioasync def test_commit_user_mode_ignores_user_specific_key_flow(monkeypatch):monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("user"))- client = VikingClient(agent_id="workspace")+ client = VikingClient()async def _must_not_call(*_args, **_kwargs):raise AssertionError("user mode should not call user management path")@@ -157,7 +155,7 @@ async def test_commit_user_mode_ignores_user_specific_key_flow(monkeypatch):@pytest.mark.asyncioasync def test_commit_root_mode_uses_sender_user_key(monkeypatch):monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))- client = VikingClient(agent_id="workspace")+ client = VikingClient()async def _exists(_user_id):return True@@ -252,14 +250,14 @@ async def test_compact_hook_session_context_commits_admin_and_sender_sessions(moself,session_id,messages,- default_user_role_id=None,+ default_user_peer_id=None,session_user_id=None,):self.append_calls.append((session_id,[message["content"] for message in messages],- default_user_role_id,+ default_user_peer_id,session_user_id,))@@ -386,7 +384,7 @@ async def test_compact_hook_force_commit_does_not_resync_already_synced_messagesself,session_id,messages,- default_user_role_id=None,+ default_user_peer_id=None,session_user_id=None,):self.append_calls.append((session_id, [message["content"] for message in messages]))@@ -465,7 +463,7 @@ async def test_compact_hook_force_commit_commits_sender_sessions_without_unsynceself,session_id,messages,- default_user_role_id=None,+ default_user_peer_id=None,session_user_id=None,):self.append_calls.append((session_id, [message["content"] for message in messages]))@@ -541,7 +539,7 @@ async def test_compact_hook_session_context_sender_failure_does_not_advance_syncself,session_id,messages,- default_user_role_id=None,+ default_user_peer_id=None,session_user_id=None,):self.append_calls.append((session_id, [message["content"] for message in messages]))@@ -618,7 +616,7 @@ async def test_compact_hook_session_context_commits_when_message_threshold_reachself,session_id,messages,- default_user_role_id=None,+ default_user_peer_id=None,session_user_id=None,):self.append_calls.append((session_id, [message["content"] for message in messages]))@@ -700,7 +698,7 @@ async def test_compact_hook_sender_commit_failure_does_not_commit_admin_and_retrself,session_id,messages,- default_user_role_id=None,+ default_user_peer_id=None,session_user_id=None,):self.append_calls.append((session_id, [message["content"] for message in messages]))@@ -792,7 +790,7 @@ async def test_compact_hook_session_context_skips_message_threshold_after_recentself,session_id,messages,- default_user_role_id=None,+ default_user_peer_id=None,session_user_id=None,):self.append_calls.append((session_id, [message["content"] for message in messages]))@@ -848,7 +846,7 @@ async def test_compact_hook_session_context_skips_message_threshold_after_recent@pytest.mark.asyncioasync def test_viking_client_normalizes_system_tool_and_tool_result_messages(monkeypatch):monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))- client = VikingClient(agent_id="workspace")+ client = VikingClient(workspace_id="workspace")normalized = client._normalize_session_messages([@@ -875,7 +873,7 @@ async def test_viking_client_normalizes_system_tool_and_tool_result_messages(mon"timestamp": "2026-05-01T12:00:02Z",},],- default_user_role_id="admin",+ default_user_peer_id="admin",)assert [message["role"] for message in normalized] == [@@ -883,20 +881,22 @@ async def test_viking_client_normalizes_system_tool_and_tool_result_messages(mon"assistant","assistant",]- assert [message["role_id"] for message in normalized] == [- "workspace",- "workspace",- "workspace",+ assert [message["peer_id"] for message in normalized] == [+ "admin",+ "admin",+ "admin",]assert normalized[0]["content"] == "system context"assert normalized[1]["content"] == "tool response"assert normalized[2]["content"] == "assistant answer"+ assert normalized[2]["parts"][1]["type"] == "tool"+ assert normalized[2]["parts"][1]["tool_name"] == "read_file"@pytest.mark.asyncioasync def test_viking_client_append_messages_chunks_batches_at_server_limit(monkeypatch):monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))- client = VikingClient(agent_id="workspace")+ client = VikingClient(workspace_id="workspace")async def _exists(_session_id):return True@@ -917,7 +917,7 @@ async def test_viking_client_append_messages_chunks_batches_at_server_limit(monkresult = await client.append_messages("session-1",[{"role": "user", "content": f"message {index}"} for index in range(101)],- default_user_role_id="admin",+ default_user_peer_id="admin",)assert [len(messages) for _, messages in calls] == [100, 1]@@ -925,9 +925,9 @@ async def test_viking_client_append_messages_chunks_batches_at_server_limit(monk@pytest.mark.asyncio-async def test_search_memory_uses_flat_namespaces(monkeypatch):+async def test_search_memory_uses_user_namespace(monkeypatch):monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))- client = VikingClient(agent_id="workspace")+ client = VikingClient()calls = []@@ -944,18 +944,15 @@ async def test_search_memory_uses_flat_namespaces(monkeypatch):monkeypatch.setattr(client, "_check_user_exists", _exists)monkeypatch.setattr(client.client, "find", _find)- await client.search_memory("hello", "sender-1", "admin", limit=5)+ await client.search_memory("hello", "sender-1", limit=5)- assert calls == [- "viking://user/sender-1/memories/",- "viking://agent/workspace/memories/",- ]+ assert calls == ["viking://user/sender-1/memories/"]@pytest.mark.asyncio-async def test_search_memory_uses_policy_scoped_namespaces(monkeypatch):+async def test_search_memory_uses_user_namespace_without_agent_scope(monkeypatch):monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))- client = VikingClient(agent_id="workspace")+ client = VikingClient()calls = []@@ -969,47 +966,22 @@ async def test_search_memory_uses_policy_scoped_namespaces(monkeypatch):calls.append(target_uri)return _Result()- async def _accounts():- return [- {- "account_id": "acct",- "isolate_user_scope_by_agent": True,- "isolate_agent_scope_by_user": True,- }- ]-monkeypatch.setattr(client, "_check_user_exists", _exists)monkeypatch.setattr(client.client, "find", _find)- monkeypatch.setattr(client.client, "admin_list_accounts", _accounts)- await client.search_memory("hello", "sender-1", "admin", limit=5)+ await client.search_memory("hello", "sender-1", limit=5)- assert calls == [- "viking://user/sender-1/agent/workspace/memories/",- "viking://agent/workspace/user/admin/memories/",- ]+ assert calls == ["viking://user/sender-1/memories/"]@pytest.mark.asyncio-async def test_skill_memory_uri_respects_namespace_policy(monkeypatch):+async def test_skill_memory_uri_uses_user_memory_namespace(monkeypatch):monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))- client = VikingClient(agent_id="workspace")-- async def _accounts():- return [- {- "account_id": "acct",- "isolate_user_scope_by_agent": False,- "isolate_agent_scope_by_user": True,- }- ]-- monkeypatch.setattr(client.client, "admin_list_accounts", _accounts)- await client._load_namespace_policy()+ client = VikingClient()assert (client._skill_memory_uri("planner", "admin")- == "viking://agent/workspace/user/admin/memories/skills/planner.md"+ == "viking://user/admin/memories/skills/planner.md")@@ -1057,51 +1029,40 @@ async def test_openviking_grep_passes_admin_user_id(monkeypatch):@pytest.mark.asyncio-async def test_openviking_search_uses_policy_scoped_user_namespace(monkeypatch):+async def test_openviking_search_uses_user_namespace(monkeypatch):monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))tool = VikingSearchTool()- client = VikingClient(agent_id="workspace")+ client = VikingClient()calls = []- async def _accounts():- return [- {- "account_id": "acct",- "isolate_user_scope_by_agent": True,- "isolate_agent_scope_by_user": False,- }- ]-async def _search(query, target_uri=None, limit=20, user_id=None):- calls.append(target_uri)+ calls.append((target_uri, user_id))return {"memories": [{"uri": target_uri, "abstract": "a", "score": 0.9, "is_leaf": True}]}async def _fake_get_client(_tool_context):return client- monkeypatch.setattr(client.client, "admin_list_accounts", _accounts)monkeypatch.setattr(client, "search", _search)monkeypatch.setattr(tool, "_get_client", _fake_get_client)- await client._load_namespace_policy()tool_context = SimpleNamespace(workspace_id="workspace", memory_user_ids=["sender-1"])result = await tool.execute(tool_context, query="hello")- assert "sender-1/agent/workspace/memories" in result- assert calls == ["viking://user/sender-1/agent/workspace/memories/"]+ assert "sender-1/memories" in result+ assert calls == [("viking://user/sender-1/memories/", "admin")]@pytest.mark.asyncioasync def test_openviking_search_user_key_mode_uses_current_user_namespace(monkeypatch):monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("user"))tool = VikingSearchTool()- client = VikingClient(agent_id="workspace")+ client = VikingClient()calls = []async def _search(query, target_uri=None, limit=20, user_id=None):- calls.append(target_uri)+ calls.append((target_uri, user_id))return {"memories": [{"uri": target_uri, "abstract": "a", "score": 0.9, "is_leaf": True}]}async def _fake_get_client(_tool_context):@@ -1116,4 +1077,4 @@ async def test_openviking_search_user_key_mode_uses_current_user_namespace(monkeresult = await tool.execute(tool_context, query="hello")assert "viking://user/memories/" in result- assert calls == ["viking://user/memories/"]+ assert calls == [("viking://user/memories/", "admin")]diff --git a/bot/vikingbot/agent/context.py b/bot/vikingbot/agent/context.pyindex 13c45a49f..a3bb5a8e9 100644--- a/bot/vikingbot/agent/context.py+++ b/bot/vikingbot/agent/context.py@@ -169,7 +169,6 @@ Skills with available="false" need dependencies installed first - you can try inmemory_users: list[str] | None = None,ov_tools_enable: bool = True,is_first_round: bool = True,- agent_id: str | None = None,) -> str:"""Build the system prompt from bootstrap files, memory, and skills.@@ -204,11 +203,8 @@ Skills with available="false" need dependencies installed first - you can try inexp_first_round_only = load_config().ov_server.recall_exp_first_round_onlyif exp_first_round_only:- # Alt mode: skip per-turn user+agent recall; inject exp once per session.- # When the caller provides an explicit agent_id (e.g. tau2 runner passing- # a per-domain id like "airline_v0"), use it as the experience workspace- # so retrieval targets viking://agent/<agent_id>/memories/experiences/.- exp_workspace_id = agent_id or workspace_id+ # Alt mode: skip per-turn recall; inject experience memory once per session.+ exp_workspace_id = workspace_idself.latest_relevant_memories = Noneif is_first_round:start = _time.time()@@ -314,7 +310,6 @@ IMPORTANT:ov_tools_enable: bool = True,profile_user_list: list[str] | None = None,memory_users: list[str] | None = None,- agent_id: str | None = None,) -> list[dict[str, Any]]:"""Build the complete message list for an LLM call.@@ -352,7 +347,6 @@ IMPORTANT:memory_users,ov_tools_enable=ov_tools_enable,is_first_round=not history,- agent_id=agent_id,)messages.append({"role": "user", "content": user_info})diff --git a/bot/vikingbot/agent/memory.py b/bot/vikingbot/agent/memory.pyindex 20309500a..0fce09c48 100644--- a/bot/vikingbot/agent/memory.py+++ b/bot/vikingbot/agent/memory.py@@ -192,12 +192,11 @@ class MemoryStore:logger.info(f"user_ids={search_user_ids}")logger.info(f"admin_user_id={admin_user_id}")- client = await VikingClient.create(agent_id=workspace_id)+ client = await VikingClient.create()result = await client.search_memory(query=current_message,user_ids=search_user_ids,- agent_user_id=admin_user_id,- limit=10,+ limit=30,)if not result:return ""@@ -205,26 +204,18 @@ class MemoryStore:# Log raw search results for debuggingmemory_list = []- memory_list.append(f"user_memory[{len(result['user_memory'])}]:")+ memory_list.append(f"user_memory[{len(result)}]:")- for i, mem in enumerate(result["user_memory"]):- uri = mem.get("uri", "") if isinstance(mem, dict) else getattr(mem, "uri", "")- score = mem.get("score", 0) if isinstance(mem, dict) else getattr(mem, "score", 0)- memory_list.append(f"{i},{uri},{score}")- memory_list.append(f"agent_memory[{len(result['agent_memory'])}]:")- for i, mem in enumerate(result["agent_memory"]):+ for i, mem in enumerate(result):uri = mem.get("uri", "") if isinstance(mem, dict) else getattr(mem, "uri", "")score = mem.get("score", 0) if isinstance(mem, dict) else getattr(mem, "score", 0)memory_list.append(f"{i},{uri},{score}")raw_memories_log = "\n".join(memory_list)logger.info(f"[RAW_MEMORIES]\n{raw_memories_log}")user_memory = await self._parse_viking_memory(- result["user_memory"], client, min_score=0.1, max_chars=4000- )- agent_memory = await self._parse_viking_memory(- result["agent_memory"], client, min_score=0.1, max_chars=2000+ result, client, min_score=0.1, max_chars=4000)- return f"### user memories:\n{user_memory}\n### agent memories:\n{agent_memory}"+ return f"### user memories:\n{user_memory}"except Exception as e:logger.error(f"[READ_USER_MEMORY]: search error. {e}")return ""@@ -240,7 +231,7 @@ class MemoryStore:client = Nonetry:ov_cfg = load_config().ov_server- client = await VikingClient.create(agent_id=workspace_id)+ client = await VikingClient.create()experiences = await client.search_experiences(query, limit=ov_cfg.exp_recall_limit)logger.info(f"[READ_EXPERIENCE_MEMORY]: found {len(experiences)} experiences, query={query[:50]}"@@ -267,7 +258,7 @@ class MemoryStore:async def get_viking_user_profile(self, workspace_id: str, user_id: str) -> str:client = Nonetry:- client = await VikingClient.create(agent_id=workspace_id)+ client = await VikingClient.create()result = await client.read_user_profile(user_id)return result or ""except Exception as e:@@ -295,7 +286,7 @@ class MemoryStore:client = Nonetry:- client = await VikingClient.create(agent_id=workspace_id)+ client = await VikingClient.create()async def fetch_profile(user_id: str) -> tuple[str, str]:"""Fetch a single user profile."""diff --git a/bot/vikingbot/agent/tools/ov_file.py b/bot/vikingbot/agent/tools/ov_file.pyindex be0547e07..cb314bc89 100644--- a/bot/vikingbot/agent/tools/ov_file.py+++ b/bot/vikingbot/agent/tools/ov_file.py@@ -19,8 +19,9 @@ class OVFileTool(Tool, ABC):self._client = Noneasync def _get_client(self, tool_context: ToolContext):+ del tool_contextif self._client is None:- self._client = await VikingClient.create(tool_context.workspace_id)+ self._client = await VikingClient.create()return self._client@@ -335,7 +336,7 @@ class VikingAddResourceTool(OVFileTool):if not local_path.is_file():return f"Error: Not a file: {path}"- client = await VikingClient.create(tool_context.workspace_id)+ client = await VikingClient.create()result = await client.add_resource(path, description)if result:diff --git a/bot/vikingbot/config/schema.py b/bot/vikingbot/config/schema.pyindex 0f2e68a05..933e12190 100644--- a/bot/vikingbot/config/schema.py+++ b/bot/vikingbot/config/schema.py@@ -519,7 +519,6 @@ class OpenVikingConfig(BaseModel):root_api_key: str = ""account_id: str = "default"admin_user_id: str = "default"- agent_id: str = ""exp_write_tools: list[str] = Field(default_factory=lambda: ["write_file", "edit_file"])# When True, switch auto-recall mode: skip the per-turn user+agent memory retrieval# entirely, and instead retrieve experience memory once per session (on the firstdiff --git a/bot/vikingbot/hooks/builtins/openviking_hooks.py b/bot/vikingbot/hooks/builtins/openviking_hooks.pyindex a44325aa4..51a47459c 100644--- a/bot/vikingbot/hooks/builtins/openviking_hooks.py+++ b/bot/vikingbot/hooks/builtins/openviking_hooks.py@@ -30,18 +30,16 @@ except Exception:VikingClient = Noneov = None-# Clients are cached per workspace so canonical agent_id routing stays aligned-# with OpenViking account namespace policy.-_global_clients: dict[str | None, VikingClient] = {}+_global_client: Any = Noneasync def get_global_client(workspace_id: str | None) -> VikingClient:- """Get or create a workspace-scoped VikingClient."""- client = _global_clients.get(workspace_id)- if client is None:- client = await VikingClient.create(workspace_id)- _global_clients[workspace_id] = client- return client+ """Get or create the shared VikingClient."""+ del workspace_id+ global _global_client+ if _global_client is None:+ _global_client = await VikingClient.create()+ return _global_clientclass OpenVikingCompactHook(Hook):@@ -135,7 +133,7 @@ class OpenVikingCompactHook(Hook):append_result = await client.append_messages(session_id=sender_session_id,messages=user_messages,- default_user_role_id=user_id,+ default_user_peer_id=user_id,session_user_id=user_id,)return {@@ -182,7 +180,7 @@ class OpenVikingCompactHook(Hook):admin_append_result = await client.append_messages(session_id=session_id,messages=messages_to_sync,- default_user_role_id=admin_user_id,+ default_user_peer_id=admin_user_id,session_user_id=admin_user_id,)state["last_synced_local_index"] = len(session.messages) - 1diff --git a/bot/vikingbot/openviking_mount/README.md b/bot/vikingbot/openviking_mount/README.mdindex 6104ef1e5..25213dbc8 100644--- a/bot/vikingbot/openviking_mount/README.md+++ b/bot/vikingbot/openviking_mount/README.md@@ -8,7 +8,7 @@## 功能特性- **文件系统范式**: 将 OpenViking 的 `viking://` URI 映射到本地文件路径-- **多作用域支持**: 支持 resources、session、user、agent 等多种作用域挂载+- **多作用域支持**: 支持 resources、session、user 等多种作用域挂载- **挂载管理**: 支持多个挂载点的生命周期管理- **语义搜索**: 通过文件系统路径进行语义搜索- **层级内容访问**: 支持 L0 (abstract)、L1 (overview)、L2 (details) 三层内容访问@@ -125,7 +125,6 @@ vikingbot/openviking_mount/| `RESOURCES` | 只挂载资源目录 || `SESSION` | 只挂载会话目录 || `USER` | 只挂载用户目录 |-| `AGENT` | 只挂载 Agent 目录 || `ALL` | 挂载所有作用域 |#### 主要方法@@ -177,7 +176,6 @@ OpenViking URI 本地路径viking://resources/foo -> {mount_point}/resources/fooviking://session/bar -> {mount_point}/session/barviking://user/baz -> {mount_point}/user/baz-viking://agent/qux -> {mount_point}/agent/qux```## 测试diff --git a/bot/vikingbot/openviking_mount/mount.py b/bot/vikingbot/openviking_mount/mount.pyindex c106c5d2c..79b353d5a 100644--- a/bot/vikingbot/openviking_mount/mount.py+++ b/bot/vikingbot/openviking_mount/mount.py@@ -7,15 +7,15 @@ OpenViking Filesystem Mount Module - Core Implementationfrom __future__ import annotations-import sys-from pathlib import Path-from typing import Any, Dict, List, Optional, Union-from dataclasses import dataclass, field+from dataclasses import dataclassfrom enum import Enum-import openviking as ov+from pathlib import Path+from typing import List, Optional, Unionfrom loguru import logger+import openviking as ov+class MountScope(Enum):"""OpenViking挂载作用域"""@@ -23,7 +23,6 @@ class MountScope(Enum):RESOURCES = "resources"SESSION = "session"USER = "user"- AGENT = "agent"ALL = "all"@@ -371,7 +370,7 @@ class OpenVikingMount:is_dir=False, # 需要根据实际结果判断)if hasattr(r, "score"):- setattr(file_info, "score", r.score)+ file_info.score = r.scorefile_infos.append(file_info)return file_infosdiff --git a/bot/vikingbot/openviking_mount/ov_server.py b/bot/vikingbot/openviking_mount/ov_server.pyindex a20adb11e..e28fa4212 100644--- a/bot/vikingbot/openviking_mount/ov_server.py+++ b/bot/vikingbot/openviking_mount/ov_server.py@@ -1,5 +1,7 @@import asyncio-import hashlib+import json+import re+import uuidfrom typing import Any, Dict, List, Optionalfrom loguru import logger@@ -11,21 +13,12 @@ from vikingbot.openviking_mount.user_apikey_manager import UserApiKeyManagerviking_resource_prefix = "viking://resources/"-def _is_session_key(agent_id: Optional[str]) -> bool:- """Whether agent_id is a session key rather than a standalone agent workspace.-- Session keys (e.g. "cli__default__<uuid>") contain "__"; a per-domain id such as- the tau2 domain "airline_v0" does not, and is treated as an isolated agent- namespace instead of the shared "default" one.- """- return agent_id is not None and "__" in agent_id--class VikingClient:- def __init__(self, agent_id: Optional[str] = None):+ def __init__(self, workspace_id: Optional[str] = None):config = load_config()openviking_config = config.ov_serverself.openviking_config = openviking_config+ self.workspace_id = workspace_idself.ov_path = config.ov_data_pathself.mode = openviking_config.modeself.api_key_type = (openviking_config.api_key_type or "root").strip().lower()@@ -35,41 +28,20 @@ class VikingClient:self._apikey_manager = Noneself.admin_user_client = Noneself._user_clients = {}- self._namespace_policy = {- "isolate_user_scope_by_agent": False,- "isolate_agent_scope_by_user": False,- }- self._namespace_policy_loaded = Falseif openviking_config.mode == "local":- # Session keys fall back to the shared "default" namespace; a standalone- # per-domain id (e.g. "airline_v0") is treated as an isolated agent workspace- # and threaded into the HTTP client so storage is scoped per id.- if agent_id is None or _is_session_key(agent_id):- self.client = ov.AsyncHTTPClient(url=openviking_config.server_url)- self.agent_id = "default"- else:- self.client = ov.AsyncHTTPClient(- url=openviking_config.server_url,- agent_id=agent_id,- )- self.agent_id = agent_id+ self.client = ov.AsyncHTTPClient(url=openviking_config.server_url)self.account_id = "default"self.user_id = "default"self.admin_user_id = "default"return- if agent_id and "#" in agent_id:- agent_id = agent_id.split("#", 1)[0]-- self.agent_id = agent_idself.account_id = openviking_config.account_idself.admin_user_id = openviking_config.admin_user_idremote_client_kwargs = {"url": openviking_config.server_url,"api_key": openviking_config.root_api_key,- "agent_id": agent_id,}if self._is_root_key_mode():remote_client_kwargs["account"] = openviking_config.account_id@@ -87,16 +59,11 @@ class VikingClient:async def _initialize(self):"""Initialize the client (must be called after construction)"""await self.client.initialize()- await self._load_namespace_policy()@classmethod- async def create(cls, agent_id: Optional[str] = None):- """Factory method to create and initialize a VikingClient instance.-- Args:- agent_id: The agent ID to use- """- instance = cls(agent_id)+ async def create(cls, workspace_id: Optional[str] = None):+ """Factory method to create and initialize a VikingClient instance."""+ instance = cls(workspace_id=workspace_id)await instance._initialize()return instance@@ -125,9 +92,6 @@ class VikingClient:"reason": getattr(relation, "reason", ""),}- def get_agent_space_name(self, user_id: str) -> str:- return hashlib.md5(f"{user_id}:{self.agent_id}".encode()).hexdigest()[:12]-def _is_root_key_mode(self) -> bool:return self.mode == "remote" and self.api_key_type == "root"@@ -139,67 +103,20 @@ class VikingClient:return ""return user_id or self.admin_user_id- async def _load_namespace_policy(self) -> None:- if self._namespace_policy_loaded:- return-- policy = {- "isolate_user_scope_by_agent": False,- "isolate_agent_scope_by_user": False,- }-- if self.mode == "remote" and self.account_id:- try:- accounts = await self.client.admin_list_accounts()- for account in accounts or []:- if account.get("account_id") == self.account_id:- policy = {- "isolate_user_scope_by_agent": bool(- account.get("isolate_user_scope_by_agent", False)- ),- "isolate_agent_scope_by_user": bool(- account.get("isolate_agent_scope_by_user", False)- ),- }- break- except Exception as e:- logger.warning(- f"Failed to load account namespace policy for {self.account_id}: {e}"- )-- self._namespace_policy = policy- self._namespace_policy_loaded = True-def _user_space_fragment(self, user_id: Optional[str]) -> str:effective_user_id = self._effective_user_id(user_id)if not effective_user_id:return ""- if self._namespace_policy["isolate_user_scope_by_agent"] and self.agent_id:- return f"{effective_user_id}/agent/{self.agent_id}"return effective_user_id- def _agent_space_fragment(self, user_id: Optional[str]) -> str:- if not self.agent_id:- return ""- effective_user_id = self._effective_user_id(user_id)- if self._namespace_policy["isolate_agent_scope_by_user"] and effective_user_id:- return f"{self.agent_id}/user/{effective_user_id}"- return self.agent_id-def _memory_target_uri(self, user_id: Optional[str]) -> str:user_space = self._user_space_fragment(user_id)if user_space:return f"viking://user/{user_space}/memories/"return "viking://user/memories/"- def _agent_memory_target_uri(self, user_id: Optional[str]) -> str:- agent_space = self._agent_space_fragment(user_id)- if agent_space:- return f"viking://agent/{agent_space}/memories/"- return "viking://agent/memories/"-def _skill_memory_uri(self, skill_name: str, user_id: Optional[str] = None) -> str:- return f"{self._agent_memory_target_uri(user_id)}skills/{skill_name}.md"+ return f"{self._memory_target_uri(user_id)}skills/{skill_name}.md"def should_sender_fanout(self) -> bool:return self._is_root_key_mode()@@ -248,7 +165,6 @@ class VikingClient:async def read_user_profile(self, user_id: str) -> str:"""读取用户 profile。"""- await self._load_namespace_policy()effective_user_id = self._effective_user_id(user_id)user_exists = await self._check_user_exists(effective_user_id)@@ -295,7 +211,6 @@ class VikingClient:}async def search_user_memory(self, query: str, user_id: str) -> list[Any]:- await self._load_namespace_policy()effective_user_id = self._effective_user_id(user_id)user_exists = await self._check_user_exists(effective_user_id)if not user_exists:@@ -397,7 +312,6 @@ class VikingClient:client_kwargs = {"url": self.openviking_config.server_url,"api_key": user_api_key,- "agent_id": self.agent_id,}if effective_user_id == self.admin_user_id:client_kwargs["account"] = self.account_id@@ -410,10 +324,9 @@ class VikingClient:return self.client, Falseasync def search_memory(- self, query: str, user_ids: str | list[str], agent_user_id: str, limit: int = 10- ) -> dict[str, list[Any]]:- """通过上下文消息,检索viking 的user memory 和 agent memory。"""- await self._load_namespace_policy()+ self, query: str, user_ids: str | list[str], limit: int = 10+ ) -> list[Any]:+ """通过上下文消息检索用户 memory。"""def _extract_memories(result: Any) -> list[Any]:if not result:@@ -446,24 +359,11 @@ class VikingClient:)all_user_memories.extend(_extract_memories(user_memory))- uri_agent_memory = self._agent_memory_target_uri(agent_user_id)- agent_memory_result = await self.client.find(- query=query,- target_uri=uri_agent_memory,- limit=limit,- )- all_agent_memories = _extract_memories(agent_memory_result)-- return {"user_memory": all_user_memories, "agent_memory": all_agent_memories}+ return all_user_memoriesasync def search_experiences(self, query: str, limit: int = 5) -> list[Any]:- """用 query 检索 agent experience 记忆。"""- effective_agent_id = self.openviking_config.agent_id or "default"- # A per-instance, non-session agent_id overrides the global config so each domain- # reads from its own experience namespace.- if self.agent_id and not _is_session_key(self.agent_id):- effective_agent_id = self.agent_id- exp_uri = f"viking://agent/{effective_agent_id}/memories/experiences/"+ """用 query 检索 vikingbot experience 记忆。"""+ exp_uri = f"{self._memory_target_uri(self.admin_user_id)}experiences/"result = await self.search(query=query, target_uri=exp_uri, limit=limit)return result.get("memories", [])@@ -533,17 +433,12 @@ class VikingClient:client = ov.AsyncHTTPClient(url=self.openviking_config.server_url,api_key=api_key,- agent_id=self.agent_id,- account=self.account_id,- user=user_id,)await client.initialize()self._user_clients[user_id] = clientreturn client- def _assistant_role_id(self) -> Optional[str]:- if self.agent_id:- return self.agent_id+ def _assistant_peer_id(self) -> Optional[str]:if self.admin_user_id:return self.admin_user_idreturn None@@ -551,10 +446,11 @@ class VikingClient:def _normalize_session_messages(self,messages: list[dict[str, Any]],- default_user_role_id: Optional[str] = None,+ default_user_peer_id: Optional[str] = None,+ session_id: Optional[str] = None,) -> list[dict[str, Any]]:normalized: list[dict[str, Any]] = []- assistant_role_id = self._assistant_role_id()+ assistant_peer_id = self._assistant_peer_id()for message in messages:role = str(message.get("role") or "").strip().lower()@@ -562,24 +458,81 @@ class VikingClient:continuecontent = self._session_message_content(message)- if not content:+ tools_used = message.get("tools_used") or []+ parts: list[dict[str, Any]] = []++ if content:+ parts.append({"type": "text", "text": content})++ if isinstance(tools_used, list):+ for tool_info in tools_used:+ if not isinstance(tool_info, dict):+ continue+ tool_name = str(tool_info.get("tool_name") or "").strip()+ if not tool_name:+ continue++ raw_args = tool_info.get("args", {})+ if isinstance(raw_args, dict):+ tool_input = raw_args+ else:+ try:+ tool_input = json.loads(raw_args) if raw_args else {}+ except Exception:+ tool_input = {"raw_args": str(raw_args)}++ result_str = str(tool_info.get("result", ""))+ skill_uri = ""+ if tool_name == "read_file" and result_str:+ match = re.search(+ r"^---\s*\nname:\s*(.+?)\s*\n",+ result_str,+ re.MULTILINE,+ )+ if match:+ skill_name = match.group(1).strip()+ skill_uri = self._skill_memory_uri(skill_name, default_user_peer_id)++ tool_id = f"{tool_name}_{uuid.uuid4().hex[:8]}"+ parts.append(+ {+ "type": "tool",+ "tool_id": tool_id,+ "tool_name": tool_name,+ "tool_uri": f"viking://session/{session_id}/tools/{tool_id}"+ if session_id+ else "",+ "tool_input": tool_input,+ "tool_output": result_str[:2000],+ "tool_status": "completed"+ if tool_info.get("execute_success", True)+ else "error",+ "skill_uri": skill_uri,+ "duration_ms": float(tool_info.get("duration", 0.0) or 0.0),+ "prompt_tokens": tool_info.get("input_token"),+ "completion_tokens": tool_info.get("output_token"),+ }+ )++ if not parts:continueov_role = "user" if role == "user" else "assistant"payload = {"role": ov_role,"content": content,+ "parts": parts,"created_at": message.get("created_at") or message.get("timestamp"),}- role_id = message.get("role_id")- if not role_id and ov_role == "user":- role_id = message.get("sender_id") or default_user_role_id- elif not role_id and ov_role == "assistant":- role_id = assistant_role_id+ peer_id = message.get("peer_id")+ if not peer_id and ov_role == "user":+ peer_id = message.get("sender_id") or default_user_peer_id+ elif not peer_id and ov_role == "assistant":+ peer_id = assistant_peer_id- if role_id:- payload["role_id"] = role_id+ if peer_id:+ payload["peer_id"] = peer_idnormalized.append(payload)@@ -618,13 +571,14 @@ class VikingClient:self,session_id: str,messages: list[dict[str, Any]],- default_user_role_id: Optional[str] = None,+ default_user_peer_id: Optional[str] = None,session_user_id: Optional[str] = None,) -> Dict[str, Any]:await self.ensure_session(session_id, user_id=session_user_id)batch = self._normalize_session_messages(messages,- default_user_role_id=default_user_role_id,+ default_user_peer_id=default_user_peer_id,+ session_id=session_id,)if not batch:return {"session_id": session_id, "added": 0, "message_count": 0}@@ -664,7 +618,7 @@ class VikingClient:appended = await self.append_messages(session_id,messages,- default_user_role_id=user_id or self.admin_user_id,+ default_user_peer_id=user_id or self.admin_user_id,session_user_id=user_id,)commit_result = await self.commit_session(@@ -693,7 +647,7 @@ class VikingClient:async def main_test():- client = await VikingClient.create(agent_id="shared")+ client = await VikingClient.create()# res = client.list_resources()# res = await client.search("头有点疼", target_uri="viking://user/memories/")# res = await client.get_viking_memory_context("123", current_message="头疼", history=[])@@ -719,7 +673,6 @@ async def account_test():client = ov.AsyncHTTPClient(url="http://localhost:1933",api_key="",- agent_id="shared",)await client.initialize()diff --git a/crates/ov_cli/README.md b/crates/ov_cli/README.mdindex ce4651392..5d8b4a0bd 100644--- a/crates/ov_cli/README.md+++ b/crates/ov_cli/README.md@@ -27,8 +27,7 @@ Create `~/.openviking/ovcli.conf`:"url": "http://localhost:1933","api_key": "your-api-key","account": "acme",- "user": "alice",- "agent_id": "assistant-1"+ "user": "alice"}```@@ -135,7 +134,7 @@ ov find "API authentication" --threshold 0.7 --limit 5ov ls viking://resources --recursive# Temporarily override identity from CLI flags-ov --account acme --user alice --agent-id assistant-2 ls viking://+ov --account acme --user alice ls viking://# Glob searchov glob "**/*.md" --uri viking://resourcesdiff --git a/crates/ov_cli/src/base_client.rs b/crates/ov_cli/src/base_client.rsindex 07d775f65..71efdec7a 100644--- a/crates/ov_cli/src/base_client.rs+++ b/crates/ov_cli/src/base_client.rs@@ -145,7 +145,6 @@ pub struct BaseClient {pub(crate) api_key: Option<String>,pub(crate) account: Option<String>,pub(crate) user: Option<String>,- pub(crate) agent_id: Option<String>,pub(crate) profile_enabled: bool,pub(crate) extra_headers: Option<std::collections::HashMap<String, String>>,}@@ -154,7 +153,6 @@ impl BaseClient {pub fn new(base_url: impl Into<String>,api_key: Option<String>,- agent_id: Option<String>,account: Option<String>,user: Option<String>,timeout_secs: f64,@@ -172,7 +170,6 @@ impl BaseClient {api_key,account,user,- agent_id,profile_enabled,extra_headers,}@@ -190,10 +187,6 @@ impl BaseClient {self.user.as_deref()}- pub fn agent_id(&self) -> Option<&str> {- self.agent_id.as_deref()- }-pub fn api_key(&self) -> Option<&str> {self.api_key.as_deref()}@@ -209,11 +202,6 @@ impl BaseClient {headers.insert("X-API-Key", value);}}- if let Some(agent_id) = &self.agent_id {- if let Ok(value) = reqwest::header::HeaderValue::from_str(agent_id) {- headers.insert("X-OpenViking-Agent", value);- }- }if let Some(account) = &self.account {if let Ok(value) = reqwest::header::HeaderValue::from_str(account) {headers.insert("X-OpenViking-Account", value);@@ -298,7 +286,10 @@ impl BaseClient {})}- pub(crate) fn create_client_with_timeout(&self, timeout: std::time::Duration) -> Result<ReqwestClient> {+ pub(crate) fn create_client_with_timeout(+ &self,+ timeout: std::time::Duration,+ ) -> Result<ReqwestClient> {ReqwestClient::builder().timeout(timeout).build()@@ -369,10 +360,7 @@ impl BaseClient {let url = format!("{}{}", self.base_url, path);let client = self.create_client_with_timeout(timeout)?;- let request = client- .post(&url)- .headers(self.build_headers())- .json(body);+ let request = client.post(&url).headers(self.build_headers()).json(body);let request = if self.profile_enabled {request.query(&[("profile", "1")])} else {@@ -392,11 +380,7 @@ impl BaseClient {body: &B,) -> Result<T> {let url = format!("{}{}", self.base_url, path);- let request = self- .http- .put(&url)- .headers(self.build_headers())- .json(body);+ let request = self.http.put(&url).headers(self.build_headers()).json(body);let request = if self.profile_enabled {request.query(&[("profile", "1")])} else {@@ -595,13 +579,13 @@ mod tests {None,None,None,- None,5.0,true,None,);- let params = client.append_profile_query(&[("to_uri".to_string(), "viking://x".to_string())]);+ let params =+ client.append_profile_query(&[("to_uri".to_string(), "viking://x".to_string())]);assert_eq!(params,@@ -619,7 +603,6 @@ mod tests {None,None,None,- None,5.0,true,None,@@ -652,7 +635,11 @@ impl<'a> FileUploader<'a> {self}- pub fn zip_directory(&self, dir_path: &Path, ignore_dirs: Option<&str>) -> Result<NamedTempFile> {+ pub fn zip_directory(+ &self,+ dir_path: &Path,+ ignore_dirs: Option<&str>,+ ) -> Result<NamedTempFile> {if !dir_path.is_dir() {return Err(Error::Network(format!("Path {} is not a directory",@@ -781,7 +768,10 @@ impl<'a> FileUploader<'a> {if let Some(pb) = pb {if total_size > 0 {- pb.finish_with_message(format!("Compression complete: {:.2} MiB → {:.2} MiB", original_size_mb, zip_size_mb));+ pb.finish_with_message(format!(+ "Compression complete: {:.2} MiB → {:.2} MiB",+ original_size_mb, zip_size_mb+ ));} else {pb.finish_with_message(format!("Compression complete: {:.2} MiB", zip_size_mb));}@@ -852,15 +842,22 @@ impl<'a> FileUploader<'a> {let file_size = file_content.len() as u64;if verbose {- eprintln!("Uploading: {} ({:.2} MB)", file_name, file_size as f64 / 1024.0 / 1024.0);+ eprintln!(+ "Uploading: {} ({:.2} MB)",+ file_name,+ file_size as f64 / 1024.0 / 1024.0+ );}let pb = ProgressBar::new_spinner();- pb.set_message(format!("Uploading {} ({:.2} MB)...", file_name, file_size as f64 / 1024.0 / 1024.0));+ pb.set_message(format!(+ "Uploading {} ({:.2} MB)...",+ file_name,+ file_size as f64 / 1024.0 / 1024.0+ ));pb.enable_steady_tick(std::time::Duration::from_millis(100));- let part = reqwest::multipart::Part::bytes(file_content)- .file_name(file_name.to_string());+ let part = reqwest::multipart::Part::bytes(file_content).file_name(file_name.to_string());let part = part.mime_str("application/octet-stream")diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex ab34d60d9..288db767a 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -19,7 +19,6 @@ impl HttpClient {pub fn new(base_url: impl Into<String>,api_key: Option<String>,- agent_id: Option<String>,account: Option<String>,user: Option<String>,timeout_secs: f64,@@ -30,7 +29,6 @@ impl HttpClient {base: BaseClient::new(base_url,api_key,- agent_id,account,user,timeout_secs,@@ -44,10 +42,6 @@ impl HttpClient {self.base.user_id()}- pub fn agent_id(&self) -> Option<&str> {- self.base.agent_id()- }-pub fn api_key(&self) -> Option<&str> {self.base.api_key()}@@ -146,7 +140,8 @@ impl HttpClient {verbose: bool,ignore_dirs: Option<&str>,) -> Result<tempfile::NamedTempFile> {- self.create_uploader().zip_directory_with_progress(dir_path, verbose, ignore_dirs)+ self.create_uploader()+ .zip_directory_with_progress(dir_path, verbose, ignore_dirs)}async fn upload_temp_file(&self, file_path: &Path) -> Result<String> {@@ -377,6 +372,7 @@ impl HttpClient {until: Option<String>,time_field: Option<String>,level: Option<Vec<i32>>,+ peer_id: Option<String>,) -> Result<serde_json::Value> {let body = serde_json::json!({"query": query,@@ -387,6 +383,7 @@ impl HttpClient {"until": until,"time_field": time_field,"level": level,+ "peer_id": peer_id,});self.post("/api/v1/search/find", &body).await}@@ -402,6 +399,7 @@ impl HttpClient {until: Option<String>,time_field: Option<String>,level: Option<Vec<i32>>,+ peer_id: Option<String>,) -> Result<serde_json::Value> {let body = serde_json::json!({"query": query,@@ -413,6 +411,7 @@ impl HttpClient {"until": until,"time_field": time_field,"level": level,+ "peer_id": peer_id,});self.post("/api/v1/search/search", &body).await}@@ -944,11 +943,6 @@ impl HttpClient {self.get(&path, ¶ms).await}- pub async fn admin_list_agents(&self, account_id: &str) -> Result<Value> {- let path = format!("/api/v1/admin/accounts/{}/agents", account_id);- self.get(&path, &[]).await- }-pub async fn admin_remove_user(&self, account_id: &str, user_id: &str) -> Result<Value> {let path = format!("/api/v1/admin/accounts/{}/users/{}", account_id, user_id);self.delete(&path, &[]).await@@ -1154,7 +1148,8 @@ impl HttpClient {pub async fn trigger_watch_by_uri(&self, to_uri: &str) -> Result<serde_json::Value> {let params = vec![("to_uri".to_string(), to_uri.to_string())];let empty = serde_json::json!({});- self.post_with_query("/api/v1/watches/trigger", &empty, ¶ms).await+ self.post_with_query("/api/v1/watches/trigger", &empty, ¶ms)+ .await}}@@ -1190,7 +1185,6 @@ mod tests {let client = BaseClient::new("http://localhost:1933",Some("test-key".to_string()),- Some("assistant-1".to_string()),Some("acme".to_string()),Some("alice".to_string()),5.0,diff --git a/crates/ov_cli/src/commands/admin.rs b/crates/ov_cli/src/commands/admin.rsindex 4ac6b04e9..13693a89f 100644--- a/crates/ov_cli/src/commands/admin.rs+++ b/crates/ov_cli/src/commands/admin.rs@@ -82,17 +82,6 @@ pub async fn list_users(Ok(())}-pub async fn list_agents(- client: &HttpClient,- account_id: &str,- output_format: OutputFormat,- compact: bool,-) -> Result<()> {- let response = client.admin_list_agents(account_id).await?;- output_success(&response, output_format, compact);- Ok(())-}-pub async fn remove_user(client: &HttpClient,account_id: &str,diff --git a/crates/ov_cli/src/commands/filesystem.rs b/crates/ov_cli/src/commands/filesystem.rsindex d910de9b8..9c8b8a168 100644--- a/crates/ov_cli/src/commands/filesystem.rs+++ b/crates/ov_cli/src/commands/filesystem.rs@@ -486,11 +486,11 @@ mod tests {"abstract": "The resources directory is a centralized collection of learning and reference materials focused on cloud architecture, AWS best practices, and technical quick-reference content."},{- "uri": "viking://agent",+ "uri": "viking://user/default/memories","size": 0,"isDir": true,"modTime": "2026-05-25",- "abstract": "# viking://agent [Directory abstract is not ready]"+ "abstract": "# viking://user/default/memories [Directory abstract is not ready]"}]);diff --git a/crates/ov_cli/src/commands/search.rs b/crates/ov_cli/src/commands/search.rsindex 52f0cb51c..fae633b0f 100644--- a/crates/ov_cli/src/commands/search.rs+++ b/crates/ov_cli/src/commands/search.rs@@ -54,6 +54,7 @@ pub async fn find(until: Option<&str>,time_field: Option<&str>,level: Option<Vec<i32>>,+ peer_id: Option<&str>,output_format: OutputFormat,compact: bool,) -> Result<()> {@@ -67,6 +68,7 @@ pub async fn find(until.map(|s| s.to_string()),time_field.map(|s| s.to_string()),level,+ peer_id.map(|s| s.to_string()),).await?;output_search_results(@@ -89,6 +91,7 @@ pub async fn search(until: Option<&str>,time_field: Option<&str>,level: Option<Vec<i32>>,+ peer_id: Option<&str>,output_format: OutputFormat,compact: bool,) -> Result<()> {@@ -103,6 +106,7 @@ pub async fn search(until.map(|s| s.to_string()),time_field.map(|s| s.to_string()),level,+ peer_id.map(|s| s.to_string()),).await?;output_search_results(diff --git a/crates/ov_cli/src/commands/session.rs b/crates/ov_cli/src/commands/session.rsindex 064b858e7..93b5bd560 100644--- a/crates/ov_cli/src/commands/session.rs+++ b/crates/ov_cli/src/commands/session.rs@@ -66,9 +66,6 @@ fn render_session_get_for_table(value: &Value) -> Option<String> {if let Some(users) = object.get("participant_user_ids") {push_row(&mut lines, "participants", &format_list(users));}- if let Some(agents) = object.get("participant_agent_ids") {- push_row(&mut lines, "agents", &format_list(agents));- }if let Some(user) = object.get("user").and_then(Value::as_object) {push_row(&mut lines, "active user", &format_identity(user));}@@ -175,7 +172,7 @@ fn format_list(value: &Value) -> String {}fn format_identity(object: &serde_json::Map<String, Value>) -> String {- ["account_id", "user_id", "agent_id"]+ ["account_id", "user_id"].into_iter().filter_map(|key| object.get(key).map(|value| (key, format_json_value(value)))).filter(|(_, value)| !value.is_empty() && value != "null")@@ -311,14 +308,18 @@ pub async fn add_message(session_id: &str,role: &str,content: &str,+ peer_id: Option<&str>,output_format: OutputFormat,compact: bool,) -> Result<()> {let path = format!("/api/v1/sessions/{}/messages", url_encode(session_id));- let body = json!({+ let mut body = json!({"role": role,"content": content});+ if let Some(peer_id) = peer_id {+ body["peer_id"] = json!(peer_id);+ }let response: serde_json::Value = client.post(&path, &body).await?;output_success(&response, output_format, compact);@@ -477,7 +478,6 @@ mod tests {"updated_at": "2026-05-26T10:00:07.603Z","created_by_user_id": "haozhe","participant_user_ids": ["haozhe"],- "participant_agent_ids": ["deerflow"],"message_count": 0,"commit_count": 1,"memories_extracted": {@@ -499,8 +499,7 @@ mod tests {"total_message_count": 2,"user": {"account_id": "default",- "user_id": "haozhe",- "agent_id": "default"+ "user_id": "haozhe"}});diff --git a/crates/ov_cli/src/config.rs b/crates/ov_cli/src/config.rsindex 9bbaeecd0..dac0eb4fc 100644--- a/crates/ov_cli/src/config.rs+++ b/crates/ov_cli/src/config.rs@@ -45,8 +45,6 @@ pub struct Config {pub account: Option<String>,#[serde(skip_serializing_if = "Option::is_none", alias = "user_id")]pub user: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]- pub agent_id: Option<String>,#[serde(default = "default_timeout",skip_serializing_if = "is_default_timeout"@@ -151,7 +149,6 @@ impl Default for Config {root_api_key: None,account: None,user: None,- agent_id: None,timeout: 60.0,output: "table".to_string(),echo_command: true,@@ -358,15 +355,13 @@ mod tests {"url": "http://127.0.0.1:1933","api_key": "test-key","account": "acme",- "user": "alice",- "agent_id": "assistant-1"+ "user": "alice"}"#,).expect("config should deserialize");assert_eq!(config.account.as_deref(), Some("acme"));assert_eq!(config.user.as_deref(), Some("alice"));- assert_eq!(config.agent_id.as_deref(), Some("assistant-1"));assert!(config.upload.ignore_dirs.is_none());assert!(config.upload.include.is_none());assert!(config.upload.exclude.is_none());diff --git a/crates/ov_cli/src/config_wizard/store.rs b/crates/ov_cli/src/config_wizard/store.rsindex 1a2a73ca9..fe08ab06d 100644--- a/crates/ov_cli/src/config_wizard/store.rs+++ b/crates/ov_cli/src/config_wizard/store.rs@@ -563,7 +563,6 @@ pub(crate) async fn validate_candidate_config_with_role(let client = BaseClient::new(&config.url,auth.api_key.clone(),- config.agent_id.clone(),auth.account,auth.user,timeout,diff --git a/crates/ov_cli/src/config_wizard/wizard.rs b/crates/ov_cli/src/config_wizard/wizard.rsindex d37f12d36..efc9601a9 100644--- a/crates/ov_cli/src/config_wizard/wizard.rs+++ b/crates/ov_cli/src/config_wizard/wizard.rs@@ -752,7 +752,6 @@ async fn status_box_runtime(active: Option<&Config>) -> StatusBoxRuntime {let client = BaseClient::new(config.url.clone(),auth.api_key,- config.agent_id.clone(),auth.account,auth.user,STATUS_BOX_PROBE_TIMEOUT_SECS,diff --git a/crates/ov_cli/src/error_ui.rs b/crates/ov_cli/src/error_ui.rsindex f746529a0..97260c046 100644--- a/crates/ov_cli/src/error_ui.rs+++ b/crates/ov_cli/src/error_ui.rs@@ -347,7 +347,6 @@ fn contextual_help_command(command: &str) -> Option<String> {"delete-account","register-user","list-users",- "list-agents","remove-user","set-role","regenerate-key",diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rsindex 6f6957a73..e89e7e17a 100644--- a/crates/ov_cli/src/handlers.rs+++ b/crates/ov_cli/src/handlers.rs@@ -78,7 +78,6 @@ pub async fn handle_add_resource(let client = client::HttpClient::new(&ctx.config.url,auth.api_key,- ctx.config.agent_id.clone(),auth.account,auth.user,effective_timeout,@@ -331,12 +330,14 @@ pub async fn handle_session(cmd: SessionCommands, ctx: CliContext) -> Result<()>session_id,role,content,+ peer_id,} => {commands::session::add_message(&client,&session_id,&role,&content,+ peer_id.as_deref(),ctx.output_format,ctx.compact,)@@ -419,9 +420,6 @@ pub async fn handle_admin(cmd: AdminCommands, ctx: CliContext) -> Result<()> {).await}- AdminCommands::ListAgents { account_id } => {- commands::admin::list_agents(&client, &account_id, ctx.output_format, ctx.compact).await- }AdminCommands::RemoveUser {account_id,user_id,@@ -1108,6 +1106,7 @@ pub async fn handle_find(after: Option<String>,before: Option<String>,level: Option<Vec<i32>>,+ peer_id: Option<String>,ctx: CliContext,) -> Result<()> {let mut params = vec![format!("--uri={}", uri), format!("-n {}", node_limit)];@@ -1124,6 +1123,9 @@ pub async fn handle_find(.join(",")));}+ if let Some(ref p) = peer_id {+ params.push(format!("--peer-id {}", p));+ }params.push(format!("\"{}\"", query));print_command_echo("ov find", ¶ms.join(" "), ctx.config.echo_command);let client = ctx.get_client();@@ -1137,6 +1139,7 @@ pub async fn handle_find(before.as_deref(),None,level,+ peer_id.as_deref(),ctx.output_format,ctx.compact,)@@ -1152,6 +1155,7 @@ pub async fn handle_search(after: Option<String>,before: Option<String>,level: Option<Vec<i32>>,+ peer_id: Option<String>,ctx: CliContext,) -> Result<()> {let mut params = vec![format!("--uri={}", uri), format!("-n {}", node_limit)];@@ -1171,6 +1175,9 @@ pub async fn handle_search(.join(",")));}+ if let Some(ref p) = peer_id {+ params.push(format!("--peer-id {}", p));+ }params.push(format!("\"{}\"", query));print_command_echo("ov search", ¶ms.join(" "), ctx.config.echo_command);let client = ctx.get_client();@@ -1185,6 +1192,7 @@ pub async fn handle_search(before.as_deref(),None,level,+ peer_id.as_deref(),ctx.output_format,ctx.compact,)diff --git a/crates/ov_cli/src/health_ui.rs b/crates/ov_cli/src/health_ui.rsindex 53e2644ac..a3727d83e 100644--- a/crates/ov_cli/src/health_ui.rs+++ b/crates/ov_cli/src/health_ui.rs@@ -97,20 +97,6 @@ pub(crate) fn render_health_with_language(language,),));- lines.push(detail_line(- match language {- Language::En => "Agent",- Language::ZhCn => "Agent",- },- plain_or_unknown(- identity_field(- payload,- "agent_id",- config.and_then(|c| c.agent_id.as_deref()),- ),- language,- ),- ));lines.push(detail_line(match language {Language::En => "Role",@@ -267,7 +253,6 @@ mod tests {"auth_mode": "api_key","account_id": "default","user_id": "haozhe",- "agent_id": "default","role": "admin"});@@ -287,7 +272,6 @@ mod tests {assert!(plain.contains("Identity"));assert!(plain.contains("Account default"));assert!(plain.contains("User haozhe"));- assert!(plain.contains("Agent default"));assert!(plain.contains("Role admin"));assert!(plain.contains("Details"));assert!(plain.contains("ov status Full system diagnostics"));@@ -302,7 +286,6 @@ mod tests {"auth_mode": "api_key","account_id": "default","user_id": "haozhe",- "agent_id": "default","role": "admin"});diff --git a/crates/ov_cli/src/help_ui.rs b/crates/ov_cli/src/help_ui.rsindex c7245a50c..088d2b343 100644--- a/crates/ov_cli/src/help_ui.rs+++ b/crates/ov_cli/src/help_ui.rs@@ -347,10 +347,6 @@ const GLOBAL_OPTIONS: &[HelpItem] = &[label: "--user <user>",description: "Override X-OpenViking-User for this command.",},- HelpItem {- label: "--agent-id <agent>",- description: "Override X-OpenViking-Agent for this command.",- },];const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[@@ -2275,10 +2271,6 @@ pub(crate) fn render_top_level_help_with_language(language: Language) -> String"--user <user>",copy(language, "Override user", "覆盖用户"),));- lines.push(option_line(- "--agent-id <agent>",- copy(language, "Override agent", "覆盖 Agent"),- ));lines.push(option_line("--sudo",copy(@@ -2476,7 +2468,6 @@ fn localized_help_item_description<'a>("-c, --compact <bool>" => "使用紧凑的表格或 JSON 输出。","--account <account>" => "覆盖本次命令的 X-OpenViking-Account。","--user <user>" => "覆盖本次命令的 X-OpenViking-User。",- "--agent-id <agent>" => "覆盖本次命令的 X-OpenViking-Agent。","--sudo" => "使用 root API Key 执行管理命令。",_ => description,}@@ -2752,7 +2743,6 @@ fn config_help_path(tokens: &[String]) -> Option<Vec<String>> {| "--root-api-key-env"| "--account"| "--user"- | "--agent-id"){i += if token.contains('=') { 1 } else { 2 };@@ -2832,12 +2822,11 @@ fn is_help_flag(token: &str) -> bool {fn consumes_value(token: &str) -> bool {matches!(token,- "-o" | "--output" | "-c" | "--compact" | "--account" | "--user" | "--agent-id"+ "-o" | "--output" | "-c" | "--compact" | "--account" | "--user") || token.starts_with("--output=")|| token.starts_with("--compact=")|| token.starts_with("--account=")|| token.starts_with("--user=")- || token.starts_with("--agent-id=")}#[cfg(test)]diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex 759539cc6..08a9d6427 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -49,7 +49,6 @@ impl CliContext {compact: bool,account: Option<String>,user: Option<String>,- agent_id: Option<String>,sudo: bool,show_progress: Option<bool>,verbose: Option<bool>,@@ -61,9 +60,6 @@ impl CliContext {if user.is_some() {config.user = user;}- if agent_id.is_some() {- config.agent_id = agent_id;- }Self {config,output_format,@@ -94,7 +90,6 @@ impl CliContext {client::HttpClient::new(&self.config.url,auth.api_key,- self.config.agent_id.clone(),auth.account,auth.user,timeout_secs.unwrap_or(self.config.timeout),@@ -126,10 +121,6 @@ struct Cli {#[arg(long, global = true)]user: Option<String>,- /// Agent identifier to send as X-OpenViking-Agent- #[arg(long = "agent-id", global = true)]- agent_id: Option<String>,-/// Use root API key for admin commands#[arg(long, global = true, hide = true)]sudo: bool,@@ -430,6 +421,9 @@ enum Commands {/// Only include results with specific level(s) (0=abstract, 1=overview, 2=file)#[arg(short = 'L', long = "level", value_delimiter = ',')]level: Option<Vec<i32>>,+ /// Limit memory retrieval to this peer plus the current user memory+ #[arg(long = "peer-id")]+ peer_id: Option<String>,},/// [Experimental][Data] Run context-aware retrievalSearch {@@ -461,6 +455,9 @@ enum Commands {/// Only include results with specific level(s) (0=abstract, 1=overview, 2=file)#[arg(short = 'L', long = "level", value_delimiter = ',')]level: Option<Vec<i32>>,+ /// Limit memory retrieval to this peer plus the current user memory+ #[arg(long = "peer-id")]+ peer_id: Option<String>,},/// [Data] Run content pattern searchGrep {@@ -809,6 +806,9 @@ enum SessionCommands {/// Message content#[arg(long)]content: String,+ /// Stable interaction peer id. Omit for self memory.+ #[arg(long = "peer-id")]+ peer_id: Option<String>,},/// Add multiple messages to a sessionAddMessages {@@ -983,11 +983,6 @@ enum AdminCommands {#[arg(long)]role: Option<String>,},- /// List all agent namespaces in an account- ListAgents {- /// Account ID- account_id: String,- },/// Remove a user from an accountRemoveUser {/// Account ID@@ -1178,7 +1173,7 @@ fn find_command_index(args: &[OsString]) -> Option<usize> {while i < args.len() {let token = args[i].to_string_lossy();match token.as_ref() {- "--output" | "-o" | "--compact" | "--account" | "--user" | "--agent-id" => {+ "--output" | "-o" | "--compact" | "--account" | "--user" => {i += 2;}"--sudo" | "--progress" | "--no-progress" | "--verbose" | "-v" => {@@ -1270,7 +1265,6 @@ fn consumes_plain_help_value(token: &str) -> bool {| "--compact"| "--account"| "--user"- | "--agent-id"| "-u"| "--uri"| "-x"@@ -1309,7 +1303,6 @@ fn consumes_plain_help_value(token: &str) -> bool {|| token.starts_with("--compact=")|| token.starts_with("--account=")|| token.starts_with("--user=")- || token.starts_with("--agent-id=")|| token.starts_with("--uri=")|| token.starts_with("--exclude-uri=")|| token.starts_with("--to=")@@ -1571,7 +1564,6 @@ fn is_admin_subcommand(token: &str) -> bool {| "delete-account"| "register-user"| "list-users"- | "list-agents"| "remove-user"| "set-role"| "regenerate-key"@@ -1788,7 +1780,7 @@ fn first_command_token(args: &[OsString]) -> Option<String> {}fn global_option_takes_value(option: &str) -> bool {- matches!(option, "--output" | "--account" | "--user" | "--agent-id")+ matches!(option, "--output" | "--account" | "--user")}fn global_short_option_takes_value(option: &str) -> bool {@@ -1958,7 +1950,6 @@ async fn main() {compact,cli.account.clone(),cli.user.clone(),- cli.agent_id.clone(),cli.sudo,None,None,@@ -2267,9 +2258,12 @@ async fn main() {after,before,level,+ peer_id,} => {- handlers::handle_find(query, uri, node_limit, threshold, after, before, level, ctx)- .await+ handlers::handle_find(+ query, uri, node_limit, threshold, after, before, level, peer_id, ctx,+ )+ .await}Commands::Search {query,@@ -2280,9 +2274,10 @@ async fn main() {after,before,level,+ peer_id,} => {handlers::handle_search(- query, uri, session_id, node_limit, threshold, after, before, level, ctx,+ query, uri, session_id, node_limit, threshold, after, before, level, peer_id, ctx,).await}@@ -2343,21 +2338,38 @@ mod tests {#[test]fn cli_parses_global_identity_override_flags() {- let cli = Cli::try_parse_from([- "ov",- "--account",- "acme",- "--user",- "alice",- "--agent-id",- "assistant-1",- "ls",- ])- .expect("cli should parse");+ let cli = Cli::try_parse_from(["ov", "--account", "acme", "--user", "alice", "ls"])+ .expect("cli should parse");assert_eq!(cli.account.as_deref(), Some("acme"));assert_eq!(cli.user.as_deref(), Some("alice"));- assert_eq!(cli.agent_id.as_deref(), Some("assistant-1"));+ }++ #[test]+ fn cli_parses_find_peer_id() {+ let cli = Cli::try_parse_from(["ov", "find", "invoice", "--peer-id", "web:visitor:alice"])+ .expect("find peer id should parse");++ match cli.command {+ Commands::Find { peer_id, .. } => {+ assert_eq!(peer_id.as_deref(), Some("web:visitor:alice"));+ }+ _ => panic!("expected find command"),+ }+ }++ #[test]+ fn cli_parses_search_peer_id() {+ let cli =+ Cli::try_parse_from(["ov", "search", "invoice", "--peer-id", "web:visitor:alice"])+ .expect("search peer id should parse");++ match cli.command {+ Commands::Search { peer_id, .. } => {+ assert_eq!(peer_id.as_deref(), Some("web:visitor:alice"));+ }+ _ => panic!("expected search command"),+ }}#[test]@@ -2560,7 +2572,6 @@ mod tests {&["ov", "admin", "delete-account"],&["ov", "admin", "register-user"],&["ov", "admin", "list-users"],- &["ov", "admin", "list-agents"],&["ov", "admin", "remove-user"],&["ov", "admin", "set-role"],&["ov", "admin", "regenerate-key"],@@ -2998,7 +3009,6 @@ mod tests {root_api_key: None,account: Some("from-config-account".to_string()),user: Some("from-config-user".to_string()),- agent_id: Some("from-config-agent".to_string()),timeout: 60.0,output: "table".to_string(),echo_command: true,@@ -3015,7 +3025,6 @@ mod tests {true,Some("from-cli-account".to_string()),Some("from-cli-user".to_string()),- Some("from-cli-agent".to_string()),false,None,None,@@ -3024,7 +3033,6 @@ mod tests {assert_eq!(ctx.config.account.as_deref(), Some("from-cli-account"));assert_eq!(ctx.config.user.as_deref(), Some("from-cli-user"));- assert_eq!(ctx.config.agent_id.as_deref(), Some("from-cli-agent"));}#[test]@@ -3035,7 +3043,6 @@ mod tests {root_api_key: Some("root-key".to_string()),account: None,user: None,- agent_id: None,timeout: 60.0,output: "table".to_string(),echo_command: true,@@ -3053,7 +3060,6 @@ mod tests {true,None,None,- None,false,None,None,@@ -3069,7 +3075,6 @@ mod tests {true,None,None,- None,true,None,None,diff --git a/crates/ov_cli/src/tui/app.rs b/crates/ov_cli/src/tui/app.rsindex 25d1d72b1..5b6de11fb 100644--- a/crates/ov_cli/src/tui/app.rs+++ b/crates/ov_cli/src/tui/app.rs@@ -524,19 +524,19 @@ impl App {/// Reload the entire tree and restore stateasync fn reload_tree_and_restore_state(&mut self, client: &HttpClient, expanded_nodes: &[String], target_uri: &str) {self.tree.load_root(client, "viking://").await;-+// Restore expanded state for previously expanded nodesfor uri in expanded_nodes {self.tree.expand_node_by_uri(client, uri).await;}-+// Ensure parent directories of target URI are expandedself.ensure_parent_directories_expanded(client, target_uri).await;-+// Find and set cursor to target URIlet cursor = self.find_cursor_for_uri(target_uri);self.tree.cursor = cursor;-+// Load content for selected nodeself.load_content_for_selected().await;}@@ -546,13 +546,13 @@ impl App {let selected_node = self.tree.selected_uri().map(|uri| uri.to_string()).unwrap_or_else(|| "viking://".to_string());-+// Collect expanded nodes before refreshlet expanded_nodes = self.collect_expanded_nodes();-+// Reload tree and restore stateself.reload_tree_and_restore_state(&client, &expanded_nodes, &selected_node).await;-+self.set_status_message("Tree refreshed".to_string());}diff --git a/crates/ov_cli/src/tui/event.rs b/crates/ov_cli/src/tui/event.rsindex ac6dff1ca..a80352bb1 100644--- a/crates/ov_cli/src/tui/event.rs+++ b/crates/ov_cli/src/tui/event.rs@@ -43,7 +43,7 @@ pub async fn handle_key(app: &mut App, key: KeyEvent) {}return;}-+match key.code {KeyCode::Char('q') => {app.should_quit = true;diff --git a/crates/ov_cli/src/tui/tree.rs b/crates/ov_cli/src/tui/tree.rsindex 710d989fd..c9ce900a5 100644--- a/crates/ov_cli/src/tui/tree.rs+++ b/crates/ov_cli/src/tui/tree.rs@@ -290,7 +290,7 @@ impl TreeState {self.scroll_offset = self.cursor - viewport_height + 1;}}-+/// Expand a node by its URIpub async fn expand_node_by_uri(&mut self, client: &HttpClient, uri: &str) {// Find the node in visible rows@@ -316,7 +316,7 @@ impl TreeState {}}}-+pub fn allow_deletion(&self, selected_uri: &str) -> bool {selected_uri != "/" && !Self::ROOT_SCOPES.iter().any(|s| selected_uri == format!("viking://{}", s))}diff --git a/crates/ov_cli/src/tui/ui.rs b/crates/ov_cli/src/tui/ui.rsindex 0851a114d..863a09973 100644--- a/crates/ov_cli/src/tui/ui.rs+++ b/crates/ov_cli/src/tui/ui.rs@@ -365,14 +365,14 @@ fn render_status_bar(frame: &mut Frame, app: &App, area: ratatui::layout::Rect)hints.extend_from_slice(&[Span::styled(- "d",+ "d",Style::default().fg(Color::Yellow)- .add_modifier(Modifier::BOLD)),+ .add_modifier(Modifier::BOLD)),Span::raw(":delete "),Span::styled(- "r",+ "r",Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)),diff --git a/crates/ragfs/src/plugins/queuefs/backend.rs b/crates/ragfs/src/plugins/queuefs/backend.rsindex f22693016..49568bcbe 100644--- a/crates/ragfs/src/plugins/queuefs/backend.rs+++ b/crates/ragfs/src/plugins/queuefs/backend.rs@@ -925,7 +925,7 @@ mod tests {params!["Semantic","legacy-msg-id",- r#"{"id":"legacy-msg-id","data":"{\"id\":\"semantic-inner\",\"uri\":\"viking://resources/demo\",\"context_type\":\"resource\",\"status\":\"pending\",\"timestamp\":1776411350,\"recursive\":true,\"account_id\":\"default\",\"user_id\":\"default\",\"agent_id\":\"default\",\"role\":\"root\",\"skip_vectorization\":false,\"telemetry_id\":\"tm_demo\",\"target_uri\":null,\"lifecycle_lock_handle_id\":\"lock-demo\",\"is_code_repo\":false,\"changes\":null}","timestamp":"2026-04-17T15:37:39.287855+08:00"}"#,+ r#"{"id":"legacy-msg-id","data":"{\"id\":\"semantic-inner\",\"uri\":\"viking://resources/demo\",\"context_type\":\"resource\",\"status\":\"pending\",\"timestamp\":1776411350,\"recursive\":true,\"account_id\":\"default\",\"user_id\":\"default\",\"peer_id\":\"default\",\"role\":\"root\",\"skip_vectorization\":false,\"telemetry_id\":\"tm_demo\",\"target_uri\":null,\"lifecycle_lock_handle_id\":\"lock-demo\",\"is_code_repo\":false,\"changes\":null}","timestamp":"2026-04-17T15:37:39.287855+08:00"}"#,1776411459_i64,],)diff --git a/docs/design/account-namespace-shared-session-design.md b/docs/design/account-namespace-shared-session-design.mddeleted file mode 100644index 64d81cc24..000000000--- a/docs/design/account-namespace-shared-session-design.md+++ /dev/null@@ -1,1004 +0,0 @@-# Account 级 User / Agent 命名空间策略与共享 Session 设计方案--## Context--当前 OpenViking 已具备 `account_id / user_id / agent_id` 三元身份模型,但 `user` 与 `agent` 的关系语义仍然不够明确,`session`、目录和检索对这层关系的表达也不一致,主要问题有:--- 系统内缺少 account 级显式策略来定义 `user scope` 是否再按 `agent` 切分、`agent scope` 是否再按 `user` 切分-- 命名空间决策分散在多处,目录拓扑无法直接体现 `user` / `agent` 关系-- `session` 仍然偏向单 user 视角,不能准确表达一个 account 内多 user / 多 agent 协同场景中的真实参与者身份-- 检索、目录遍历、向量索引、消息身份模型之间缺少一套统一的 owner / participant 语义--本次方案的目标,是把 `user` / `agent` 关系显式提升为 account 级命名空间策略,并为后续混合参与者 session 的提取、审计和协同能力打基础。-------## 决策摘要--- account 级新增两项配置:- - `isolate_user_scope_by_agent: bool`- - `isolate_agent_scope_by_user: bool`-- 默认值:- - `isolate_user_scope_by_agent = false`- - `isolate_agent_scope_by_user = false`-- `user` 与 `agent` 目录都采用显式嵌套 canonical URI,不再依赖 hash space。-- `session` 升级为 account 级共享作用域,统一落在:- - `viking://session/{session_id}`-- `session add-message` 新增 `role_id`:- - `role=user` 时绑定真实 `user_id`- - `role=assistant` 时绑定真实 `agent_id`-- 检索与目录可见性统一基于以下信息:- - `account_id`- - `uri`- - `owner_user_id`- - `owner_agent_id`-- 本方案按不兼容改造设计:- - 不做旧命名空间兼容- - 不做历史数据迁移- - 不做 mixed session `commit / extract` 分流-------## 一、目标与非目标--### 1.1 目标--- 引入 account 级配置,显式定义 `user` 和 `agent` 的共享边界-- 统一 `user / agent / session` 的逻辑 URI 与底层目录拓扑-- 将 `session` 升级为 account 级共享会话-- 在 `session add-message` 中显式记录消息归属身份-- 统一文件系统可见性与检索过滤规则,避免“能搜到但不能读”--### 1.2 非目标--- 本次不实现历史数据迁移-- 本次不实现双读双写兼容-- 本次不定义混合参与者 session 的 `commit / extract` 分流算法-- 本次不引入 participant 级 ACL,只提供 account 级共享 session-------## 二、核心设计决策--### 2.1 account 级配置字段--推荐字段名:--- `isolate_user_scope_by_agent: bool`-- `isolate_agent_scope_by_user: bool`--语义如下:--- `isolate_user_scope_by_agent = false`- - `user` 作用域只按 `user_id` 分区-- `isolate_user_scope_by_agent = true`- - `user` 作用域按 `(user_id, agent_id)` 分区-- `isolate_agent_scope_by_user = false`- - `agent` 作用域只按 `agent_id` 分区-- `isolate_agent_scope_by_user = true`- - `agent` 作用域按 `(agent_id, user_id)` 分区--默认值:--- `isolate_user_scope_by_agent = false`-- `isolate_agent_scope_by_user = false`--这个默认值的含义是:--- `user` 记忆按 user 隔离,不区分 agent-- `agent` 记忆按 agent 隔离,不区分 user--采用这个默认值的原因是:--- 大多数产品里,用户画像、偏好、个人事实更自然地跟 `user` 绑定,应该能跨 agent 复用-- 很多 agent 在系统内更像“共享能力单元”而不是“每个 user 一份的私有副本”,默认跨 user 共享更符合直觉-- 把两者都默认设为“不额外切分”,可以让目录语义最直接,减少初期理解和使用成本--### 2.2 配置方式与生命周期--这两个字段在 account 创建时配置,并跟随 account 生命周期持久化。--持久化位置:--- `/local/{account_id}/_system/setting.json`--示例:--```json-{- "namespace": {- "isolate_user_scope_by_agent": false,- "isolate_agent_scope_by_user": false- }-}-```--配置入口:--- `POST /api/v1/admin/accounts`--请求示例:--```json-{- "account_id": "acme",- "admin_user_id": "alice",- "isolate_user_scope_by_agent": false,- "isolate_agent_scope_by_user": false-}-```--如果请求里省略这两个字段,则服务端按默认值补齐:--```json-{- "isolate_user_scope_by_agent": false,- "isolate_agent_scope_by_user": false-}-```--读取入口:--- `GET /api/v1/admin/accounts`-- `GET /api/v1/admin/accounts/{account_id}`(如果后续补充单 account 查询接口)--持久化要求:--- account 创建时,服务端将这两个字段写入 `/{account_id}/_system/setting.json` 的 `namespace` 节点-- 服务启动后加载 account 配置时,这两个字段进入 `AccountNamespacePolicy`-- 后续所有 URI 解析、目录初始化、检索过滤、session 可见性都只能读取这一个来源--修改策略:--- 本阶段不提供 account policy 更新接口-- account 创建完成后,这两个字段视为不可变-- 不支持通过手工修改 `setting.json` 的方式在线切换 policy--原因:--- 修改任一字段都会改变 canonical URI 结构-- 已有目录路径、索引字段、session 派生引用都会跟着变化-- 在没有迁移工具、校验工具和回滚策略之前,不应支持在线修改--如果后续业务确实需要调整:--- 方案一:新建 account,按新 policy 初始化,再做数据迁移-- 方案二:单独立项做离线迁移,不通过常规 admin API 在线修改--### 2.3 配置生效层级--这两个字段只在 `account` 上定义,不在 `user`、`agent`、`session` 或请求级覆盖。--原因:--- 命名空间拓扑属于 account 级存储契约,不适合在请求级动态切换-- 一旦允许运行时切换,就会导致同一 account 内路径布局和检索过滤规则不稳定-- 统一到 account 级后,目录、索引、权限判断才能保持一致-------## 三、命名空间模型--### 3.1 总体原则--- 逻辑 URI 采用显式嵌套路径,不再依赖不可读的 hash space-- `user`、`agent`、`session` 都有 canonical URI-- 简写 URI 可以保留,但内部必须先 canonicalize,再进入存储、检索和权限判断--### 3.2 四种拓扑矩阵--#### `isolate_user_scope_by_agent=false`,`isolate_agent_scope_by_user=false`--```text-viking://user/{user_id}/...-viking://agent/{agent_id}/...-viking://session/{session_id}/...-```--底层目录:--```text-/local/{account_id}/user/{user_id}/...-/local/{account_id}/agent/{agent_id}/...-/local/{account_id}/session/{session_id}/...-```--访问规则:--- 当前请求身份为 `(user_id=ua, agent_id=aa)` 时,可以访问 `viking://user/ua/...` 下的全部 user 数据,不受当前 agent 影响-- 当前请求身份为 `(user_id=ua, agent_id=aa)` 时,可以访问 `viking://agent/aa/...` 下的全部 agent 数据,不受当前 user 影响-- 不能访问其他 user 的 `viking://user/{other_user_id}/...`-- 不能访问其他 agent 的 `viking://agent/{other_agent_id}/...`-- `session` 按 account 共享,访问规则独立于这两个字段--适用场景:--- 一个 account 内多个 user 共同使用一组标准化 agent,且 agent 的技能、案例、工作区都希望在团队内共享-- 用户侧资料也希望跨 agent 复用,例如统一的用户画像、偏好、长期事实-- 更适合协作型工作区,而不是强隔离场景--#### `isolate_user_scope_by_agent=false`,`isolate_agent_scope_by_user=true`--```text-viking://user/{user_id}/...-viking://agent/{agent_id}/user/{user_id}/...-viking://session/{session_id}/...-```--底层目录:--```text-/local/{account_id}/user/{user_id}/...-/local/{account_id}/agent/{agent_id}/user/{user_id}/...-/local/{account_id}/session/{session_id}/...-```--访问规则:--- 当前请求身份为 `(user_id=ua, agent_id=aa)` 时,可以访问 `viking://user/ua/...` 下的全部 user 数据,不受当前 agent 影响-- 当前请求身份为 `(user_id=ua, agent_id=aa)` 时,只能访问 `viking://agent/aa/user/ua/...`-- 不能访问 `viking://agent/aa/user/{other_user_id}/...`-- 不能访问 `viking://agent/{other_agent_id}/user/ua/...`-- `session` 按 account 共享,访问规则独立于这两个字段--适用场景:--- 同一个 user 会在多个 agent 之间切换,希望个人资料和长期偏好能直接复用-- 不同 user 虽然可能使用同名 agent,但 agent 的案例、instructions、技能配置等沉淀需要彼此隔离-- 适合希望保留 user 侧共享,但对 agent 侧共享更谨慎的部署方式--#### `isolate_user_scope_by_agent=true`,`isolate_agent_scope_by_user=false`--```text-viking://user/{user_id}/agent/{agent_id}/...-viking://agent/{agent_id}/...-viking://session/{session_id}/...-```--底层目录:--```text-/local/{account_id}/user/{user_id}/agent/{agent_id}/...-/local/{account_id}/agent/{agent_id}/...-/local/{account_id}/session/{session_id}/...-```--访问规则:--- 当前请求身份为 `(user_id=ua, agent_id=aa)` 时,只能访问 `viking://user/ua/agent/aa/...`-- 不能访问 `viking://user/ua/agent/{other_agent_id}/...`-- 当前请求身份为 `(user_id=ua, agent_id=aa)` 时,可以访问 `viking://agent/aa/...` 下的全部 agent 数据,不受当前 user 影响-- 不能访问其他 agent 的 `viking://agent/{other_agent_id}/...`-- `session` 按 account 共享,访问规则独立于这两个字段--适用场景:--- agent 本身代表某种共享岗位能力或团队能力,希望其案例、技能、instructions 等沉淀在所有 user 之间复用-- 但同一个 user 在不同 agent 下的个人资料或用户记忆不希望互通-- 适合“agent 是主实体,user 只是调用者”的平台型场景--#### `isolate_user_scope_by_agent=true`,`isolate_agent_scope_by_user=true`--```text-viking://user/{user_id}/agent/{agent_id}/...-viking://agent/{agent_id}/user/{user_id}/...-viking://session/{session_id}/...-```--底层目录:--```text-/local/{account_id}/user/{user_id}/agent/{agent_id}/...-/local/{account_id}/agent/{agent_id}/user/{user_id}/...-/local/{account_id}/session/{session_id}/...-```--访问规则:--- 当前请求身份为 `(user_id=ua, agent_id=aa)` 时,只能访问 `viking://user/ua/agent/aa/...`-- 不能访问 `viking://user/ua/agent/{other_agent_id}/...`-- 当前请求身份为 `(user_id=ua, agent_id=aa)` 时,只能访问 `viking://agent/aa/user/ua/...`-- 不能访问 `viking://agent/aa/user/{other_user_id}/...`-- 不能访问 `viking://agent/{other_agent_id}/user/ua/...`-- `session` 按 account 共享,访问规则独立于这两个字段--适用场景:--- 每个 `(user, agent)` 组合都应视为独立工作单元,不能共享任何用户记忆或 agent 沉淀-- 强合规、强审计、强租户内隔离场景-- 适合外包、敏感业务、或需要最小共享面的部署方式--### 3.3 scope 内部结构--#### user scope--```text-memories/- preferences/- entities/- events/-profile.md-```--#### agent scope--```text-memories/- cases/- patterns/-skills/-instructions/-```--#### session scope--```text-messages.jsonl-history/-tools/-.meta.json-```--### 3.4 简写 URI 规则--保留如下简写:--- `viking://user/...`-- `viking://agent/...`--但内部一律按当前 account policy 和请求身份展开为 canonical URI。--示例:当前身份为 `(account=acme, user=ua, agent=aa)`--当 `isolate_user_scope_by_agent=false` 时:--```text-viking://user/memories/preferences/-=> viking://user/ua/memories/preferences/-```--当 `isolate_user_scope_by_agent=true` 时:--```text-viking://user/memories/preferences/-=> viking://user/ua/agent/aa/memories/preferences/-```--当 `isolate_agent_scope_by_user=false` 时:--```text-viking://agent/memories/cases/-=> viking://agent/aa/memories/cases/-```--当 `isolate_agent_scope_by_user=true` 时:--```text-viking://agent/memories/cases/-=> viking://agent/aa/user/ua/memories/cases/-```--要求:--- 存储层只处理 canonical URI-- 向量索引写入只处理 canonical URI-- 权限判断只处理 canonical URI-------## 四、Session 模型重构--### 4.1 Session 作用域调整--将 `session` 从 user 目录下移出,统一为 account 级共享:--```text-viking://session/{session_id}-```--底层目录:--```text-/local/{account_id}/session/{session_id}-```--设计原因:--- 同一 account 内可能有多个 user / agent 共同参与一个会话-- 把 session 绑定在某个 user 根目录下,会让会话共享变得别扭-- session 作为临时协作容器,更适合按 account 共享,再通过消息身份描述参与者--### 4.2 Session 可见性与权限--推荐权限:--- `create / list / get / add-message / commit`- - 同 account 内可访问-- `delete`- - 仅 `ADMIN`- - 或 `ROOT`--这意味着:--- session 可被 account 内其他 user 看到和继续使用-- 删除权限单独收紧,避免 shared session 的“所有者”语义不清--### 4.3 Session 元数据--`session/.meta.json` 新增字段:--- `created_by_user_id`-- `participant_user_ids`-- `participant_agent_ids`--说明:--- `created_by_user_id` 表示“这个 session 最初是由哪个请求身份创建出来的”-- 写入时机:- - 第一次真正创建 session 时写入 `.meta.json`- - 具体包括 `POST /api/v1/sessions` 创建- - 以及未来如果保留 `auto_create` 语义,则第一次自动创建时也写入-- 写入来源:- - 直接取创建请求对应的 `RequestContext.user.user_id`- - 也就是发起这次创建操作的请求用户-- 一旦写入,不再随着后续 `add-message` 的 `role_id` 变化而变化-- 它是审计字段,不直接参与删除权限判断-- `participant_*` 只用于索引、展示、后续提取分流,不承担 ACL--也就是说:--- `created_by_user_id` 不是客户端额外传的参数-- 它是服务端在“创建 session 的那一刻”从当前登录身份里自动记下来的-- 它和消息里的 `role_id` 不是一回事- - `created_by_user_id` 解决“这个 session 最初由谁创建”- - `role_id` 解决“这条消息是谁说的”-------### 4.4 `add-message` 接口扩展--在 `POST /api/v1/sessions/{session_id}/messages` 中新增 `role_id`。--示例:--```json-{- "role": "user",- "role_id": "ua",- "content": "你好"-}-```--```json-{- "role": "assistant",- "role_id": "aa",- "parts": [...]-}-```--规则:--- `role == "user"` 时,`role_id` 表示真实 `user_id`-- `role == "assistant"` 时,`role_id` 表示真实 `agent_id`-- 其他 role 暂不使用 `role_id`--### 4.5 请求头语义与 `RequestContext` 解析--服务端需要区分“真实调用者身份”和“本次请求按谁的视角执行”。--在不同认证模式下,`X-OpenViking-Account`、`X-OpenViking-User`、`X-OpenViking-Agent` 的语义如下:--- `trusted` 模式- - `X-OpenViking-Account / User / Agent` 表示真实调用者身份- - 此时不存在模拟其他用户身份的语义--- `api_key + ROOT`- - `X-OpenViking-Account / User / Agent` 表示本次请求的生效上下文- - `ROOT` 可以显式指定本次请求作用到哪个 account / user / agent--- `api_key + ADMIN`- - `X-OpenViking-User / Agent` 表示本次请求的生效 user / agent 上下文- - `ADMIN` 只能在自己的 account 内使用这组请求头模拟用户视角- - `ADMIN` 不允许通过 `X-OpenViking-Account` 切换到其他 account--- `api_key + USER`- - `user_id` 只能从当前 user key 对应的身份解析- - `X-OpenViking-Agent` 仍可用于指定当前请求的 agent 上下文- - `USER` 不允许通过 `X-OpenViking-User` 切换到其他 user--`RequestContext` 的语义统一为:--- `ctx.user` 表示本次请求的生效身份-- `ctx.role` 表示真实调用者角色-- namespace 解析、检索过滤、文件系统可见性都按 `ctx.user` 执行-- 管理权限按 `ctx.role` 判断--### 4.6 `add-message` 校验与默认填充--`role_id` 的语义如下:--- `role = "user"` 时,`role_id` 表示消息所属的 `user_id`-- `role = "assistant"` 时,`role_id` 表示消息所属的 `agent_id`--校验与填充规则:--- `trusted`、`ROOT`、`ADMIN`- - 可以显式传入 `role_id`- - 如果未显式传入:- - `role = "user"` 时,默认填充 `ctx.user.user_id`- - `role = "assistant"` 时,默认填充 `ctx.user.agent_id`--- `USER`- - 可以显式传入 `role_id`,服务端以传入值为准- - 如果未显式传入:- - `role = "user"` 时,默认填充 `ctx.user.user_id`- - `role = "assistant"` 时,默认填充 `ctx.user.agent_id`--额外约束:--- `role = "user"` 时,`role_id` 语义表示消息所属的 `user_id`,由调用方保证为当前 account 下合法的 `user_id`-- `role = "assistant"` 时,`role_id` 作为 `agent_id` 使用-- 本阶段不引入独立的 agent registry;服务端不对 `role_id` 做格式或上下文一致性校验,语义一致性由调用方承担--### 4.7 消息持久化结构--`Message` 增加字段:--```json-{- "id": "msg_xxx",- "role": "assistant",- "role_id": "aa",- "parts": [...],- "created_at": "2026-04-09T10:00:00Z"-}-```--`role_id` 表示这条消息的 actor 身份,不等于真实调用者身份。后续从消息派生 tool / skill / memory 归属时,应以消息自身的 `role + role_id` 为准。--### 4.8 Session 派生 URI--`tool_uri` 统一调整为:--```text-viking://session/{session_id}/tools/{tool_id}-```--后续凡是从 message 中派生 tool / skill / memory 归属时,都应优先使用消息上的 `role + role_id`,而不是默认使用当前请求上下文里的 agent / user。--------## 五、检索、文件系统与可见性--### 5.1 问题--当前很多逻辑依赖单一字符串字段 `owner_space`。这个字段在以下场景下不够稳定:--- 命名空间拓扑有四种组合-- session 改成 account 共享后,不能再把 session 误归到 user owner-- user/agent 简写 URI 需要展开-- 仅靠一个字符串,不方便做结构化可见性判断--### 5.2 索引中的归属信息--向量索引和 `Context` 的归属字段调整为:--- 保留已有字段:- - `account_id`- - `uri`-- 新增字段:- - `owner_user_id`- - `owner_agent_id`-- 移除字段:- - `owner_scope`--其中:--- `uri` 使用标准路径-- `scope` 从 `uri` 的前缀解析得到,不单独存 `owner_scope`-- `owner_user_id` / `owner_agent_id` 用来表达这条数据绑定到哪个 user / agent-- `uri` 和 `owner_user_id` / `owner_agent_id` 需要保持一致,不能互相冲突--### 5.3 写入规则--所有写入到索引的数据,都必须先确定标准 URI,再由标准 URI 生成 `owner_user_id` / `owner_agent_id`。--写入时规则如下:--#### resource--```text-uri = viking://resources/...-owner_user_id = null-owner_agent_id = null-```--#### user scope--```text-uri = viking://user/{user_id}/... if isolate_user_scope_by_agent = false-uri = viking://user/{user_id}/agent/{agent_id}/... if isolate_user_scope_by_agent = true--owner_user_id = user_id-owner_agent_id = null if isolate_user_scope_by_agent = false-owner_agent_id = agent_id if isolate_user_scope_by_agent = true-```--#### agent scope--```text-uri = viking://agent/{agent_id}/... if isolate_agent_scope_by_user = false-uri = viking://agent/{agent_id}/user/{user_id}/... if isolate_agent_scope_by_user = true--owner_agent_id = agent_id-owner_user_id = null if isolate_agent_scope_by_user = false-owner_user_id = user_id if isolate_agent_scope_by_user = true-```--#### session--```text-uri = viking://session/{session_id}/...-owner_user_id = null-owner_agent_id = null-```--### 5.4 查询过滤规则--检索时先加:--```text-account_id == ctx.account_id-```--然后根据当前 `(user_id, agent_id)` 和 account policy,算出本次请求可见的路径根:--#### resource 根路径--```text-viking://resources/-```--#### session 根路径--```text-viking://session/-```--#### user 根路径--```text-viking://user/{user_id}/... if isolate_user_scope_by_agent = false-viking://user/{user_id}/agent/{agent_id}/... if isolate_user_scope_by_agent = true-```--#### agent 根路径--```text-viking://agent/{agent_id}/... if isolate_agent_scope_by_user = false-viking://agent/{agent_id}/user/{user_id}/... if isolate_agent_scope_by_user = true-```--检索过滤由两部分组成:--- `account_id == ctx.account_id`-- `uri` 必须落在上述可见根路径下-- `owner_user_id` / `owner_agent_id` 必须满足当前 policy 对应的可见范围--如果请求显式传了 `target_uri`,则:--- 先把 `target_uri` 归一化成标准路径-- 校验该 `target_uri` 是否在当前请求可见范围内-- 再把检索范围收敛到该 `target_uri` 前缀下--说明:--- session 在本方案中按 account 共享,因此统一落在 `viking://session/`-- `uri` 用来表达真实路径范围-- `owner_user_id` / `owner_agent_id` 用来表达绑定到哪个 user / agent-- 文件系统可见性与检索过滤必须复用同一套判断规则--### 5.5 结果校验与错误处理--检索返回后,服务端仍需对命中结果做一次基于 `uri + owner_user_id + owner_agent_id` 的一致性校验,避免索引脏数据或历史遗留数据泄漏。--错误处理如下:--- `target_uri` 路径形状和当前 policy 不匹配:返回 `400`-- `target_uri` 本身形状没问题,但当前身份无权访问:返回 `403`-- 不传 `target_uri` 时,按当前身份可见范围做全局检索-------### 5.6 文件系统与目录初始化--#### VikingFS--需要引入统一的 namespace resolver,承担以下职责:--- 根据 account policy + 当前身份生成 canonical user / agent 根路径-- 将简写 URI canonicalize-- 解析 URI 对应的 owner 结构-- 判断路径是否对当前 `(account_id, user_id, agent_id)` 可见--`VikingFS` 的以下能力都需要切到新规则:--- `_uri_to_path`-- `_path_to_uri`-- `_is_accessible`-- `ls / tree / stat / read / write`--#### DirectoryInitializer--目录初始化要区分两类节点:--- 真实作用域根- - 需要生成 `memories / skills / instructions` 等预置结构-- 中间容器目录- - 只承担路径承载作用- - 不重复写入预置抽象与 overview--例如在 `isolate_user_scope_by_agent=true` 且 `isolate_agent_scope_by_user=true` 下:--```text-viking://agent/{agent_id}-```--只是容器;--```text-viking://agent/{agent_id}/user/{user_id}-```--才是实际的 agent scope 根。-------## 六、接口与类型变更--### 6.1 Admin API--`POST /api/v1/admin/accounts` 新增:--- `isolate_user_scope_by_agent`-- `isolate_agent_scope_by_user`--`GET /api/v1/admin/accounts` 返回同样两项配置。--account 级 namespace policy 持久化在:--- `/local/{account_id}/_system/setting.json`--文件示例:--```json-{- "namespace": {- "isolate_user_scope_by_agent": false,- "isolate_agent_scope_by_user": false- }-}-```--如果创建请求未显式传值,则服务端使用默认值:--- `isolate_user_scope_by_agent = false`-- `isolate_agent_scope_by_user = false`--本阶段不提供修改 account policy 的更新接口。--原因:--- 修改 policy 本质上是重排目录和索引-- 没有迁移机制前,不应允许运行时修改-- 直接手工修改 `setting.json` 也不在支持范围内--### 6.2 核心类型--需要扩展:--- `AccountInfo`-- `ResolvedIdentity`-- `RequestContext`-- `Message`-- `SessionMeta`-- `Context`--## 七、影响模块--本次方案预计影响如下模块族:--- 多租户与认证- - account 配置读写- - auth middleware- - request context-- 命名空间解析- - `UserIdentifier`- - 新增统一 resolver / policy-- 文件系统- - `VikingFS`- - `DirectoryInitializer`-- session- - `Session`- - `SessionService`- - `sessions router`- - `Message`-- 检索与向量- - `Context`- - embedding message converter- - semantic processor- - collection schema- - vector backend filter-- 接入层- - Python SDK- - HTTP client- - Rust CLI-------## 八、兼容性策略--本次不采用“全量兼容”或“双读双写”策略,而是按 scope 分别处理:--### 8.1 user scope--- `user` 侧默认路径本身就是 `viking://user/{user_id}/...`-- 如果新拓扑仍然采用 user 共享形态,则 AGFS 路径天然兼容-- 因此本阶段不对 `user` 侧做目录迁移--### 8.2 session scope--- `session` 只在 AGFS 中维护,不进入 VectorDB-- 在确认 account 内不存在同名 `session_id` 的前提下,session 迁移按纯目录移动处理:--```text-viking://session/{user_id}/{session_id}--> viking://session/{session_id}-```--- 本阶段不保留旧 session 根路径兼容读-- 迁移完成后,session 的 list / get / delete / add-message / commit 全部只认新路径--### 8.3 agent scope--- 本次不支持旧 agent 数据自动迁移到新命名空间-- 不保留旧 hash namespace 的兼容访问-- 不继续让 `memory.agent_scope_mode` 参与服务端命名空间决策-- 如需保留旧 agent 数据,可在升级前自行使用现有 `ovpack` 做离线备份--推荐迁移方式:--- 升级前:在旧版本中从 legacy hash namespace 导出,例如:--```bash-ov export viking://agent/{legacy_agent_space_hash}/memories ./agent_memory.ovpack-```--- 升级后:在新版本中按目标 account policy 导入到 agent space 的父目录:--```bash-# isolate_agent_scope_by_user = false-ov import ./agent_memory.ovpack viking://agent/{agent_id}/ --force--# isolate_agent_scope_by_user = true-ov import ./agent_memory.ovpack viking://agent/{agent_id}/user/{user_id}/ --force-```--- 不要把 `.ovpack` 直接导入到 `.../memories/` 本身,否则会得到 `.../memories/memories/...`-- 当 `isolate_agent_scope_by_user = true` 时,`viking://agent/{agent_id}/user/` 不是合法目标;必须显式提供 `user_id}`--- 当前 agent root 是 hash space,而不是显式 `agent_id`-- hash 值不能从结果稳定反推出原始 `user_id / agent_id`-- 如果目标拓扑还涉及 agent 共享,会进一步引入多份旧数据合并问题--### 8.4 总体取舍--本次兼容策略总结如下:--- `user`:天然兼容,不迁-- `session`:直接 `mv`-- `agent`:不自动兼容,只提供 ovpack 导出--这个取舍的目的是把新命名空间模型尽快收敛为单一存储契约,而不是把 legacy hash 逻辑继续带入新实现。-------## 九、风险与边界--### 9.1 混合参与者 session 的提取策略尚未定义--当一个 session 同时包含多个 user 和多个 assistant 时,后续 `commit / extract` 如何分流到对应 user / agent 作用域,是独立问题。--本次只解决:--- 会话可以共享-- 每条消息的参与者身份可追踪-- 检索与目录可见性有稳定 owner 语义--### 9.2 session 共享不等于 participant ACL--本方案采用 account 级共享 session。也就是说,同 account 内用户都可以看见 session。--如果未来需要“仅参与者可见”的 session,需要额外引入 participant ACL 模型,这不在本次范围内。--### 9.3 拓扑切换不可在线修改--一旦 account 已有数据,切换 `isolate_user_scope_by_agent` 或 `isolate_agent_scope_by_user` 会导致:--- 目录 root 变化-- 索引字段变化-- 检索过滤条件变化--因此本阶段不支持在线修改。-------## 十、测试方案--### 10.1 account policy--- 创建 account 时两项配置写入成功-- list account 能返回两项配置-- 默认值为 `false / false`-- 四种组合可正确加载--### 10.2 namespace matrix--- `user` / `agent` canonical URI 生成正确-- 简写 URI 展开正确-- 四种拓扑下底层目录映射正确-- 中间容器目录与真实作用域根区分正确--### 10.3 session--- session 根路径为 `viking://session/{session_id}`-- session list 为 account 级-- `role_id` 校验正确-- `Message.role_id` 持久化正确-- `participant_user_ids` / `participant_agent_ids` 正确累积-- `ADMIN / ROOT` 删除权限正确--### 10.4 retrieval / visibility--- FS `ls / stat / read` 与检索结果一致-- user scope 在四种 policy 下可见性正确-- agent scope 在四种 policy 下可见性正确-- session scope 按 account 共享-- cross-account 不泄漏--### 10.5 negative cases--- 缺失 `role_id`-- 非法 nested URI-- policy 与路径不匹配-- 尝试访问非本 user / agent 可见作用域-------## 十一、推荐落地顺序--建议按以下顺序实施:--1. 引入 account policy 与统一 namespace resolver-2. 改造 `UserIdentifier`、`RequestContext`、Admin API-3. 改造 `VikingFS` 与目录初始化-4. 改造 `session` 路径与 `Message.role_id`-5. 改造 `Context`、embedding、vector schema 与过滤逻辑-6. 最后更新 SDK / CLI 与文档--这样可以先把“路径与身份语义”固定,再去改造检索与接入层,风险更可控。-------## 结论--本方案的核心是把 `user`、`agent` 的共享关系显式提升为 account 级策略,并将 `session` 升级为 account 级共享容器,再用 `role_id` 和标准 URI 把消息、目录和检索统一到同一套身份模型上。--如果接受这份方案,后续实现应严格遵守两条主线:--- 所有 URI 先 canonicalize,再进入存储、检索、权限判断-- 所有可见性与索引判断都基于 `account_id + uri + owner_user_id + owner_agent_id`--这两条一旦立住,后续 mixed session extraction、participant ACL、审计追踪才有稳定的基础。diff --git a/docs/design/memory-extractor-optimization.md b/docs/design/memory-extractor-optimization.mddeleted file mode 100644index d7f5d1749..000000000--- a/docs/design/memory-extractor-optimization.md+++ /dev/null@@ -1,1057 +0,0 @@-# Memory Extractor Templating and Update Mechanism Optimization / 记忆抽取模版与更新机制优化--## Context / 上下文--### Problem Background / 问题背景--- [#578](https://github.com/volcengine/OpenViking/issues/578) "[Feature]: 允许提示词模板自定义添加和指定" - Current OpenViking memory_extractor uses 8 fixed memory categories (profile, preferences, entities, events, cases, patterns, tools, skills), adding new memory types requires modifying multiple core code files, prompt templates and merge logic are hard-coded. This design implements the custom template capability requested in #578. / [#578](https://github.com/volcengine/OpenViking/issues/578) "[Feature]: 允许提示词模板自定义添加和指定" - 当前 OpenViking 的 memory_extractor 使用 8 个固定的记忆类别(profile, preferences, entities, events, cases, patterns, tools, skills),新增记忆类型需要修改多处核心代码,提示模板和合并逻辑都是硬编码的。本设计实现了 #578 中要求的自定义模板能力。-- User memory filenames use random ID encoding, not semantic, wasting the navigation value of filenames / 用户记忆文件名采用随机 ID 编码,没有语义化,浪费了文件名的导航价值-- After extraction, merging is still required, involving multiple LLM calls, low efficiency / 抽取之后还需要做合并,涉及多次 LLM 调用,效率较低--### Goals / 目标--Implement a memory templating system based on OpenViking storage, such that: / 实现基于 OpenViking 存储的记忆模版化系统,使得:-1. Design memory templating mechanism, can add new memory types without modifying core code / 设计记忆模版机制,无需修改核心代码即可添加新的记忆类型-2. Maintain backward compatibility (existing 8 categories continue to work) / 保持向后兼容(现有 8 个类别继续工作)-3. Adopt ReAct (Reasoning + Action) pattern for memory updates, update all memories in one ReAct-based LLM call / 采用 ReAct (Reasoning + Action) 模式进行记忆更新,一次基于 ReAct 的 LLM 调用更新所有记忆-4. Adopt semantic filenames, fully utilize the navigation value of filenames / 采用语义化文件名,充分利用文件名的导航价值-5. Learn from commercial memory library implementations, adopt patch incremental update mechanism (including abstract and overview), reduce LLM call count / 借鉴商业化记忆库的实现,采用 patch 增量更新机制(包括abstract和overview),减少 LLM 调用次数--### Reference Design / 参考设计--This design references the following core ideas from the `../memory` project: / 本设计参考了 `../memory` 项目的以下核心思想:-- Memory templating (OpenViking's memory template is a subset of the commercial version, preserving the possibility of future upgrade to commercial version) / 记忆模版化(openviking的记忆模版是商业化版本的一个子集,保留未来升级到商业化版本的可能性)-- Three-operation Schema (write/edit/delete) / 三种操作 Schema(write/edit/delete)-- RoocodePatch patch protocol (patch + replace) / RoocodePatch patch协议(patch + replace)-------## Two Memory Modes / 两种记忆模式--The system provides two memory modes, distinguished by whether `content_template` exists. / 系统提供两种记忆模式,用是否有 `content_template` 来区分。--### Simple Mode (without content_template) / 模式一:简单模式(无 content_template)--**Use Cases**: profile, preferences, entities, events, cases, patterns / 适用场景:profile、preferences、entities、events、cases、patterns--**Characteristics**: / 特点:-- Only `name`, `content` two fields (or a few simple fields) / 只有 `name`、`content` 两个字段(或简单的几个字段)-- `content` is Markdown content, no rendering needed / `content` 就是 Markdown 内容,不需要渲染-- No `MEMORY_FIELDS` comment needed / 不需要 `MEMORY_FIELDS` 注释-- Directly use patch to incrementally update content during updates / 更新时直接用 patch 增量更新 content--**Config Examples** / **配置示例**:--**profile.yaml**-```yaml-name: profile-description: |- User profile memory - captures "who the user is" as a person.- Extract relatively stable personal attributes that define the user's identity, work style, and preferences.- Include: profession, experience level, technical background, communication style, work habits, etc.- Do NOT include transient conversation content or temporary mood states.-directory: "viking://user/{user_space}/memories"-filename_template: "profile.md"--fields:- - name: content- type: string- description: |- User profile content describing "who the user is".- Includes relatively stable personal attributes: profession, experience, tech stack, communication style, etc.- Example: "User is an AI development engineer with 3 years of LLM application development experience, mainly using Python and LangChain tech stack. Communication style is concise and direct, prefers efficient code implementation."- merge_op: patch-```--**preferences.yaml**-```yaml-name: preferences-description: |- User preference memory - captures "what the user likes/dislikes or is accustomed to".- Extract specific preferences the user has expressed across conversations.- Each preference should be about a specific topic (not generic).- Topics can be: code style, communication style, tools, workflow, food, commute, etc.- Store different topics as separate memory files, do NOT mix unrelated preferences.-directory: "viking://user/{user_space}/memories/preferences"-filename_template: "{topic}.md"--fields:- - name: topic- type: string- description: |- Preference topic used to uniquely identify this preference memory.- Should be a semantic topic description such as "Python code style", "Communication style", "Food preference", "Commute preference", etc.- Different preference topics should be stored as separate memories, do not mix unrelated preferences.- merge_op: immutable-- - name: content- type: string- description: |- Specific preference content describing "what the user prefers/is accustomed to".- Example: "User has shown clear preferences for Python code style in multiple conversations: dislikes using type hints, considers them redundant; requires concise function comments, limited to 1-2 lines; prefers direct implementation, avoids excessive fallbacks and over-engineering."- merge_op: patch-```--**entities.yaml**-```yaml-name: entities-description: |- Entity memory - captures "what this named thing is, what properties it has".- Extract information about specific entities mentioned in conversation.- Entity types include: projects, people, organizations, systems, technologies, concepts, products, etc.- Each entity is a named thing that has attributes worth remembering for future conversations.- Store each entity as a separate memory file, keyed by entity name.-directory: "viking://user/{user_space}/memories/entities"-filename_template: "{entity_name}.md"--fields:- - name: entity_name- type: string- description: |- Entity name used to uniquely identify this entity memory.- Should be the specific name of the entity such as "OpenViking project", "Alice (colleague)", "Redis", etc.- merge_op: immutable-- - name: entity_type- type: string- description: |- Entity type describing what type of entity this is.- Possible values: project, person, organization, system, technology, concept, etc.-- - name: content- type: string- description: |- Detailed entity content describing "what this named thing is, what properties it has".- Includes: basic information, core attributes, status, etc.- Example: "OpenViking is an AI Agent long-term memory management system the user is developing. The project uses Python and AGFS tech stack, core features include memory extraction, deduplication, and retrieval. Currently in active development, goal is to build Claude-like long-term memory capabilities."- merge_op: patch-```--**events.yaml**-```yaml-name: events-description: |- Event memory - captures "what happened, what decision was made, and why".- Extract notable events, decisions, milestones, and turning points from the conversation.- Events should be things worth remembering for future context: decisions made, agreements reached, milestones achieved, problems solved, etc.- Each event should include: what happened, why it happened, what the outcome was, and any relevant context/timeline.- Use absolute dates for event_time, not relative time like "today" or "recently".-directory: "viking://user/{user_space}/memories/events"-filename_template: "{event_time}_{event_name}.md"--fields:- - name: event_name- type: string- description: |- Event name used to uniquely identify this event memory.- Should be a specific event description such as "Decided to refactor memory system", "Started OpenViking project", "Completed Q3 review", etc.- Example: "[Action]: [Description]"- merge_op: immutable-- - name: event_time- type: string- description: |- Time when the event occurred, use absolute time format, do not use relative time (such as "today", "recently").- Can be empty if time is unknown.- Example: "2026-03-17"- merge_op: immutable-- - name: content- type: string- description: |- Detailed event content describing "what happened".- Includes: decision content, reasons, results, background, timeline, etc.- Example: "During memory system design discussion, found that the original 6 categories had blurry boundaries. Especially states, lessons, insights often overlapped and were hard to distinguish. Decided to refactor to 5 categories, removing these three to make classification boundaries clearer."- merge_op: patch-```--**cases.yaml**-```yaml-name: cases-description: |- Case memory - captures "what problem was encountered and how it was solved".- Extract specific problem-solution pairs from the conversation that are worth remembering for future reference.- Cases should be about specific problems that have clear solutions.- Each case should include: what the problem was (symptoms, error messages, context), what the solution was (steps taken, principles used), and why it worked.- Case names should be in "Problem → Solution" format to make them easily searchable.-directory: "viking://agent/{agent_space}/memories/cases"-filename_template: "{case_name}.md"--fields:- - name: case_name- type: string- description: |- Case name used to uniquely identify this case memory.- Should be in "Problem → Solution" format such as "Band not recognized → Request member/album/style details", "Memory merge timeout → Split into smaller chunks", etc.- Example: "[Problem] → [Solution]"- merge_op: immutable-- - name: problem- type: string- description: |- Problem description specifically detailing what problem was encountered.- Includes: error messages, symptoms, context, and other specific details.- Example: "User feedback that a band cannot be recognized by system."- merge_op: patch-- - name: solution- type: string- description: |- Solution description detailing how to solve this problem.- Includes: solution method, steps, principles, etc.- Example: "Request user to provide more identification details: band member names, representative album names, music style, etc. This information can improve recognition accuracy."- merge_op: patch-- - name: content- type: string- description: |- Complete case content including full narrative of problem and solution.- Example: "User feedback mentioned a band that the system could not recognize. Solution is to request user to provide more identification details: band member names, representative album names, music style, etc. This information can improve recognition accuracy."- merge_op: patch-```--**patterns.yaml**-```yaml-name: patterns-description: |- Pattern memory - captures "under what circumstances to follow what process".- Extract reusable workflows, processes, and methods that the agent should follow in similar future situations.- Patterns should be about: how to approach certain types of tasks, what steps to follow, what considerations to keep in mind.- Each pattern should include: trigger conditions (when to use this pattern), process steps (what to do), and considerations (what to watch out for).- Pattern names should be in "Process name: Step description" format.-directory: "viking://agent/{agent_space}/memories/patterns"-filename_template: "{pattern_name}.md"--fields:- - name: pattern_name- type: string- description: |- Pattern name used to uniquely identify this pattern memory.- Should be in "Process name: Step description" format such as "Teaching topic handling: Outline→Plan→Generate PPT", "Code refactoring: Understand→Test→Refactor→Verify", etc.- Example: "[Pattern name]: [Step sequence]"- merge_op: immutable-- - name: pattern_type- type: string- description: |- Pattern type describing what type of pattern this is.- Possible values: workflow, method, process, etc.-- - name: content- type: string- description: |- Detailed pattern content describing "under what circumstances to follow what process".- Includes: trigger conditions, process steps, considerations, etc.- Example: "When user requests teaching content for a topic, use a four-step process: first list the topic outline to understand overall structure; then create a detailed learning plan; next generate PPT framework; finally refine specific content for each section. This process ensures content is systematic and complete."- merge_op: patch-```--**Memory File Storage Format Example** / **记忆文件存储格式示例**:-```markdown-# User Profile--User is an AI development engineer with 3 years of experience...-```-------### Template Mode (with content_template) / 模式二:模板模式(有 content_template)--**Use Cases**: tools, skills / 适用场景:tools、skills--**Characteristics**: / 特点:-- Has multiple structured fields (including statistical fields like usage count, success rate, etc.) / 有多个结构化字段(包括统计字段如使用次数、成功率等)-- `content` is rendered from fields via `content_template` / `content` 是通过 `content_template` 从字段渲染出来的-- `MEMORY_FIELDS` JSON comment is always placed at the end of the file / `MEMORY_FIELDS` JSON 注释永远放在文件最后-- Update workflow: / 更新流程:- 1. Parse JSON fields from `<!-- MEMORY_FIELDS -->` comment at the end of Markdown file / 从 Markdown 文件最后的 `<!-- MEMORY_FIELDS -->` 注释中解析 JSON 字段- 2. Perform memory updates according to field's `merge_op` / 根据字段的 `merge_op` 做记忆更新- 3. Re-render Markdown content via `content_template` after update / 更新后通过 `content_template` 重新渲染 Markdown 内容- 4. Write updated `MEMORY_FIELDS` back to end of file / 把更新后的 `MEMORY_FIELDS` 写回文件最后--**Config Examples** / **配置示例**:--**tools.yaml**-```yaml-name: tools-description: |- Tool usage memory - captures "how this tool is used, what works well, and what doesn't".- Extract tool usage patterns, statistics, and learnings from [ToolCall] records and conversation context.- For each tool, track: how many times it's been called, success rate, average time/tokens, what it's best for, optimal parameters, common failure modes, and actionable recommendations.- Also accumulate complete guidelines with "Good Cases" and "Bad Cases" examples.- Tool memories help the agent learn from experience and use tools more effectively over time.-directory: "viking://agent/{agent_space}/memories/tools"-filename_template: "{tool_name}.md"--content_template: |- Tool: {tool_name}-- Static Description:- "{static_desc}"-- Tool Memory Context:- Based on {total_calls} historical calls:- - Success rate: {success_rate}% ({success_count} successful, {fail_count} failed)- - Avg time: {avg_time}, Avg tokens: {avg_tokens}- - Best for: {best_for}- - Optimal params: {optimal_params}- - Common failures: {common_failures}- - Recommendation: {recommendation}-- {guidelines}--fields:- - name: tool_name- type: string- description: |- Tool name, copied exactly from [ToolCall] records without modification.- Used to uniquely identify this tool memory.- Examples: "web_search", "read_file", "execute_code"- merge_op: immutable-- - name: static_desc- type: string- description: |- Static description of the tool, basic functionality description.- Examples: "Searches the web for information", "Reads files from the file system"-- - name: total_calls- type: int64- description: |- Total number of tool calls, accumulated from historical statistics.- Used to calculate success rate and average duration.- merge_op: sum-- - name: success_count- type: int64- description: |- Number of successful tool calls, accumulated from historical statistics.- Counts calls with status "completed".- merge_op: sum-- - name: fail_count- type: int64- description: |- Number of failed tool calls, accumulated from historical statistics.- Counts calls with status not "completed".- merge_op: sum-- - name: total_time_ms- type: int64- description: |- Total tool call duration in milliseconds, accumulated from historical statistics.- Used to calculate average duration.- merge_op: sum-- - name: total_tokens- type: int64- description: |- Total tokens used by tool calls (prompt tokens + completion tokens), accumulated from historical statistics.- Used to calculate average token consumption.- merge_op: sum-- - name: best_for- type: string- description: |- Best use cases for the tool, describing in what scenarios this tool works best.- Examples: "Technical documentation, tutorials, API references"- merge_op: patch-- - name: optimal_params- type: string- description: |- Optimal parameter range/best practices for the tool, describing general parameter optimization suggestions.- Should describe general best practices (such as "max_results=5-20", "timeout>30s for large files"),- do not describe specific case values (such as "command: 'echo hello'").- Examples: "max_results: 5-20 (larger values may timeout); language: 'en' for better results; query: specific multi-word phrases with qualifiers"- merge_op: patch-- - name: common_failures- type: string- description: |- Common failure modes of the tool, describing problems and error patterns this tool frequently encounters.- Examples: "Single-word queries return irrelevant results; max_results>50 causes timeout; non-English queries have lower quality"- merge_op: patch-- - name: recommendation- type: string- description: |- Actionable recommendations for tool usage, short actionable recommendations.- Examples: "Use specific multi-word queries like 'Python asyncio tutorial'; add qualifiers like 'guide', 'docs', 'example'"- merge_op: patch-- - name: guidelines- type: string- description: |- Tool usage guidelines, complete usage guide content.- Must include exact English headings:- - "## Guidelines" - best practices- - "### Good Cases" - successful usage examples- - "### Bad Cases" - failed usage examples- Headings must be in English, content can be in target language.- merge_op: patch-```--**skills.yaml**-```yaml-name: skills-description: |- Skill execution memory - captures "how this skill is executed, what works well, and what doesn't".- Extract skill execution patterns, statistics, and learnings from skill usage in conversation.- For each skill, track: how many times it's been executed, success rate, what it's best for, recommended execution flow, key dependencies, common failure modes, and actionable recommendations.- Also accumulate complete guidelines with "Good Cases" and "Bad Cases" examples.- Skill memories help the agent learn from experience and execute skills more effectively over time.-directory: "viking://agent/{agent_space}/memories/skills"-filename_template: "{skill_name}.md"--content_template: |- Skill: {skill_name}-- Skill Memory Context:- Based on {total_executions} historical executions:- - Success rate: {success_rate}% ({success_count} successful, {fail_count} failed)- - Best for: {best_for}- - Recommended flow: {recommended_flow}- - Key dependencies: {key_dependencies}- - Common failures: {common_failures}- - Recommendation: {recommendation}-- {guidelines}--fields:- - name: skill_name- type: string- description: |- Skill name, copied exactly from [ToolCall] if skill_name is present, otherwise inferred from conversation context.- Used to uniquely identify this skill memory.- Examples: "create_presentation", "analyze_code", "write_document"- merge_op: immutable-- - name: total_executions- type: int64- description: |- Total number of skill executions, accumulated from historical statistics.- Used to calculate success rate.- merge_op: sum-- - name: success_count- type: int64- description: |- Number of successful skill executions, accumulated from historical statistics.- Counts successful executions.- merge_op: sum-- - name: fail_count- type: int64- description: |- Number of failed skill executions, accumulated from historical statistics.- Counts failed executions.- merge_op: sum-- - name: best_for- type: string- description: |- Best use cases for the skill, describing in what scenarios this skill works best.- Examples: "Slide creation tasks with clear topic and target audience"- merge_op: patch-- - name: recommended_flow- type: string- description: |- Recommended execution flow for the skill, describing the best steps to execute this skill.- Examples: "1. Confirm topic and audience → 2. Collect reference materials → 3. Generate outline → 4. Create slides → 5. Refine content"- merge_op: patch-- - name: key_dependencies- type: string- description: |- Key dependencies/prerequisites for the skill, describing what prerequisites and inputs are needed to execute this skill.- Examples: "Clear topic (e.g., 'Q3 project update', 'Python tutorial'); Target audience (e.g., 'executives', 'beginners'); Reference materials (optional but recommended)"- merge_op: patch-- - name: common_failures- type: string- description: |- Common failure modes of the skill, describing problems and error patterns this skill frequently encounters.- Examples: "Vague topic like 'make a PPT' leads to multiple rework cycles; Missing audience info causes style mismatch; No reference materials results in generic content"- merge_op: patch-- - name: recommendation- type: string- description: |- Actionable recommendations for skill usage, short actionable recommendations.- Examples: "Always confirm topic and audience before starting; Collect 2-3 reference materials for better quality"- merge_op: patch-- - name: guidelines- type: string- description: |- Skill usage guidelines, complete usage guide content.- Must include exact English headings:- - "## Guidelines" - best practices- - "### Good Cases" - successful usage examples- - "### Bad Cases" - failed usage examples- Headings must be in English, content can be in target language.- merge_op: patch-```--**Memory File Storage Format Example** / **记忆文件存储格式示例**:-```markdown-Tool: web_search--Static Description:-"Searches the web for information"--Tool Memory Context:-Based on 100 historical calls:-- Success rate: 92.0% (92 successful, 8 failed)-- Avg time: 1.2s, Avg tokens: 1500-- Best for: Technical documentation, tutorials, API references-- Optimal params: max_results=5-20, timeout>30s-- Common failures: Single-word queries return irrelevant results-- Recommendation: Use specific multi-word queries--## Guidelines-...--### Good Cases-...--### Bad Cases-...--<!-- MEMORY_FIELDS-{- "tool_name": "web_search",- "static_desc": "Searches the web for information",- "total_calls": 100,- "success_count": 92,- "fail_count": 8,- "total_time_ms": 120000,- "total_tokens": 150000,- "best_for": "Technical documentation, tutorials, API references",- "optimal_params": "max_results=5-20, timeout>30s",- "common_failures": "Single-word queries return irrelevant results",- "recommendation": "Use specific multi-word queries",- "guidelines": "## Guidelines\n...\n\n### Good Cases\n...\n\n### Bad Cases\n..."-}--->-```-------## Overall Architecture / 整体架构--```-┌─────────────────────────────────────────────────────────────────┐-│ Phase 0: Pre-fetch (System) │-│ ┌───────────────────────────────────────────────────────────┐ │-│ │ System automatically executes before LLM reasoning: │ │-│ │ 1. ls: Get all memory directory structures │ │-│ │ 2. read: Read all .abstract.md (L0) and .overview.md (L1)│ │-│ │ 3. search: Perform one semantic search in all directories│ │-│ │ Output: Pre-fetched Context (dir + L0/L1 + search results)│ │-│ └───────────────────────────────────────────────────────────┘ │-└─────────────────────────────────────────────────────────────────┘- ↓-┌─────────────────────────────────────────────────────────────────┐-│ Phase 1: Reasoning + Action (LLM + Optional Reads) │-│ ┌───────────────────────────────────────────────────────────┐ │-│ │ LLM: Analyze conversation + Pre-fetched Context │ │-│ │ Output: Reasoning + Actions (optional additional reads) │ │-│ │ - Reasoning: What memories need to change │ │-│ │ - Actions: Additional read operations (only if needed) │ │-│ └───────────────────────────────────────────────────────────┘ │-└─────────────────────────────────────────────────────────────────┘- ↓-┌─────────────────────────────────────────────────────────────────┐-│ Phase 2: Generate Operations (Final Output) │-│ ┌───────────────────────────────────────────────────────────┐ │-│ │ LLM: Generate final operations based on existing memories │ │-│ │ Output: MemoryOperations │ │-│ │ - WriteOp: New memory data (create or full replace) │ │-│ │ - EditOp: patch (SEARCH/REPLACE) incremental update │ │-│ │ - DeleteOp: URI to delete │ │-│ │ [Note] This is model's final output, directly executed │ │-│ └───────────────────────────────────────────────────────────┘ │-└─────────────────────────────────────────────────────────────────┘- ↓-┌─────────────────────────────────────────────────────────────────┐-│ Phase 3: System Execute │-│ ┌───────────────────────────────────────────────────────────┐ │-│ │ MemoryUpdater: Directly execute MemoryOperations │ │-│ │ - Write to OpenViking Storage (L0/L1/L2) │ │-│ │ - Update VikingDB vector index │ │-│ └───────────────────────────────────────────────────────────┘ │-└─────────────────────────────────────────────────────────────────┘-```-------## Core Components Design / 核心组件设计--### 1. Memory Data Structures / 记忆数据结构--#### 1.1 MemoryField (Memory Field Definition / 记忆字段定义)--Field properties / 字段属性:-- name: Field name / 字段名称-- field_type: Field type (string/int64/float32/bool) / 字段类型(string/int64/float32/bool)-- description-- merge_op: Merge operation (patch/sum/avg/immutable), default patch / 合并操作(patch/sum/avg/immutable),默认 patch- - patch: Default, SEARCH/REPLACE incremental update / 默认,SEARCH/REPLACE 增量更新- - sum: Sum (numeric fields like total_calls, success_count) / 累加(数字字段,如 total_calls、success_count)- - avg: Average (calculated from sum fields, non-storage field) / 平均值(从 sum 字段计算,非存储字段)- - immutable: Immutable after initial generation (for filename-related fields) / 初次生成后不可变(用于文件名相关字段)--**Special fields** / **特殊字段**:-- `content`: Default Markdown content field, only this field is used in simple mode / 默认的 Markdown 内容字段,简单模式下只用这个字段-- `abstract`: L0 summary field (one-sentence summary for indexing) / L0 摘要字段(用于索引的一句话摘要)-- `overview`: L1 overview field (structured Markdown summary) / L1 概览字段(结构化 Markdown 摘要)--#### 1.2 MemoryType (Memory Type Definition / 记忆类型定义)--Type properties / 类型属性:-- name: Type name, e.g., "preferences", "tools" / 类型名称,如 "preferences", "tools"-- description-- directory: Full URI for memory data storage, e.g., "viking://user/{user_space}/memories/preferences" / 记忆数据存放的完整 URI,如 "viking://user/{user_space}/memories/preferences"-- fields: MemoryField list / MemoryField 列表-- filename_template: Filename generation template, e.g., "{name}_{topic}.md" / 文件名生成模板,如 "{name}_{topic}.md"-- content_template: Content rendering template (supports field placeholders), used to render Markdown content from fields / 内容渲染模板(支持字段占位符),用于从 fields 渲染 Markdown 内容--**content_template example** (for tools type) / **content_template 示例**(用于 tools 类型):-```yaml-content_template: |- # Tool: {tool_name}-- Tool Memory Context:- Based on {total_calls} historical calls:- - Success rate: {success_rate}% ({success_count} successful, {fail_count} failed)- - Best for: {best_for}- - Common failures: {common_failures}- - Recommendation: {recommendation}-- {content}-```--#### 1.3 MemoryData (Dynamic Memory Data / 动态记忆数据)--Data properties / 数据属性:-- memory_type: Memory type name / 记忆类型名称-- uri: Memory URI (provided during update) / 记忆 URI(更新时提供)-- fields: Dynamic field data (Dict) / 动态字段数据(Dict)-- abstract/overview/content: L0/L1/L2 content / L0/L1/L2 内容-- name/tags/created_at/updated_at: Metadata / 元数据--### 2. ReAct Flow Data Structures / ReAct 流程数据结构--#### 2.1 Reasoning + Action (Phase 1: Reasoning Output / 阶段 1: 推理输出)--```-ReasoningAction:- - reasoning: str # LLM's thinking string (natural language description)- - memory_changes: List[MemoryChange] # Memories that need changes- - actions: List[ReadAction] # Read operations to execute--MemoryChange:- - change_type: write/edit/delete- - memory_type: Memory type- - uri: Memory URI (if known)- - reason: Reason for change--ReadAction:- - action_type: read/find/ls- - params: Dict # Call parameters-```--**Available Tools** (consistent with OpenViking VikingFS API) / **可使用的工具**(与 OpenViking VikingFS API 保持一致):--**read**-- Parameters / 参数: `uri: str, offset: int = 0, limit: int = -1`-- Returns / 返回: Memory file content (str) / 记忆文件内容(str)-- Description / 说明: Read single file, offset is start line number (0-indexed), limit is number of lines to read, -1 means read to end / 读取单个文件,offset 为起始行号(0-indexed),limit 为读取行数,-1 表示读取到末尾--**find**-- Parameters / 参数: `query: str, target_uri: str = "", limit: int = 10, score_threshold: Optional[float] = None, filter: Optional[Dict] = None`-- Returns / 返回: FindResult (includes memories, resources, skills) / FindResult(包含 memories, resources, skills)-- Description / 说明: Semantic search, target_uri is target directory URI / 语义搜索,target_uri 为目标目录 URI--**ls**-- Parameters / 参数: `uri: str, output: str = "agent", abs_limit: int = 256, show_all_hidden: bool = False, node_limit: int = 1000`-- Returns / 返回: List[Dict] (directory entry list) / List[Dict](目录条目列表)-- Description / 说明: List directory content, includes abstract field when output="agent" / 列出目录内容,output="agent" 时包含 abstract 字段--**tree**-- Parameters / 参数: `uri: str = "viking://", output: str = "agent", abs_limit: int = 256, show_all_hidden: bool = False, node_limit: int = 1000, level_limit: int = 3`-- Returns / 返回: List[Dict] (recursive directory tree) / List[Dict](递归目录树)-- Description / 说明: Recursively list all content, includes abstract field when output="agent", level_limit controls traversal depth / 递归列出所有内容,output="agent" 时包含 abstract 字段,level_limit 控制遍历深度--**Important** / **重要**: No function calls like add_memory/update_memory/delete_memory, add/edit/delete operations are model's final output as MemoryOperations, directly executed by system / 没有 add_memory/update_memory/delete_memory 这样的 function call,增删改操作通过模型最终输出 MemoryOperations,由系统直接执行--#### 2.2 MemoryOperations (Phase 2: Final Output / 阶段 2: 最终输出)--```-MemoryOperations:- - write_operations: List[WriteOp]- - edit_operations: List[EditOp]- - delete_operations: List[DeleteOp]--WriteOp:- - uri: Target memory URI / 目标记忆的 URI- - memory_data: MemoryData--EditOp:- - uri: Target memory URI / 目标记忆的 URI- - patches: Field-level updates / 字段级更新--DeleteOp:- - uri: Memory URI to delete / 要删除的记忆 URI-```--### 3. Patch Handler / Patch 处理器--#### 3.1 Content-level Patch (SEARCH/REPLACE) / 内容级 Patch (SEARCH/REPLACE)--```-Patch format / Patch 格式:-<<<<<<< SEARCH-:start_line:10---------Original content / 原始内容-=======-New content / 新内容->>>>>>> REPLACE-```--#### 3.2 Field-level Patch / 字段级 Patch--Handle according to field's merge_op / 根据字段的 merge_op 处理:-- patch: Default, SEARCH/REPLACE incremental update / 默认,SEARCH/REPLACE 增量更新-- sum: Sum (numeric fields like total_calls, success_count) / 累加(数字字段,如 total_calls、success_count)-- avg: Average (calculated from sum fields, non-storage field) / 平均值(从 sum 字段计算,非存储字段)--### 4. MemoryTypeRegistry (Type Registry / 类型注册表)--Features / 功能:-- register(memory_type): Register memory type / 注册记忆类型-- get(name): Get memory type / 获取记忆类型-- list_all(): List all types / 列出所有类型-- load_from_dir(dir_path): Load all MemoryType YAML files from directory (one type per file) / 从目录加载所有 MemoryType YAML 文件(每个文件一个类型)- - Default load built-in types from `openviking/session/memory/schemas/` / 默认从 `openviking/session/memory/schemas/` 加载内置类型--### 5. MemoryReActOrchestrator (ReAct Orchestrator / ReAct 编排器)--#### Workflow / 工作流:--**Optimization Strategy** / **优化策略**: To avoid excessive time from multiple ReAct rounds, system automatically performs pre-fetch before LLM reasoning / 为避免多次 ReAct 导致耗时过长,系统在 LLM 推理前自动执行前置读取:--**Phase 0: Pre-fetch (system executes, before LLM reasoning)** / **阶段 0: Pre-fetch(系统执行,LLM 推理前)**:-1. **ls**: Get all memory directory structures / 获取所有记忆目录结构- - `viking://user/{user_space}/memories/` and subdirectories / 及子目录- - `viking://agent/{agent_space}/memories/` and subdirectories / 及子目录-2. **read**: Read all `.abstract.md` (L0) and `.overview.md` (L1) / 读取所有 `.abstract.md` (L0) 和 `.overview.md` (L1)- - These summary files provide memory overview with small size / 这些摘要文件提供记忆的概览信息,体积小-3. **search**: Perform one semantic search in all directories / 在所有目录执行一次语义搜索- - Use current conversation as query / 使用当前对话作为查询- - Return list of relevant memory URIs / 返回相关的记忆 URI 列表--**Phase 1: Reasoning + Action**: LLM analyzes conversation + Pre-fetched Context, outputs ReasoningAction / LLM 分析对话 + Pre-fetched Context,输出 ReasoningAction- - reasoning: LLM's thinking string (natural language description) / LLM 的 thinking 字符串(自然语言描述)- - memory_changes: Memories that need changes (write/edit/delete) / 需要变更的记忆(write/edit/delete)- - actions: Additional read operations (only execute when needed, e.g., read specific L2 content) / 额外的读取操作(仅在需要时执行,如读取具体 L2 内容)- - System executes additional read operations (if needed) / 系统执行额外读取操作(如需要)--**Phase 2: Generate Operations**: LLM generates MemoryOperations based on existing memories (final output) / LLM 基于现有记忆生成 MemoryOperations(最终输出)--**Phase 3: System Execute**: System directly executes MemoryOperations / 系统直接执行 MemoryOperations--### 6. MemoryUpdater (Patch Applier - System Execution / Patch 应用器 - 系统执行)--Features / 功能:-- apply_operations(operations, user): Apply memory operations, return list of changed URIs / 应用记忆操作,返回变更的 URI 列表-- Directly execute MemoryOperations from model output, no function call / 直接执行模型输出的 MemoryOperations,不经过 function call--### 7. Structured Output Implementation / 结构化输出实现--Based on the implementation from ../memory project, the following tech stack is used / 基于 ../memory 项目的实现方案,采用以下技术栈:--#### 7.1 Core Components / 核心组件--**Pydantic BaseModel**: Used to define all data structures / 用于定义所有数据结构-- MemoryField, MemoryType, MemoryData-- ReasoningAction, MemoryChange, ReadAction-- MemoryOperations, WriteOp, EditOp, DeleteOp--**json_repair**: Fault-tolerant LLM output parsing / 容错解析 LLM 输出-- Auto-repair incomplete JSON / 自动修复不完整的 JSON-- Handle trailing content (e.g., safety warnings) / 处理尾随内容(如安全警告)-- Compatible with non-standard formats / 兼容非标准格式--**Pydantic TypeAdapter**: Type validation and conversion / 类型验证和转换-- validate_python(value, strict=False) - non-strict mode validation / 非严格模式验证-- Automatic type conversion / 自动类型转换-- Fault-tolerant filtering for list types / 列表类型容错过滤--**BaseModelCompat**: Compatibility base class (refer to ../memory) / 兼容性基类(参考 ../memory)-- Extract base type from Optional/Union / 从 Optional/Union 提取基础类型-- Convert 'None' string to None / 'None' 字符串转 None-- Automatic string conversion (array→comma-separated string, dict→JSON) / 字符串自动转换(数组→逗号分隔字符串,dict→JSON)-- Numeric fault tolerance (string→int/float) / 数字容错(字符串→int/float)-- List fault tolerance (string→[string], dict→[dict]) / 列表容错(字符串→[string],dict→[dict])--#### 7.2 JSONAdapter Flow / JSONAdapter 流程--```-1. format() - Build prompt / 构建提示- - prepare_instructions(): Generate input/output field descriptions / 生成输入输出字段说明- - format_turn(): Format user/assistant messages / 格式化用户/助手消息- - format_fields(): Format field values / 格式化字段值--2. llm_request() - Call LLM / 调用 LLM- - Check if json_schema is supported / 检查是否支持 json_schema- - If supported: generate response_format (type: json_schema) / 如果支持:生成 response_format (type: json_schema)- - If not supported: use json_object or no format / 如果不支持:使用 json_object 或无格式- - Call LM with static_messages + dynamic_messages / 调用 LM,传入 static_messages + dynamic_messages--3. parse() - Parse output / 解析输出- - remove_trailing_content(): Remove content after JSON ends / 去除 JSON 结束后的内容- - json_repair.loads(): Fault-tolerant parsing / 容错解析- - parse_value(): Type conversion + fault tolerance / 类型转换 + 容错- - List type: filter invalid items / 列表类型:过滤无效项目- - Other types: use TypeAdapter validation / 其他类型:使用 TypeAdapter 验证-```--#### 7.3 Fault Tolerance Strategy / 容错策略--**JSON Parsing Fault Tolerance** / **JSON 解析容错**:-- Remove trailing content after JSON ends (e.g., safety warnings) / 去除 JSON 结束后的尾随内容(如安全警告)-- json_repair auto-repairs incomplete JSON / json_repair 自动修复不完整 JSON-- Compatible with array output (take first element) / 兼容数组输出(取第一个元素)--**Type Validation Fault Tolerance** / **类型验证容错**:-- List type: validate items one by one, skip invalid items / 列表类型:逐个验证元素,跳过无效项-- Non-strict mode (strict=False) validation / 非严格模式 (strict=False) 验证-- BaseModelCompat preprocessor handles common format issues / BaseModelCompat 预处理器处理常见格式问题--**Field Fault Tolerance** / **字段容错**:-- Missing fields: use default values / 缺失字段:使用默认值-- Extra fields: automatically ignore / 多余字段:自动忽略-- Type mismatch: attempt automatic conversion / 类型不匹配:尝试自动转换-------## Existing Design Analysis / 现有设计分析--### Current Architecture / 当前架构--### Storage / 存储方式--- **File Storage**: L0/L1/L2 three-level structure / L0/L1/L2 三层结构- - L0: `.abstract.md` - summary / 摘要- - L1: `.overview.md` - overview / 概览- - L2: content file / 内容文件--- **URI Structure**:- - User: `viking://user/{space}/memories/{category}/`- - Agent: `viking://agent/{space}/memories/{category}/`--- **Vector Index**: stored in context collection of VikingDB / 存储在 VikingDB 的 context 集合中--### Key Files / 关键文件--| File / 文件 | Purpose / 作用 |-| ----------------------------------------------------------------- | ------------------------------------------------------------- |-| `openviking/session/memory_extractor.py` | Memory extraction main logic (~1200 lines) / 记忆提取主逻辑 (~1200行) |-| `openviking/session/memory_deduplicator.py` | Deduplication decision (~395 lines) / 去重决策 (~395行) |-| `openviking/session/compressor.py` | Session compressor (~447 lines) / 会话压缩器 (~447行) |-| `openviking/prompts/templates/memory/` | V2 memory schema templates / v2 记忆 schema 模板 |-------## Implementation Steps / 实施步骤--### Phase 1: Core Data Structures / 核心数据结构--1. Create `openviking/session/memory/memory_data.py` / 创建 `openviking/session/memory/memory_data.py`- - Field type, merge operation Enum / 字段类型、合并策略 Enum- - MemoryField, MemoryType, MemoryData definitions / MemoryField、MemoryType、MemoryData 定义--2. Create `openviking/session/memory/memory_operations.py` / 创建 `openviking/session/memory/memory_operations.py`- - WriteOp, EditOp, DeleteOp- - MemoryOperations (LLM final output format) / MemoryOperations(LLM 最终输出格式)--3. Create `openviking/session/memory/memory_react.py` / 创建 `openviking/session/memory/memory_react.py`- - Standard LLM ReAct implementation / 标准的 LLM ReAct 实现--4. Create `openviking/session/memory/memory_functions.py` / 创建 `openviking/session/memory/memory_functions.py`- - ReadArgs/ReadResult- - FindArgs/FindResult- - LsArgs/LsResult- - READ_TOOL, FIND_TOOL, LS_TOOL definitions / READ_TOOL、FIND_TOOL、LS_TOOL 定义--### Phase 2: Patch Handling / Patch 处理--5. Create `openviking/session/memory/memory_patch.py` / 创建 `openviking/session/memory/memory_patch.py`- - MemoryPatchHandler class / MemoryPatchHandler 类- - apply_content_patch() - SEARCH/REPLACE format / SEARCH/REPLACE 格式- - apply_field_patches() - Field-level updates / 字段级更新--### Phase 3: Type Registration / 类型注册--6. Create `openviking/session/memory/memory_types.py` / 创建 `openviking/session/memory/memory_types.py`- - MemoryTypeRegistry class / MemoryTypeRegistry 类- - YAML loading functionality / YAML 加载功能- - Built-in type registration / 内置类型注册--7. Create YAML config files / 创建 YAML 配置文件- - Place in `openviking/session/memory/schemas/` directory / 放在 `openviking/session/memory/schemas/` 目录- - preferences.yaml, entities.yaml, tools.yaml, etc. / preferences.yaml、entities.yaml、tools.yaml 等--### Phase 4: MemoryUpdater--8. Create `openviking/session/memory/memory_updater.py` / 创建 `openviking/session/memory/memory_updater.py`- - MemoryUpdater class / MemoryUpdater 类- - apply_operations() method - system direct execution / apply_operations() 方法 - 系统直接执行- - Integration with OpenViking Storage / 与 OpenViking Storage 集成--### Phase 5: ReAct Orchestrator / ReAct 编排器--9. Complete `openviking/session/memory/memory_react.py` / 完善 `openviking/session/memory/memory_react.py`- - Standard LLM ReAct orchestrator implementation / 标准的 LLM ReAct 编排器实现--### Phase 6: Prompt Templates / 提示模板--10. Create LLM prompt templates / 创建 LLM 提示模板- - Reasoning prompt (output MemoryChangePlan format) / 推理提示(输出 MemoryChangePlan 格式)- - Operation generation prompt (output MemoryOperations format) / 操作生成提示(输出 MemoryOperations 格式)- - L0/L1 summary generation prompt / L0/L1 摘要生成提示--11. Create new memory_extractor_v2.py / 创建新的 memory_extractor_v2.py- - Implement new memory extractor entry point / 实现新的记忆提取器入口- - Preserve existing memory_extractor.py without modification / 保留现有 memory_extractor.py 不修改- - Can switch via config later / 后续可通过配置切换--### Phase 7: Testing and Verification / 测试与验证--12. Unit tests / 单元测试- - MemoryPatchHandler tests / MemoryPatchHandler 测试- - MemoryUpdater tests / MemoryUpdater 测试- - MemoryReActOrchestrator tests / MemoryReActOrchestrator 测试--13. Integration tests / 集成测试- - End-to-end ReAct flow tests / 端到端 ReAct 流程测试- - Backward compatibility tests / 向后兼容测试-------## File List / 文件清单--### New Files / 新增文件--```-openviking/session/-├── memory_extractor_v2.py # New memory extractor (replaces existing) / 新的记忆提取器(替换现有)--openviking/session/memory/-├── memory_data.py # Core data structures / 核心数据结构-├── memory_operations.py # Three operation definitions (LLM final output) / 三种操作定义(模型最终输出)-├── memory_react.py # ReAct orchestrator / ReAct 编排器-├── memory_functions.py # Function call definitions (read/find/ls) / Function call 定义(read/find/ls)-├── memory_patch.py # Patch handler / Patch 处理器-├── memory_types.py # Type registry / 类型注册表-├── memory_updater.py # Patch applier (system execution) / Patch 应用器(系统执行)-└── schemas/ # Config directory / 配置目录- ├── profile.yaml # directory: viking://user/{user_space}/memories- ├── preferences.yaml # directory: viking://user/{user_space}/memories/preferences- ├── entities.yaml # directory: viking://user/{user_space}/memories/entities- ├── events.yaml # directory: viking://user/{user_space}/memories/events- ├── cases.yaml # directory: viking://agent/{agent_space}/memories/cases- ├── patterns.yaml # directory: viking://agent/{agent_space}/memories/patterns- ├── tools.yaml # directory: viking://agent/{agent_space}/memories/tools- └── skills.yaml # directory: viking://agent/{agent_space}/memories/skills--tests/session/memory/-├── test_memory_data.py-├── test_memory_operations.py-├── test_memory_react.py-├── test_memory_patch.py-├── test_memory_types.py-└── test_memory_updater.py-```--### Preserved Files / 保留文件--```-openviking/session/memory_extractor.py # Preserve existing version, do not modify / 保留现有版本,不修改-```-------## ReAct Flow Details / ReAct 流程详细说明--### Phase 0: Pre-fetch (Pre-fetch - System Execution / 前置读取 - 系统执行)--**Purpose** / **目的**: Avoid excessive time from multiple ReAct rounds / 避免多次 ReAct 导致耗时过长--**System automatically executes** / **系统自动执行**:-1. **ls**: Get all memory directory structures / 获取所有记忆目录结构- - `viking://user/{user_space}/memories/` and subdirectories / 及子目录- - `viking://agent/{agent_space}/memories/` and subdirectories / 及子目录-2. **read**: Read all `.abstract.md` (L0) and `.overview.md` (L1) / 读取所有 `.abstract.md` (L0) 和 `.overview.md` (L1)-3. **search**: Perform one semantic search in all directories (using current conversation as query) / 在所有目录执行一次语义搜索(使用当前对话作为查询)--**Output** / **输出**: Pre-fetched Context (directory structure + L0/L1 summaries + search results) / Pre-fetched Context(目录结构 + L0/L1 摘要 + 搜索结果)--### Phase 1: Reasoning + Action (Reasoning + Action / 推理 + 行动)--**Input** / **输入**: Conversation history + Pre-fetched Context / 对话历史 + Pre-fetched Context--**LLM Task** / **LLM 任务**: Analyze conversation + Pre-fetched Context, identify memories that need changes + decide if additional reads are needed / 分析对话 + Pre-fetched Context,识别需要变更的记忆 + 决定是否需要额外读取--**Output** / **输出**: ReasoningAction (reasoning + optional additional actions) / ReasoningAction(reasoning + 可选的额外 actions)-- reasoning: List of memories that need changes (write/edit/delete) / 需要变更的记忆列表(write/edit/delete)-- actions: List of additional read operations (only execute when needed, e.g., read specific L2 content) / 额外的读取操作列表(仅在需要时执行,如读取具体 L2 内容)--**System Execution** / **系统执行**: Execute additional read operations in actions (if needed) / 执行 actions 中的额外读取操作(如需要)--### Phase 2: Generate Operations (Generate Final Operations / 生成最终操作)--**Input** / **输入**: Conversation history + Reasoning + read existing memories / 对话历史 + Reasoning + 读取的现有记忆--**LLM Task** / **LLM 任务**: Generate specific operations based on existing memories / 基于现有记忆生成具体的操作--**Output** / **输出**: MemoryOperations (model final output) / MemoryOperations(模型最终输出)--**Important** / **重要**: This is the model's final output, directly executed by system, no more function calls / 这是模型的最后输出,直接由系统执行,不再通过 function call--### Phase 3: System Execute (System Execution / 系统执行)--**Input** / **输入**: MemoryOperations--**Execution** / **执行**: MemoryUpdater.apply_operations() directly applies patch, writes to OpenViking Storage / MemoryUpdater.apply_operations() 直接应用 patch,写入 OpenViking Storage-------## Summary / 总结--This design is based on practices from ../memory project, uses ReAct pattern: / 本设计基于 ../memory 项目的实践,采用 ReAct 模式:-- ✅ Removed aggregation operators (not considered for now) / 移除了聚合算子(先不考虑)-- ✅ Adopt write/edit/delete three-operation Schema / 采用 write/edit/delete 三种操作 Schema-- ✅ Adopt RoocodePatch style dual-mode Patch (replace + patch) / 采用 RoocodePatch 风格的双模式 Patch(replace + patch)-- ✅ **Dual-mode design** / **双模式设计**:- - Simple mode: no content_template, only name + content fields / 简单模式:无 content_template,只有 name + content 字段- - Template mode: with content_template, supports multiple structured fields + MEMORY_FIELDS comment / 模板模式:有 content_template,支持多个结构化字段 + MEMORY_FIELDS 注释-- ✅ **Pre-fetch Optimization** / **前置读取优化**:- - Phase 0: System automatically executes before LLM reasoning / 阶段 0: 系统在 LLM 推理前自动执行- - ls: Get all memory directory structures / ls: 获取所有记忆目录结构- - read: Read all .abstract.md (L0) and .overview.md (L1) / read: 读取所有 .abstract.md (L0) 和 .overview.md (L1)- - search: Perform one semantic search in all directories / search: 在所有目录执行一次语义搜索- - Purpose: Avoid excessive time from multiple ReAct rounds / 目的:避免多次 ReAct 导致耗时过长-- ✅ **ReAct (Reasoning + Action) 3+1 phase flow** / **ReAct (Reasoning + Action) 3+1 阶段流程**:- 0. Pre-fetch: System automatically pre-fetches directories, L0/L1, search results / Pre-fetch: 系统自动前置读取目录、L0/L1、搜索结果- 1. Reasoning + Action: LLM outputs reasoning (memories that need changes) and actions (optional additional reads) based on pre-fetched context / LLM 基于 pre-fetched context 输出 reasoning(需要变更的记忆)和 actions(可选的额外读取)- 2. Generate Operations: Generate final MemoryOperations based on existing memories / 基于现有记忆生成最终的 MemoryOperations- 3. System Execute: System directly executes MemoryOperations (no more function calls) / 系统直接执行 MemoryOperations(不再通过 function call)-- ✅ Adopt semantic filenames, fully utilize navigation value of filenames / 采用语义化文件名,充分利用文件名的导航价值-- ✅ Learn from commercial memory library implementations, adopt patch incremental update mechanism, reduce LLM call count / 借鉴商业化记忆库的实现,采用 patch 增量更新机制,减少 LLM 调用次数-- ✅ Fully compatible with OpenViking existing storage structure / 完全兼容 OpenViking 现有存储结构diff --git a/docs/design/memory-isolation-design.md b/docs/design/memory-isolation-design.mddeleted file mode 100644index f34ecaa47..000000000--- a/docs/design/memory-isolation-design.md+++ /dev/null@@ -1,446 +0,0 @@-# Memory Isolation Design - Extract Loop 记忆隔离机制--## 1. 背景与目标--### 1.1 背景--根据 `account-namespace-shared-session-design.md` 设计方案,需要在 `extract_loop` 模块实现记忆隔离机制:--- **两个开关**:`isolate_user_scope_by_agent` 和 `isolate_agent_scope_by_user` 控制目录结构-- **user_id 从 session 消息提取**:支持群聊场景,从对话中动态提取记忆归属的 user_id-- **多用户归属**:events 类型记忆可归属多个 role_id,每个目录都写入一份--### 1.2 目标--1. 从 session 消息中动态提取参与者列表(user_id + agent_id)-2. 校验 LLM 输出的 role_id 是否在参与者范围内-3. 按 account namespace policy 和开关组合决定记忆存储目录-4. 支持一个记忆归属多个 role_id,分别写入对应目录-------## 2. 核心设计决策--### 2.1 职责分离--创建独立的 `MemoryIsolationHandler` 类,职责:--| 职责 | 说明 |-|------|------|-| 参与者提取 | 从 session messages 解析所有 participant user_id 和 agent_id |-| 目录计算 | 根据 namespace policy + role_id 计算存储目录 |-| 校验 | 校验 role_id 是否在参与者范围内 |-| 多目录写入 | 支持一个记忆写入多个目录 |--### 2.2 使用方--- **ExtractLoop**:初始化 handler,校验 role_id-- **MemoryUpdater**:使用 handler 计算写入目录,执行多目录写入--### 2.3 不涉及--- 不修改 session 的 CRUD 操作-- 不修改现有的 namespace policy 加载逻辑-- 不涉及向量索引的过滤逻辑-------## 3. 详细设计--### 3.1 类定义--```python-# openviking/session/memory/memory_isolation_handler.py--from dataclasses import dataclass-from typing import List, Optional, Set-from openviking.server.identity import RequestContext--@dataclass-class Participant:- """参与者信息"""- role_id: str # user 或 agent 的 ID- role_type: str # "user" 或 "agent"- account_id: str--@dataclass-class MemoryTarget:- """记忆写入目标"""- uri: str # 完整的 canonical URI- owner_user_id: Optional[str]- owner_agent_id: Optional[str]--class MemoryIsolationHandler:- """记忆隔离处理器"""-- def __init__(self, ctx: RequestContext):- self.ctx = ctx- self._participants: List[Participant] = []- self._participants_loaded = False-- def load_participants_from_messages(self, messages: List[dict]) -> None:- """- 从 session messages 中提取参与者列表。-- 遍历所有消息,按 role 字段区分:- - role="user" 时,role_id 为 user_id- - role="assistant" 时,role_id 为 agent_id- """- # 解析逻辑见 3.2- pass-- def get_participant_user_ids(self) -> List[str]:- """获取所有参与者的 user_id 列表"""- pass-- def get_participant_agent_ids(self) -> List[str]:- """获取所有参与者的 agent_id 列表"""- pass-- def validate_role_id(self, role_id: str, role_type: str) -> bool:- """- 校验 role_id 是否在参与者范围内。- - role_type="user" 时,校验 role_id 在 participant user_ids 中- - role_type="agent" 时,校验 role_id 在 participant agent_ids 中- """- pass-- def calculate_memory_targets(- self,- role_id: Optional[str],- role_type: str,- memory_type: str,- is_events: bool = False,- events_range: Optional[dict] = None,- ) -> List[MemoryTarget]:- """- 计算记忆的写入目标目录。-- Args:- role_id: 记忆归属的 role_id(可为 None,表示使用 ctx 默认值)- role_type: "user" 或 "agent"- memory_type: 记忆类型(events, preferences, entities 等)- is_events: 是否为 events 类型- events_range: events 的时间范围,用于确定涉及的 role_id-- Returns:- MemoryTarget 列表,每个目标对应一个写入目录- """- pass-- def _get_default_target(self, role_type: str) -> MemoryTarget:- """获取当前 ctx 默认的写入目标"""- pass-- def _calculate_target_for_role(- self,- role_id: str,- role_type: str,- memory_type: str,- ) -> MemoryTarget:- """为指定 role_id 计算写入目标"""- pass-```--### 3.2 参与者提取逻辑--```python-def load_participants_from_messages(self, messages: List[dict]) -> None:- """从 session messages 提取参与者"""- seen_users: Set[str] = set()- seen_agents: Set[str] = set()-- for msg in messages:- role = msg.get("role")- role_id = msg.get("role_id") or msg.get("role_id") # 兼容不同字段名-- if not role_id:- continue-- if role == "user":- if role_id not in seen_users:- seen_users.add(role_id)- self._participants.append(Participant(- role_id=role_id,- role_type="user",- account_id=self.ctx.account_id,- ))- elif role == "assistant":- if role_id not in seen_agents:- seen_agents.add(role_id)- self._participants.append(Participant(- role_id=role_id,- role_type="agent",- account_id=self.ctx.account_id,- ))-- # 如果没有从消息中提取到参与者,使用 ctx 默认值- if not self._participants:- self._participants.append(Participant(- role_id=self.ctx.user.user_id,- role_type="user",- account_id=self.ctx.account_id,- ))- self._participants.append(Participant(- role_id=self.ctx.user.agent_id,- role_type="agent",- account_id=self.ctx.account_id,- ))-- self._participants_loaded = True-```--### 3.3 目录计算逻辑--根据 namespace policy 的两个开关组合,计算存储目录:--```python-def _calculate_target_for_role(- self,- role_id: str,- role_type: str,- memory_type: str,-) -> MemoryTarget:- """为指定 role_id 计算写入目标"""- policy = self.ctx.namespace_policy- account_id = self.ctx.account_id-- if role_type == "user":- if policy.isolate_user_scope_by_agent:- # 需要额外 agent 维度,从 participants 中找 agent- agent_id = self._get_default_agent_id()- base_uri = f"viking://user/{role_id}/agent/{agent_id}"- else:- base_uri = f"viking://user/{role_id}"-- return MemoryTarget(- uri=f"{base_uri}/memories/{memory_type}",- owner_user_id=role_id,- owner_agent_id=agent_id if policy.isolate_user_scope_by_agent else None,- )-- else: # role_type == "agent"- if policy.isolate_agent_scope_by_user:- # 需要额外 user 维度,从 participants 中找 user- user_id = self._get_default_user_id()- base_uri = f"viking://agent/{role_id}/user/{user_id}"- else:- base_uri = f"viking://agent/{role_id}"-- return MemoryTarget(- uri=f"{base_uri}/memories/{memory_type}",- owner_agent_id=role_id,- owner_user_id=user_id if policy.isolate_agent_scope_by_user else None,- )-```--### 3.4 Events 多归属逻辑--```python-def calculate_memory_targets(- self,- role_id: Optional[str],- role_type: str,- memory_type: str,- is_events: bool = False,- events_range: Optional[dict] = None,-) -> List[MemoryTarget]:- """计算记忆的写入目标目录"""-- # Case 1: 非 events 类型- if not is_events:- if role_id is None:- # 使用 ctx 默认值- return [self._get_default_target(role_type)]-- # 校验 role_id- if not self.validate_role_id(role_id, role_type):- raise ValueError(- f"role_id '{role_id}' is not in session participants. "- f"Valid {role_type} participants: {self._get_valid_role_ids(role_type)}"- )-- return [self._calculate_target_for_role(role_id, role_type, memory_type)]-- # Case 2: events 类型 - 多归属- # 从 events_range 涉及的 messages 中提取所有 role_id- target_role_ids = self._extract_role_ids_from_messages_range(events_range)-- # 如果无法从 range 确定,则使用所有参与者- if not target_role_ids:- target_role_ids = self._get_valid_role_ids("user")-- targets = []- for uid in target_role_ids:- targets.append(self._calculate_target_for_role(uid, "user", memory_type))-- return targets-```--### 3.5 校验逻辑--```python-def validate_role_id(self, role_id: str, role_type: str) -> bool:- """校验 role_id 是否在参与者范围内"""- if role_type == "user":- return role_id in [p.role_id for p in self._participants if p.role_type == "user"]- else:- return role_id in [p.role_id for p in self._participants if p.role_type == "agent"]--def _get_valid_role_ids(self, role_type: str) -> List[str]:- """获取指定类型的有效 role_id 列表"""- return [p.role_id for p in self._participants if p.role_type == role_type]-```-------## 4. 接口变更--### 4.1 ExtractLoop 改动--```python-# openviking/session/memory/extract_loop.py--class ExtractLoop:- def __init__(self, ..., enable_isolation: bool = True):- # 新增- self.enable_isolation = enable_isolation- self._isolation_handler: Optional[MemoryIsolationHandler] = None-- async def run(self):- # 在 run() 开始时初始化 handler- if self.enable_isolation:- self._isolation_handler = MemoryIsolationHandler(self.ctx)- # 从 provider 获取 session messages- messages = self.context_provider.get_session_messages()- self._isolation_handler.load_participants_from_messages(messages)-- # ... 原有逻辑 ...-- def _validate_operations(self, operations: Any) -> None:- # 原有校验逻辑- super()._validate_operations(operations)-- # 新增: 校验 role_id- if self._isolation_handler:- self._isolation_handler.validate_operations_role_ids(operations)-```--### 4.2 MemoryUpdater 改动--```python-# openviking/session/memory/memory_updater.py--class MemoryUpdater:- def __init__(self, ..., isolation_handler: Optional[MemoryIsolationHandler] = None):- self.isolation_handler = isolation_handler-- async def execute_operations(self, operations):- # 对于每个 operation,计算目标目录列表- if self.isolation_handler:- targets = self.isolation_handler.calculate_memory_targets(...)- # 遍历 targets 分别写入- for target in targets:- await self._write_to_target(operation, target)- else:- # 原有逻辑- await self._write_operations(operations)-```-------## 5. 数据流--```-Session Messages- │- ▼-┌─────────────────┐-│ MemoryIsolation │ ◄── 初始化时注入 ctx-│ Handler │-└────────┬────────┘- │- ▼-┌─────────────────┐-│ 提取 Participants │-│ (user_id list, │-│ agent_id list) │-└────────┬────────┘- │- ▼-┌─────────────────┐-│ ExtractLoop │-│ _validate_ops │ ◄── 校验 LLM 输出的 role_id-└────────┬────────┘- │- ▼-┌─────────────────┐-│ MemoryUpdater │-│ execute_ops │ ◄── 计算多目标,写入多个目录-└─────────────────┘-```-------## 6. 测试计划--### 6.1 单元测试--| 测试用例 | 说明 |-|---------|------|-| `test_extract_participants_from_messages` | 从消息列表正确提取 user/agent |-| `test_validate_role_id_valid` | 合法 role_id 通过校验 |-| `test_validate_role_id_invalid` | 非法 role_id 抛出异常 |-| `test_calculate_targets_single` | 单 role_id 计算目标目录 |-| `test_calculate_targets_multiple` | 多 role_id 返回多个目标 |-| `test_namespace_policy_false_false` | 两个开关都为 false 的目录 |-| `test_namespace_policy_true_false` | isolate_user_scope_by_agent=true |-| `test_namespace_policy_false_true` | isolate_agent_scope_by_user=true |-| `test_namespace_policy_true_true` | 两个开关都为 true |--### 6.2 集成测试--| 测试用例 | 说明 |-|---------|------|-| `test_extract_loop_with_isolation` | 端到端隔离写入 |-| `test_events_multiple_users` | events 写入多个用户目录 |-| `test_invalid_role_id_rejected` | 无效 role_id 被拒绝 |-------## 7. 风险与边界--### 7.1 风险--- **消息中无 role_id**:如果 session 消息没有 role_id 字段,回退到 ctx 默认值-- **events range 解析失败**:无法解析时,使用所有参与者-- **目录冲突**:多用户写入时可能存在竞争,需要事务支持(已有)--### 7.2 边界--- 不涉及 session 创建时的 participant 记录-- 不涉及向量索引的过滤逻辑修改-- 不支持跨 account 的记忆共享-------## 8. 推荐落地顺序--1. 创建 `MemoryIsolationHandler` 类-2. 实现 participants 提取逻辑-3. 实现目录计算逻辑-4. 实现校验逻辑-5. 集成到 ExtractLoop-6. 集成到 MemoryUpdater-7. 编写单元测试-------## 9. 文件清单--| 文件 | 操作 |-|------|------|-| `openviking/session/memory/memory_isolation_handler.py` | 新建 |-| `openviking/session/memory/extract_loop.py` | 修改 |-| `openviking/session/memory/memory_updater.py` | 修改 |-| `tests/session/memory/test_memory_isolation_handler.py` | 新建 |\ No newline at end of filediff --git a/docs/design/memory-link-design.md b/docs/design/memory-link-design.mdindex 3bb7c81ee..7b957db48 100644--- a/docs/design/memory-link-design.md+++ b/docs/design/memory-link-design.md@@ -26,7 +26,7 @@ Memory Link 是在现有记忆体系(profile/preferences/entities/events 等**Skill 执行模型:** GBrain = CLI 工具(TypeScript,确定性操作如 search/put/sync/embed)+ Skillpack(29 个 fat markdown 指令文件)。Skill 是指令不是代码——告诉宿主 agent 什么时候调什么 CLI、什么条件下调 LLM,但不含运行时,没有 hook。-`gbrain skillpack install --all` 将 skill 文件复制到 agent workspace。+`gbrain skillpack install --all` 将 skill 文件复制到运行时 workspace。diff --git a/docs/design/multi-tenant-design.md b/docs/design/multi-tenant-design.mddeleted file mode 100644index 1281ac2d7..000000000--- a/docs/design/multi-tenant-design.md+++ /dev/null@@ -1,1637 +0,0 @@-# OpenViking 多租户设计方案--## Context--OpenViking 已定义了 `UserIdentifier(account_id, user_id, agent_id)` 三元组(PR #120),但多租户隔离尚未实施。当前状态:--- **认证**:单一全局 `api_key`,HMAC 比较(`openviking/server/auth.py`)-- **无 RBAC**:所有认证用户拥有完全访问权限-- **无存储隔离**:`VikingFS._uri_to_path` 将 `viking://` 映射到 `/local/`,无 account_id 前缀-- **VectorDB**:单一 `context` collection,无租户过滤-- **服务层**:`OpenVikingService` 持有单例 `_user`,不支持请求级用户上下文--目标:实现完整的多租户支持,包括 API Key 管理、RBAC、存储隔离。不考虑向后兼容。-------## 一、整体架构--```-Request- │- ▼-[Auth Middleware] ── 提取 API Key,先比对 root key,再查 user key 表 → (account_id, user_id, role)- │- ▼-[RBAC Guard] ── 按角色检查操作权限- │- ▼-[RequestContext] ── UserIdentifier + Role 注入为 FastAPI 依赖- │- ▼-[Router] ── 传递 RequestContext 到 Service- │- ▼-[Service Layer] ── 请求级用户上下文(非单例)- │- ├─► [VikingFS] ── 单例,接受 RequestContext 参数,_uri_to_path 按 account_id 隔离,逐层权限过滤- └─► [VectorDB] ── 单 collection,查询注入 account_id + owner_space 过滤-```--核心原则:-- **身份从 API Key 解析**,贯穿全链路-- **account 级隔离**:AGFS 路径前缀 + VectorDB account_id 过滤-- **user/agent 级隔离**:目录遍历时逐层过滤,只展示当前用户有权限的目录和文件-- VikingFS 通过 RequestContext 获取租户和用户信息-------## 二、API Key 管理--### 2.1 两层 Key 结构--| 类型 | 格式 | 解析结果 | 存储位置 |-|------|------|----------|----------|-| Root Key | `secrets.token_hex(32)` | role=ROOT | `ov.conf` server 段 |-| User Key (Legacy) | `secrets.token_hex(32)` | (account_id, user_id, role) | per-account `/{account_id}/_system/users.json` |-| User Key (New) | `base64url(account_id).base64url(user_id).base64url(secret)` | (account_id, user_id, role) | per-account `/{account_id}/_system/users.json` |--**新版 API Key 格式**:`base64url(account_id).base64url(user_id).base64url(secret)`-- 可直接从 key 中解码出 account_id 和 user_id(快速路径)-- 最后一段 secret 为 32 字节随机数(`secrets.token_hex(32)`)的 base64url 编码-- key 可通过前缀索引(key 前 8 字符)快速查找,也可直接解析身份-- 支持两种格式完全兼容:新 key 可通过直接解析或前缀索引解析,旧 key 继续通过前缀索引解析--用户的角色(ADMIN / USER)不由 key 决定,而是存储在 account 内的用户注册表中。--**Key 加密存储**:-- 支持 Argon2id 哈希存储 User Key(可选,通过 `encryption.api_key_hashing.enabled` 启用)-- 加密时存储:`key_prefix`(前 8 字符) + `key_hash`(Argon2id 哈希)-- 验证时:先用 key_prefix 快速定位候选 entry,再用 Argon2id 验证--**两层加密架构**:-| 加密层 | 配置项 | 算法 | 可逆性 | 说明 |-|--------|--------|------|--------|------|-| **文件层** | `encryption.enabled` | AES-GCM | ✅ 可逆 | 保护整个存储文件 |-| **API key 字段层** | `encryption.api_key_hashing.enabled` | Argon2id | ❌ 不可逆 | 保护 API key 本身 |--**默认行为**:`encryption.api_key_hashing.enabled = false`-- API key 以明文存储在 JSON 文件中-- 但整个文件被 AES-GCM 加密保护-- `ov admin list-users` 可以显示完整的 API key--### 2.2 User Key 机制--注册用户时生成新版格式 key,存入对应 account 的 `users.json`。验证时优先走快速路径(直接解析),回退到前缀索引查找。--**生成(新版)**:`generate_api_key(account_id, user_id)` → `base64url(account_id).base64url(user_id).base64url(secret)`-**生成(旧版)**:`secrets.token_hex(32)` → `7f3a9c1e...`(仅用于兼容)-**验证**:先比对 root key → 不匹配 → 检查是否为新版格式 → 直接解析并验证 → 失败则走前缀索引查找--**完整场景**:--```-1. Root 创建工作区 acme,指定 alice 为首个 admin- POST /api/v1/admin/accounts {"account_id": "acme", "admin_user_id": "alice"}- → 创建工作区 + 注册 alice(role=admin) + 返回 alice 的 user key: YWNtZQ==.YWxpY2U=.OWFmZTEyMjc2YTU3Njkz...--2. alice 用 key 访问 API- GET /api/v1/fs/ls?uri=viking:// -H "X-API-Key: YWNtZQ==.YWxpY2U=.OWFmZTEyMjc2YTU3Njkz..." → 200 OK- → 服务端直接从 key 解析出 account_id="acme", user_id="alice",再验证 secret--3. alice(admin)注册普通用户 bob- POST /api/v1/admin/accounts/acme/users {"user_id": "bob"} → 注册成功 + 返回 key: YWNtZQ==.Ym9i.5b2a...--4. bob 丢了 key,alice 重新生成(旧 key 立即失效,新 key 为新版格式)- POST /api/v1/admin/accounts/acme/users/bob/key → YWNtZQ==.Ym9i.ZWgyZDRm...(新 key)- bob 用旧 key 访问 → 401(已失效)--5. bob 的 key 泄露 → 重新生成即可,只影响 bob--6. alice 移除 bob- DELETE /api/v1/admin/accounts/acme/users/bob → 注册表和 key 一起删除- bob 再用 key 访问 → 解析验证/查表找不到 → 401-```--### 2.3 Key 存储--- **Root Key**:`ov.conf` 的 `server` 段(静态配置)-- **全局工作区列表**:AGFS `/_system/accounts.json`-- **Per-account 用户注册表**:AGFS `/{account_id}/_system/users.json`--存储结构示例:--```json-// /_system/accounts.json —— 全局工作区列表-{- "accounts": {- "default": { "created_at": "2026-02-13T00:00:00Z" },- "acme": { "created_at": "2026-02-13T10:00:00Z" }- }-}--// /acme/_system/users.json —— acme 工作区的用户注册表(未加密)-{- "users": {- "alice": { "role": "admin", "key": "YWNtZQ==.YWxpY2U=.OWFmZTEy..." },- "bob": { "role": "user", "key": "YWNtZQ==.Ym9i.ZWgyZDRm..." }- }-}--// /acme/_system/users.json —— acme 工作区的用户注册表(已加密)-{- "users": {- "alice": { "role": "admin", "key": "$argon2id$v=19$m=65536,t=3,p=2$...", "key_prefix": "YWNtZQ==" },- "bob": { "role": "user", "key": "$argon2id$v=19$m=65536,t=3,p=2$...", "key_prefix": "YWNtZQ==" }- }-}-```--启动时加载所有 account 的 `users.json` 到内存,构建全局 key → (account_id, user_id, role) 索引。写操作持久化到对应 account 目录。--**为什么存 AGFS**:User key 是运行时通过 Admin API 动态增删的,不能放 ov.conf。选择 AGFS 的核心理由是多节点一致性——多个 server 共享同一个 AGFS 后端时,一个节点创建的用户其他节点立即可见。--### 2.4 新模块 `openviking/server/api_keys/`--API Key 管理重构为模块化结构:--```-openviking/server/api_keys/-├── __init__.py # 统一对外接口,导出 APIKeyManager(默认 NewAPIKeyManager)-├── legacy.py # 原版 APIKeyManager(保留兼容,重命名为 LegacyAPIKeyManager)-└── new.py # 新版 NewAPIKeyManager,支持新版三段式 Key 格式-```--**导出接口(`__init__.py`)**:-```python-# 默认使用新版实现-from .new import NewAPIKeyManager as APIKeyManager--# 同时导出工具函数和 Legacy 实现-from .new import is_new_format_key, parse_api_key, generate_api_key-from .legacy import LegacyAPIKeyManager-```--**核心类 APIKeyManager**:-```python-class APIKeyManager:- """API Key 生命周期管理与解析(新版实现)"""-- def __init__(self, root_key: str, viking_fs: VikingFS, api_key_hashing_enabled: bool = False)- async def load() # 加载所有 account 的 users.json 到内存- def resolve(api_key: str) -> ResolvedIdentity # Key → 身份 + 角色(支持新版/旧版两种格式)- async def create_account(account_id: str, admin_user_id: str, namespace_policy=None) -> str- async def delete_account(account_id: str)- async def register_user(account_id, user_id, role="user") -> str- async def remove_user(account_id, user_id)- async def regenerate_key(account_id, user_id) -> str # 重新生成 key(升级为新版格式)- async def set_role(account_id, user_id, role)- def get_accounts() -> list- def get_users(account_id) -> list- def get_account_policy(account_id) -> AccountNamespacePolicy-```--**新版 Key 工具函数**:-```python-def is_new_format_key(api_key: str) -> bool-def parse_api_key(api_key: str) -> Tuple[str, str, str] # (account_id, user_id, secret)-def generate_api_key(account_id: str, user_id: str) -> str-```--**兼容策略**:-- `resolve()` 自动检测 key 格式,新版走快速解析路径,旧版走前缀索引-- `regenerate_key()` 总是生成新版格式 key,可用于存量 key 升级-- 存储格式与 Legacy 完全兼容,可无缝切换-------## 三、认证流程--### 3.1 核心类型--新建 `openviking/server/identity.py`:--```python-class Role(str, Enum):- ROOT = "root"- ADMIN = "admin" # account 内的管理员(用户属性,非 key 类型)- USER = "user"---@dataclass-class ResolvedIdentity:- role: Role- account_id: Optional[str] = None- user_id: Optional[str] = None- agent_id: Optional[str] = None # 来自 X-OpenViking-Agent header---@dataclass-class RequestContext:- user: UserIdentifier # account_id + user_id + agent_id- role: Role-```--### 3.2 认证流程--1. 从 `X-API-Key` 或 `Authorization: Bearer` 提取 Key-2. 若未配置 `root_api_key`,进入 **dev 模式**:返回 `(role=ROOT, account_id="default", user_id="default")`-3. 顺序匹配(Key 无前缀,纯随机 token):- - HMAC 比对 root key → 匹配则 role=ROOT- - 查 user key 内存索引 → 匹配则得到 (account_id, user_id, role),role 为 ADMIN 或 USER- - 均不匹配 → 401 Unauthorized-4. 从 `X-OpenViking-Agent` header 读取 `agent_id`(默认 `"default"`)-5. 构造 `RequestContext(UserIdentifier(account_id, user_id, agent_id), role)`--### 3.3 FastAPI 依赖注入--改动 `openviking/server/auth.py`:--```python-async def resolve_identity(request, x_api_key, authorization, x_openviking_agent) -> ResolvedIdentity-def require_role(*roles) -> Depends # 角色守卫工厂-def get_request_context(identity) -> RequestContext # 构造 RequestContext-```--所有 Router 从 `Depends(verify_api_key)` 迁移到 `Depends(get_request_context)`。-------## 四、RBAC 模型--### 4.1 三层角色--采用 ROOT / ADMIN / USER 三层角色。ADMIN 是用户在 account 内的角色属性,不由 key 类型决定。两层 key(root/user)+ 角色属性的设计:--1. **委托式管理链路**:ROOT 创建 account 并指定首个 admin → admin 自行注册用户并下发 user key。ROOT 不需要介入日常用户管理。-2. **灵活的 admin 管理**:一个 account 可以有多个 admin,ROOT 可以随时提升/降低用户角色。-3. **权限最小化**:user key 泄露只影响单个用户数据;admin 泄露影响该 account 但不波及其他 account;root key 影响全局。-4. **数据访问边界**:ADMIN 可访问本 account 下所有用户数据(管理审计需要),USER 只能访问自己的隔离空间。--### 4.2 角色与权限--| 角色 | 身份 | 能力 |-|------|------|------|-| ROOT | 系统管理员 | 一切:创建/删除工作区、指定 admin、跨租户访问 |-| ADMIN | 工作区管理员 | 管理本 account 用户、下发 User Key、账户内全量数据访问 |-| USER | 普通用户 | 访问自己的 user/agent/session scope + account 内共享 resources |--权限矩阵:--| 操作 | ROOT | ADMIN | USER |-|------|------|-------|------|-| 创建/删除工作区 | Y | N | N |-| 提升用户为 admin | Y | N | N |-| 注册/移除用户 | Y | Y (本 account) | N |-| 下发/重置 User Key | Y | Y (本 account) | N |-| FS 读写 (own scope) | Y | Y | Y |-| 跨 account 访问 | Y | N | N |-| VectorDB 搜索 | Y (全局) | Y (本 account) | Y (本 account) |-| Session 管理 | Y | Y (本 account 所有) | Y (仅自己的) |-| 系统状态 | Y | Y | N |--### 4.3 Agent 归属--Agent 目录由 `memory.agent_scope_mode` 配置决定:--- 默认 `user+agent`:按 `user_id + agent_id` 共同决定,用户与 agent 的组合有独立数据空间-- 可选 `agent`:仅按 `agent_id` 决定,同一 agent_id 的不同用户共享 agent 空间--```-# memory.agent_scope_mode = "user+agent"-/{account_id}/agent/{md5(user_id:agent_id)[:12]}/memories/cases/-/{account_id}/agent/{md5(user_id:agent_id)[:12]}/skills/-/{account_id}/agent/{md5(user_id:agent_id)[:12]}/instructions/--# memory.agent_scope_mode = "agent"-/{account_id}/agent/{md5(agent_id)[:12]}/memories/cases/-/{account_id}/agent/{md5(agent_id)[:12]}/skills/-/{account_id}/agent/{md5(agent_id)[:12]}/instructions/-```--因此,alice 和 bob 使用同一 agent_id 时,是否共享 agent 记忆和技能空间取决于 `memory.agent_scope_mode`。--### 4.4 Admin API--新增 Router: `openviking/server/routers/admin.py`--```-POST /api/v1/admin/accounts 创建工作区 + 首个 admin (ROOT)-GET /api/v1/admin/accounts 列出工作区 (ROOT)-DELETE /api/v1/admin/accounts/{account_id} 删除工作区 (ROOT),级联清理数据-POST /api/v1/admin/accounts/{account_id}/users 注册用户 (ROOT, ADMIN)-DELETE /api/v1/admin/accounts/{account_id}/users/{uid} 移除用户 (ROOT, ADMIN)-GET /api/v1/admin/accounts/{account_id}/users/{uid}/key 重新生成 User Key (ROOT, ADMIN)-PUT /api/v1/admin/accounts/{account_id}/users/{uid}/role 修改用户角色 (ROOT)-```-------## 五、存储隔离--### 5.1 三维隔离模型--存储隔离有三个独立维度:account、user、agent。--- **account**:顶层隔离,不同租户之间完全不可见-- **user**:同一 account 内,不同用户的私有数据互不可见。用户记忆、资源、session 属于用户本人-- **agent**:同一 account 内,agent 目录默认由 user_id + agent_id 共同决定;也可通过 `memory.agent_scope_mode="agent"` 改为仅由 agent_id 决定(见 4.3)--**Space 标识符**:`UserIdentifier` 提供两个方法 `user_space_name()` 和 `agent_space_name()`:--```python-def user_space_name(self) -> str:- """用户级 space,不含 agent_id"""- return f"{self._account_id}_{hashlib.md5(self._user_id.encode()).hexdigest()[:8]}"---def agent_space_name(self) -> str:- """Agent 级 space,受 memory.agent_scope_mode 控制"""- if config.memory.agent_scope_mode == "agent":- return hashlib.md5(self._agent_id.encode()).hexdigest()[:12]- return hashlib.md5(f"{self._user_id}:{self._agent_id}".encode()).hexdigest()[:12]-```--### 5.2 各 Scope 的隔离方式--| scope | AGFS 路径 | 隔离维度 | 说明 |-|-------|-----------|----------|------|-| `user/memories` | `/{account_id}/user/{user_space}/memories/` | account + user | 用户偏好、实体、事件属于用户本人 |-| `agent/memories` | `/{account_id}/agent/{agent_space}/memories/` | account + agent scope | agent 的学习记忆,隔离粒度由 `memory.agent_scope_mode` 决定 |-| `agent/skills` | `/{account_id}/agent/{agent_space}/skills/` | account + agent scope | agent 的能力集,隔离粒度由 `memory.agent_scope_mode` 决定 |-| `agent/instructions` | `/{account_id}/agent/{agent_space}/instructions/` | account + agent scope | agent 的行为规则,隔离粒度由 `memory.agent_scope_mode` 决定 |-| `resources/` | `/{account_id}/resources/` | account | account 内共享的知识资源 |-| `session/` | `/{account_id}/session/{user_space}/{session_id}/` | account + user | 用户的对话记录 |-| `redo/` | `/{account_id}/_system/redo/` | account | 崩溃恢复 redo 标记 |-| `_system/`(全局) | `/_system/` | 系统级 | 全局工作区列表 |-| `_system/`(per-account) | `/{account_id}/_system/` | account | 用户注册表 |--### 5.3 AGFS 文件系统隔离--**改动文件**: `openviking/storage/viking_fs.py`--VikingFS 保持单例,不持有任何租户状态。多租户通过参数传递实现:--**调用链路**:-1. 公开方法(`ls`、`read`、`write` 等)接收 `ctx: RequestContext` 参数-2. 公开方法从 `ctx.account_id` 提取 account_id,传给内部方法-3. 内部方法(`_uri_to_path`、`_path_to_uri`、`_collect_uris` 等)接收 `account_id: str` 参数,不依赖 ctx--**URI → AGFS 路径转换**(加 account_id 前缀):--```-viking://user/{user_space}/memories/x + account_id="acme"-→ /local/acme/user/{user_space}/memories/x-```--**AGFS 路径 → URI 转换**(去 account_id 前缀):--```-/local/acme/user/{user_space}/memories/x + account_id="acme"-→ viking://user/{user_space}/memories/x-```--返回给调用方的 URI 不含 account_id,对用户透明。account_id 只存在于 AGFS 物理路径层。--```python-# 公开方法:接收 ctx,提取 account_id,结果按权限过滤-async def ls(self, uri: str, ctx: RequestContext) -> List[str]:- path = self._uri_to_path(uri, account_id=ctx.account_id)- entries = await self._agfs.ls(path)- uris = [self._path_to_uri(e, account_id=ctx.account_id) for e in entries]- return [u for u in uris if self._is_accessible(u, ctx)] # 权限过滤,见 5.4---# 内部方法:只接收 account_id,不依赖 ctx-def _uri_to_path(self, uri: str, account_id: str = "") -> str:- remainder = uri[len("viking://") :].strip("/")- if account_id:- return f"/local/{account_id}/{remainder}" if remainder else f"/local/{account_id}"- return f"/local/{remainder}" if remainder else "/local"---def _path_to_uri(self, path: str, account_id: str = "") -> str:- inner = path[len("/local/") :] # "acme/user/{space}/memories/x"- if account_id and inner.startswith(account_id + "/"):- inner = inner[len(account_id) + 1 :] # "user/{space}/memories/x"- return f"viking://{inner}"-```--### 5.4 逐层权限过滤(Phase2)--user/agent 级隔离通过**逐层遍历时过滤**实现。用户可以从公共根目录(如 `viking://resources`)开始遍历,但每一层只能看到自己有权限的条目。--**示例**:--```-# alice(USER 角色)-ls viking://resources → 看到 account 内共享的 resources(无 user 隔离)-ls viking://agent/memories → 只看到 alice 当前 agent 的 {agent_space}/-ls viking://user/memories → 只看到 {alice_user_space}/--# admin(ADMIN 角色)-ls viking://resources → 同上,resources 在 account 内共享-ls viking://user/memories → 看到所有用户的 space 目录-```--**实现**:VikingFS 新增 `_is_accessible()` 方法:--```python-def _is_accessible(self, uri: str, ctx: RequestContext) -> bool:- """判断当前用户是否能访问该 URI"""- if ctx.role in (Role.ROOT, Role.ADMIN):- return True-- # 结构性目录(不含 space,如 viking://user/memories)→ 允许遍历- space_in_uri = self._extract_space_from_uri(uri)- if space_in_uri is None:- return True-- # 含 space 的 URI → 检查 space 是否属于当前用户或其 agent- return space_in_uri in (- ctx.user.user_space_name(),- ctx.user.agent_space_name(),- )-```--- **列举操作**(`ls`、`tree`、`glob`):AGFS 返回全量结果后,用 `_is_accessible` 过滤-- **读写操作**(`read`、`write`、`mkdir` 等):执行前调 `_is_accessible` 校验,无权限则拒绝-- **将来加 ACL**:`_is_accessible` 内部扩展为查 ACL 表,接口不变(见 5.7)--### 5.5 VectorDB 租户隔离--**改动文件**: `openviking/storage/collection_schemas.py`--单 `context` collection,schema 新增两个字段:--- `account_id`(string):account 级过滤-- `owner_space`(string):user/agent 级过滤,值为记录所有者的 `user_space_name()` 或 `agent_space_name()`--查询过滤策略(由 retriever 根据 ctx 构造):--| 角色 | 过滤条件 |-|------|---------|-| ROOT | 无 |-| ADMIN | `account_id` = ctx.account_id |-| USER | `account_id` = ctx.account_id AND `owner_space` IN (ctx.user.user_space_name(), ctx.user.agent_space_name()) |--写入时,`Context` 对象携带 `account_id` 和 `owner_space`,通过 `EmbeddingMsgConverter` 透传到 VectorDB。`owner_space` 始终只存原始所有者,不因共享而修改。--### 5.6 目录初始化--**改动文件**: `openviking/core/directories.py`--- 创建新账户时,初始化 account 级预设目录结构(公共根:`viking://user`、`viking://agent`、`viking://resources` 等)-- 用户首次访问时,懒初始化 user space 子目录(`viking://user/{user_space}/memories/preferences` 等)-- agent 首次使用时,懒初始化 agent space 子目录(`viking://agent/{agent_space}/memories/cases` 等)--### 5.7 未来 ACL 扩展方向(本版不实现)--当需要支持用户间资源共享(如 alice 共享某个 resources 目录给 bob)时,有两种扩展路径:--**方案 a:独立 ACL 表**--共享关系存储在独立的 ACL 表中(AGFS 或 VectorDB),不修改数据记录本身:--```-# ACL 记录-{ "grantee_space": "bob_user_space", "granted_uri_prefix": "viking://resources/{alice_space}/project-x" }--# bob 查询时-1. 解析可访问 space 列表:own spaces + 查 ACL 表得到被授权的 spaces-2. VectorDB filter: owner_space IN [bob_user_space, bob_agent_space, alice_user_space]-3. VikingFS _is_accessible: 检查 own space OR ACL 授权-```--优势:数据记录不变,授权/撤销即时生效,不需要批量更新记录。--**方案 b:VectorDB 新增 `shared_spaces` 字段**--在被共享的**目录记录**(非叶子节点)上新增 `shared_spaces` 列表字段,标记哪些 space 有访问权限:--```-# 目录记录-{ "uri": "viking://resources/{alice_space}/project-x", "owner_space": "alice_space", "shared_spaces": ["bob_space"] }--# bob 遍历时-_is_accessible 检查: owner_space 匹配 OR space in shared_spaces-```--优势:权限信息自包含在目录节点上,遍历时不需要额外查 ACL 表。需要配合遍历时的权限继承(子节点继承父目录的 shared_spaces)。--两种方案可结合使用。具体选型在 ACL 设计时确定。-------## 六、配置变更--### `ov.conf` server 段--```json-{- "server": {- "host": "0.0.0.0",- "port": 1933,- "root_api_key": "your-secret-root-key",- "cors_origins": ["*"]- }-}-```--**改动文件**: `openviking/server/config.py`--```python-@dataclass-class ServerConfig:- host: str = "0.0.0.0"- port: int = 1933- root_api_key: Optional[str] = None # 替代原 api_key- cors_origins: List[str] = field(default_factory=lambda: ["*"])-```--- `root_api_key`:替代原有的 `api_key`,用于 ROOT 身份认证。为 None 时进入本地开发模式(跳过认证)。-- 已移除 `private_key`(User Key 采用随机存储方案,不需要加密密钥)和 `multi_tenant`(统一多租户,不区分部署模式)。-------## 七、客户端变更--核心变化:多租户前客户端需要自行传递 `account_id` 和 `user_id`,多租户后这两个字段由服务端从 API Key 解析,客户端只需提供 `api_key` 和可选的 `agent_id`。--| 项目 | 多租户前 | 多租户后 |-|------|---------|---------|-| 身份来源 | 客户端构造 UserIdentifier | 服务端从 API Key 解析 |-| 必须参数 | url, api_key, account_id, user_id | url, api_key |-| 可选参数 | agent_id | agent_id |-| 身份 header | `X-OpenViking-User` + `X-OpenViking-Agent` | 仅 `X-OpenViking-Agent` |--### 7.1 Python SDK--**改动文件**: `openviking_cli/client/http.py`, `openviking_cli/client/sync_http.py`--```python-# 多租户后:身份由服务端从 api_key 解析-client = ov.SyncHTTPClient(- url="http://localhost:1933",- api_key="7f3a9c1e...", # 服务端查表解析出 account_id + user_id- agent_id="coding-agent", # 可选,默认 "default"-)-```--### 7.2 CLI--**改动文件**: `openviking_cli/session/user_id.py`--`ovcli.conf` 新增 `agent_id` 字段:--```json-{- "url": "http://localhost:1933",- "api_key": "7f3a9c1e...",- "agent_id": "coding-agent",- "output": "table"-}-```--CLI 发起请求时通过 `X-OpenViking-Agent` header 携带 agent_id。不再需要配置 `account_id` 和 `user_id`。--### 7.3 嵌入模式--嵌入模式支持多租户,通过构造参数传入 `UserIdentifier`。无 API Key 认证,身份由调用方直接声明(嵌入模式的调用方是可信代码)。--```python-# 默认(单用户,使用 default 工作区)-client = ov.Client(path="/data/openviking")--# 多租户(指定身份)-from openviking_cli.session.user_id import UserIdentifier--user = UserIdentifier("acme", "alice", "coding-agent")-client = ov.Client(path="/data/openviking", user=user)-```--内部将 `UserIdentifier` 转为 `RequestContext` 传给 Service 层,路径隔离和权限过滤逻辑与 HTTP 模式一致。-------## 八、部署模式--多租户为**破坏性改造**,不保留单租户模式。所有部署统一走多租户路径结构。--### 8.1 统一路径结构--所有 account(包括 default)使用层级路径:--```-/local/{account_id}/resources/...-/local/{account_id}/user/{user_space}/memories/...-/local/{account_id}/agent/{agent_space}/memories/...-```--原有扁平路径 `/local/resources/...` 不再使用,现有数据需重新导入。--### 8.2 运行模式--| 配置 | 行为 |-|------|------|-| 不配置 `root_api_key` | Dev 模式:跳过认证,使用 default account + default user + ROOT 角色 |-| 配置 `root_api_key` | 生产模式:强制 API Key 认证,支持多 account 和多用户 |--两种配置使用**完全相同的路径结构和 VectorDB schema**,区别仅在认证层:-- Dev 模式不验证 Key,自动填充默认身份-- 生产模式从 Key 解析身份--代码无分支逻辑,VikingFS 和 VectorDB 只有一套实现。--### 8.3 升级与数据迁移--旧版(单租户)升级到多租户后,存储结构变化:--| 影响 | 旧结构 | 新结构 |-|------|--------|--------|-| resources | `/local/resources/...` | `/local/default/resources/...` |-| user memories | `/local/user/memories/...` | `/local/default/user/{default_space}/memories/...` |-| agent data | `/local/agent/memories/...` | `/local/default/agent/{default_space}/memories/...` |-| session | `/local/session/...` | `/local/default/session/{default_space}/...` |-| VectorDB | 无 `account_id` 字段 | 需补 `account_id="default"` + `owner_space` |--迁移目标始终是 `default` account + `default` user,映射关系完全确定。--提供 CLI 迁移命令(Phase 2 实现):--```bash-python -m openviking migrate-```--迁移逻辑:-1. 检测旧结构(`/local/resources/` 存在但 `/local/default/` 不存在)-2. 创建 default account 目录结构-3. 搬迁 AGFS 文件到新路径-4. Batch update VectorDB 记录,补充 `account_id` 和 `owner_space` 字段-5. 输出迁移报告(搬迁文件数、更新记录数)--用户升级流程:停服 → 备份 → 执行 `migrate` → 验证 → 启动新版-------## 九、实施分期与任务拆解--### Phase 1:API 层多租户能力定义--实施顺序:`T1 → T3 → T2 → T4 → T5 → T10/T11 并行 → T12 → T16-P1 → T17-P1 → T14-P1`-------#### T1: 身份与角色类型定义--**新建** `openviking/server/identity.py`,依赖:无--定义三个类型,供后续所有任务引用:--```python-from enum import Enum-from dataclasses import dataclass-from typing import Optional-from openviking.session.user_id import UserIdentifier---class Role(str, Enum):- ROOT = "root"- ADMIN = "admin" # account 内的管理员(用户属性,非 key 类型)- USER = "user"---@dataclass-class ResolvedIdentity:- """认证中间件的输出:从 API Key 解析出的原始身份信息"""-- role: Role- account_id: Optional[str] = None # ROOT 可能无 account_id- user_id: Optional[str] = None # ROOT 可能无 user_id- agent_id: Optional[str] = None # 来自 X-OpenViking-Agent header---@dataclass-class RequestContext:- """请求级上下文,贯穿 Router → Service → VikingFS 全链路"""-- user: UserIdentifier # 完整三元组(account_id, user_id, agent_id)- role: Role-- @property- def account_id(self) -> str:- return self.user.account_id-```--**注意**:`RequestContext` 而非 `ResolvedIdentity` 是下游使用的类型。`ResolvedIdentity` 只在 auth 层内部使用,转换为 `RequestContext` 后传递。原因:`ResolvedIdentity` 的字段都是 Optional(ROOT 没有 account_id),而 `RequestContext.user` 是确定的 `UserIdentifier`——对于 ROOT,填入 `account_id="default"`。-------#### T3: ServerConfig 更新--**修改** `openviking/server/config.py`,依赖:无--改动点:--```python-# 改前-@dataclass-class ServerConfig:- host: str = "0.0.0.0"- port: int = 1933- api_key: Optional[str] = None # ← 删除- cors_origins: List[str] = field(default_factory=lambda: ["*"])---# 改后-@dataclass-class ServerConfig:- host: str = "0.0.0.0"- port: int = 1933- root_api_key: Optional[str] = None # ← 替代 api_key- cors_origins: List[str] = field(default_factory=lambda: ["*"])-```--`load_server_config()` 中对应修改读取字段:-```python-config = ServerConfig(- host=server_data.get("host", "0.0.0.0"),- port=server_data.get("port", 1933),- root_api_key=server_data.get("root_api_key"), # ← 改- cors_origins=server_data.get("cors_origins", ["*"]),-)-```-------#### T2: API Key Manager--**重构** `openviking/server/api_keys.py` → `openviking/server/api_keys/` 目录,依赖:T1--##### 存储结构(与 Legacy 兼容)--Per-account 存储,两级文件:--```python-# /_system/accounts.json — 全局工作区列表-{- "accounts": {- "default": {"created_at": "2026-02-12T10:00:00Z"},- "acme": {"created_at": "2026-02-13T08:00:00Z"},- }-}--# /{account_id}/_system/users.json — 该 account 的用户注册表(未加密)-{- "users": {- "alice": {"role": "admin", "key": "YWNtZQ==.YWxpY2U=.OWFmZTEy..."},- "bob": {"role": "user", "key": "YWNtZQ==.Ym9i.ZWgyZDRm..."},- }-}--# /{account_id}/_system/users.json — 该 account 的用户注册表(已加密)-{- "users": {- "alice": {"role": "admin", "key": "$argon2id$v=19$...", "key_prefix": "YWNtZQ=="},- "bob": {"role": "user", "key": "$argon2id$v=19$...", "key_prefix": "YWNtZQ=="},- }-}-```--内存索引(启动时从所有 account 加载):-```python-self._prefix_index: Dict[str, List[UserKeyEntry]] = {} # {key_prefix -> [entries]}-self._accounts: Dict[str, AccountInfo] = {} # {account_id -> AccountInfo(users)}-```--##### 方法逻辑(新版 NewAPIKeyManager)--**`__init__(root_key, viking_fs, api_key_hashing_enabled=False)`**:-- 存储 root_key-- 接收 VikingFS 实例(而非 AGFS URL)-- 可选启用 Argon2id 加密存储--**`async load()`**:-- 从 AGFS 读取 `/_system/accounts.json`,若不存在则创建 default account-- 遍历每个 account,读取 `/{account_id}/_system/users.json`-- 构建前缀索引:key 前 8 字符 → [UserKeyEntry]-- 支持自动迁移:plaintext key → hashed key(当 api_key_hashing_enabled=True 时)--**`resolve(api_key) -> ResolvedIdentity`**:-```-# 快速路径 + 兼容路径-if hmac.compare_digest(key, self._root_key):- → ResolvedIdentity(role=ROOT)--# 新版格式:直接解析 identity-if is_new_format_key(api_key):- try:- account_id, user_id, secret = parse_api_key(api_key)- account = self._accounts.get(account_id)- if account and user_id in account.users:- # 验证 secret(支持 plaintext 或 hashed)- if verify_secret(api_key, account.users[user_id]):- → ResolvedIdentity(role, account_id, user_id)- except:- pass # 解析失败回退到前缀索引--# Legacy 格式:前缀索引查找-key_prefix = key[:8]-for entry in self._prefix_index.get(key_prefix, []):- if verify_api_key(key, entry):- → ResolvedIdentity(role=entry.role, account_id=entry.account_id, user_id=entry.user_id)--raise UnauthenticatedError-```--**`async create_account(account_id, admin_user_id, namespace_policy=None) -> str`**:-- 验证 account_id 格式-- 检查 account_id 不重复-- 创建 account 记录到 `_accounts`-- 注册首个 admin 用户,生成 `generate_api_key(account_id, admin_user_id)`(新版格式)-- 可选存储 namespace_policy-- 持久化 `/_system/accounts.json`、`/{account_id}/_system/users.json` 和 setting.json-- 返回 admin 的 user key--**`async delete_account(account_id)`**:-- 从 `_accounts` 删除-- 从 `_prefix_index` 中删除该 account 的所有 key-- 删除 `/_system/accounts.json` 中的记录-- **注意**:AGFS 数据和 VectorDB 数据的级联清理由 Admin Router 调用方负责--**`async register_user(account_id, user_id, role="user") -> str`**:-- 检查 account_id 存在-- 生成 `generate_api_key(account_id, user_id)`(新版格式)-- 写入 account 用户表和前缀索引-- 持久化 `/{account_id}/_system/users.json`-- 返回 user key--**`async remove_user(account_id, user_id)`**:-- 从 account 用户表和前缀索引中移除-- 持久化 `/{account_id}/_system/users.json`--**`async regenerate_key(account_id, user_id) -> str`**:-- 删除旧 key 的前缀索引-- 生成 `generate_api_key(account_id, user_id)`(新版格式,用于升级)-- 更新用户表和前缀索引-- 持久化 `/{account_id}/_system/users.json`-- 返回新 key--**`async set_role(account_id, user_id, role)`**:-- 更新用户角色(仅 ROOT 可调用)-- 更新前缀索引中的 role-- 持久化 `/{account_id}/_system/users.json`--##### 兼容策略--- `LegacyAPIKeyManager` 保留在 `api_keys/legacy.py` 中,完整保留原行为-- `NewAPIKeyManager` 完整支持旧格式 key 的解析和存储-- `regenerate_key()` 可用于将旧格式 key 升级为新版格式-------#### T4: 认证中间件重写--**重写** `openviking/server/auth.py`,依赖:T1, T2, T3--删除现有的 `verify_api_key()`、`get_user_header()`、`get_agent_header()`,替换为:--**`resolve_identity(request, x_api_key, authorization, x_openviking_agent) -> ResolvedIdentity`**:-```-1. api_key_manager = request.app.state.api_key_manager-2. 若 api_key_manager 为 None(dev 模式,未配置 root_api_key):- 返回 ResolvedIdentity(role=ROOT, account_id="default", user_id="default", agent_id="default")-3. 提取 key(同现有逻辑:X-API-Key 或 Bearer)-4. identity = api_key_manager.resolve(key)- - 先 HMAC 比对 root key → 匹配则 role=ROOT- - 再查 user key 索引 → 匹配则得到 account_id, user_id, role(ADMIN/USER)- - 均不匹配 → 401-5. identity.agent_id = x_openviking_agent or "default"-6. 返回 identity-```--**`get_request_context(identity: ResolvedIdentity = Depends(resolve_identity)) -> RequestContext`**:-```-account_id = identity.account_id or "default"-user_id = identity.user_id or "default"-agent_id = identity.agent_id or "default"-return RequestContext(- user=UserIdentifier(account_id, user_id, agent_id),- role=identity.role,-)-```--**`require_role(*allowed_roles) -> dependency`**:-```python-def require_role(*allowed_roles: Role):- async def _check(ctx: RequestContext = Depends(get_request_context)):- if ctx.role not in allowed_roles:- raise PermissionDeniedError(f"Requires role: {allowed_roles}")- return ctx-- return _check-```-------#### T5: App 初始化集成--**修改** `openviking/server/app.py`,依赖:T2, T4--改动点在 `create_app()` 和 `lifespan()`:--```python-# 改前-app.state.api_key = config.api_key--# 改后-if config.root_api_key:- # 生产模式:初始化 APIKeyManager- api_key_manager = APIKeyManager(- root_key=config.root_api_key,- agfs_url=service._agfs_url,- )- await api_key_manager.load()- app.state.api_key_manager = api_key_manager-else:- # Dev 模式:跳过认证,使用默认身份- app.state.api_key_manager = None--# Admin API 始终注册(dev 模式下通过 role 守卫限制访问)-app.include_router(admin_router)-```--删除 `app.state.api_key`。--**注意**:APIKeyManager 初始化必须在 service.initialize() 之后,因为需要 AGFS URL。时序是:-1. `service = OpenVikingService()` → 启动 AGFS-2. `await service.initialize()` → 初始化 VikingFS/VectorDB-3. `api_key_manager = APIKeyManager(agfs_url=service._agfs_url)` → 用 AGFS 读 accounts.json + users.json-4. `await api_key_manager.load()`-------#### T10: Router 依赖注入迁移--**修改文件**:`server/routers/` 下所有 router,依赖:T4--##### Phase 1 改动--所有 router 的依赖从 `verify_api_key` 迁移到 `get_request_context`,但 **service 调用不变**(ctx 仅接收,不向下传递):--```python-# 改前[email protected]("/ls")-async def ls(uri: str, _: bool = Depends(verify_api_key)):- service = get_service()- result = await service.fs.ls(uri)- ...---# Phase 1 改后(ctx 接收但不传递)[email protected]("/ls")-async def ls(uri: str, _ctx: RequestContext = Depends(get_request_context)):- service = get_service()- result = await service.fs.ls(uri) # service 调用不变- ...-```--##### Phase 2 改动(待实施,依赖 T9)--Service 层适配完成后,将 ctx 传给 service 方法:--```python-# Phase 2 改后-async def ls(uri: str, ctx: RequestContext = Depends(get_request_context)):- service = get_service()- result = await service.fs.ls(uri, ctx=ctx) # 传递 ctx- ...-```--##### 需要改的 router 列表--| Router 文件 | 端点数量 | 备注 |-|-------------|---------|------|-| `filesystem.py` | ~10 | ls, tree, stat, mkdir, rm, mv, glob 等 |-| `content.py` | ~3 | read, abstract, overview |-| `search.py` | ~2 | find, search |-| `resources.py` | ~2 | add_resource, add_skill |-| `sessions.py` | ~5 | create, list, get, delete, extract, add_message |-| `relations.py` | ~3 | relations, link, unlink |-| `pack.py` | ~2 | export, import |-| `system.py` | ~1 | health(可能不需要 ctx) |-| `debug.py` | ~3 | status, observer 等 |-| `observer.py` | ~1 | 系统监控 |-------#### T11: Admin Router--**新建** `openviking/server/routers/admin.py`,依赖:T2, T4--##### 端点逻辑--**POST /api/v1/admin/accounts** — 创建工作区 + 首个 admin-```-权限:require_role(ROOT)-入参:{"account_id": "acme_corp", "admin_user_id": "alice"}-逻辑:- 1. api_key_manager.create_account(account_id, admin_user_id) → admin_user_key- 2. 为新账户初始化 AGFS 目录结构(调用 DirectoryInitializer)-返回:{"account_id": "acme_corp", "admin_user_id": "alice", "user_key": "<random_token>"}-```--**GET /api/v1/admin/accounts** — 列出工作区-```-权限:require_role(ROOT)-逻辑:遍历 api_key_manager._accounts-返回:[{"account_id": "acme_corp", "created_at": "...", "user_count": 2}, ...]-```--**DELETE /api/v1/admin/accounts/{account_id}** — 删除工作区-```-权限:require_role(ROOT)-逻辑:- 1. api_key_manager.delete_account(account_id)- 2. 级联清理 AGFS:rm -r /{account_id}/ (通过 VikingFS)- 3. 级联清理 VectorDB:删除 account_id=X 的所有记录-返回:{"deleted": true}-```--**POST /api/v1/admin/accounts/{account_id}/users** — 注册用户-```-权限:require_role(ROOT, ADMIN)-额外检查:ADMIN 只能操作自己的 account-入参:{"user_id": "bob", "role": "user"}-逻辑:api_key_manager.register_user(account_id, user_id, role) → user_key-返回:{"account_id": "acme_corp", "user_id": "bob", "user_key": "<random_token>"}-```--**DELETE /api/v1/admin/accounts/{account_id}/users/{uid}** — 移除用户-```-权限:require_role(ROOT, ADMIN)-额外检查:ADMIN 只能操作自己的 account-逻辑:api_key_manager.remove_user(account_id, uid)-返回:{"deleted": true}-```--**PUT /api/v1/admin/accounts/{account_id}/users/{uid}/role** — 修改用户角色-```-权限:require_role(ROOT)-入参:{"role": "admin"}-逻辑:api_key_manager.set_role(account_id, uid, role)-返回:{"account_id": "acme_corp", "user_id": "bob", "role": "admin"}-```--**POST /api/v1/admin/accounts/{account_id}/users/{uid}/key** — 重新生成 User Key-```-权限:require_role(ROOT, ADMIN)-额外检查:ADMIN 只能操作自己的 account-逻辑:api_key_manager.regenerate_key(account_id, uid) → new_key(旧 key 立即失效)-返回:{"user_key": "<random_token>"}-```--注册到 `server/routers/__init__.py` 和 `server/app.py`。-------#### T12: 客户端 SDK 更新--##### Phase 1 改动:HTTP 客户端--**修改文件**:`openviking_cli/client/http.py`, `openviking_cli/client/sync_http.py`,依赖:T4--HTTP 模式新增 `agent_id` 参数,通过 `X-OpenViking-Agent` header 发送:--```python-def __init__(self, url=None, api_key=None, agent_id=None):- self._agent_id = agent_id---# headers 构建-headers = {}-if self._api_key:- headers["X-API-Key"] = self._api_key-if self._agent_id:- headers["X-OpenViking-Agent"] = self._agent_id-```--身份由服务端从 API Key 解析,客户端不构造 `UserIdentifier`。--##### Phase 2 改动(待实施,依赖 T9):嵌入模式--**修改文件**:`openviking/client/local.py`,依赖:T9--嵌入模式支持多租户,通过构造参数传入 `UserIdentifier`,无 API Key 认证:--```python-def __init__(self, path=None, user: UserIdentifier = None):- self._service = OpenVikingService(path=path)- self._ctx = RequestContext(- user=user or UserIdentifier.the_default_user(),- role=Role.ROOT, # 嵌入模式无 RBAC,默认 ROOT 权限- )--async def ls(self, uri, ...):- return await self._service.fs.ls(uri, ctx=self._ctx)-```--嵌入模式不涉及 API Key 认证,但使用与服务模式相同的多租户路径结构(按 account_id 隔离)。-------#### T16-P1: 用户文档更新(Phase 1)--**修改文件**:`docs/en/` + `docs/zh/` 对应文件,依赖:T4, T11, T12--Phase 1 涉及认证和 API 层变更,需同步更新以下文档(中英文各一份):--| 文档 | 改动 |-|------|------|-| `guides/01-configuration.md` | server 段 `api_key` → `root_api_key`;ovcli.conf 新增 `agent_id` 字段说明 |-| `guides/04-authentication.md` | 重写:多租户认证机制(root key / user key)、RBAC 三层角色、Admin API 管理 key 的流程 |-| `guides/03-deployment.md` | 配置示例改用 `root_api_key`;客户端连接示例加 `agent_id`;新增多租户部署说明 |-| `api/01-overview.md` | 客户端示例加 `agent_id`;认证说明扩展为多租户;新增 Admin API 端点文档 |-| `getting-started/03-quickstart-server.md` | 示例更新 `root_api_key` + `agent_id` |-------#### T17-P1: 示例更新(Phase 1)--**修改文件**:`examples/` 目录,依赖:T4, T11, T12--Phase 1 涉及认证体系和客户端接口变更,需同步更新示例:--| 文件 | 改动 |-|------|------|-| `examples/ov.conf.example` | `api_key` → `root_api_key` |-| `examples/server_client/ov.conf.example` | 同上 |-| `examples/server_client/client_sync.py` | 新增 `--agent-id` 参数 |-| `examples/server_client/client_async.py` | 新增 `agent_id` 参数 |-| `examples/server_client/client_cli.sh` | 添加 `X-OpenViking-Agent` header 示例 |-| `examples/server_client/ovcli.conf.example` | 新增 `agent_id` 字段 |--新增多租户管理示例 `examples/multi_tenant/`:--```-examples/multi_tenant/-├── README.md # 多租户管理流程说明-├── ov.conf.example # 启用 root_api_key 的配置示例-├── admin_workflow.py # ROOT 创建 account → 注册 admin → admin 注册 user-├── admin_workflow.sh # 等效的 curl 命令版本-└── user_workflow.py # user key 日常操作(ls、add_resource、find)-```--`admin_workflow.py` 覆盖:-- ROOT 创建工作区(含首个 admin)-- Admin 注册普通 user 并获取 user key-- 列出所有账户和用户-- 删除用户和账户--`user_workflow.py` 覆盖:-- 使用 user key 连接 server-- 执行常规操作(ls, add_resource, find, session)-- 验证无权限访问 admin API 时返回 403-------#### T14-P1: 认证与管理测试--**T14a: APIKeyManager 单元测试**-- root key 验证(正确/错误)-- user key 注册、生成、解析(含角色:admin/user)-- 用户注册/移除后 key 有效性变化-- key 重新生成后旧 key 失效-- per-account users.json 持久化和加载-- create_account 同时创建首个 admin--**T14b: 认证中间件测试**-- resolve_identity 流程:root key 匹配 → ROOT,user key 查表 → ADMIN/USER-- user key 解析出 ADMIN 或 USER 角色(取决于用户注册表中的 role)-- dev 模式(无 root_api_key)-- require_role 守卫-- 无效 key / 缺失 key 的错误码--**T14e: 回归**-- 现有测试改为使用 dev mode(不配置 root_api_key)-------### Phase 2:存储层隔离实现(后续)--实施顺序:`T6/T7 并行 → T8 → T9 → T13 → T15 → T16-P2 → T17-P2 → T14-P2`-------#### T6: VikingFS 多租户改造--**修改** `openviking/storage/viking_fs.py`,依赖:T1--##### 需要加 `ctx` 参数的方法(全部公开方法)--VikingFS 有以下公开方法需要加 `ctx: RequestContext` 参数:--| 方法 | 调用 `_uri_to_path` | 备注 |-|------|---------------------|------|-| `read(uri, ctx)` | Y | |-| `write(uri, data, ctx)` | Y | |-| `mkdir(uri, ctx, ...)` | Y | |-| `rm(uri, ctx, ...)` | Y | |-| `mv(old_uri, new_uri, ctx)` | Y | |-| `grep(uri, pattern, ctx, ...)` | Y | |-| `stat(uri, ctx)` | Y | |-| `glob(pattern, uri, ctx)` | Y(间接,通过 tree) | |-| `tree(uri, ctx)` | Y | |-| `ls(uri, ctx)` | Y | |-| `find(query, ctx, ...)` | N(不直接调 _uri_to_path,但 retriever 需要 ctx) | |-| `search(query, ctx, ...)` | N(同上) | |-| `abstract(uri, ctx)` | Y | |-| `overview(uri, ctx)` | Y | |-| `relations(uri, ctx)` | Y | |-| `link(from_uri, uris, ctx, ...)` | Y | |-| `unlink(from_uri, uri, ctx)` | Y | |-| `write_file(uri, content, ctx)` | Y | |-| `read_file(uri, ctx)` | Y | |-| `read_file_bytes(uri, ctx)` | Y | |-| `write_file_bytes(uri, content, ctx)` | Y | |-| `append_file(uri, content, ctx)` | Y | |-| `move_file(from_uri, to_uri, ctx)` | Y | |-| `write_context(uri, ctx, ...)` | Y | |-| `read_batch(uris, ctx, ...)` | Y(间接) | |--##### 核心改动--统一多租户路径,`_uri_to_path` 和 `_path_to_uri` 始终按 account_id 前缀处理:--```python-def _uri_to_path(self, uri: str, account_id: str = "") -> str:- remainder = uri[len("viking://") :].strip("/")- if account_id:- return f"/local/{account_id}/{remainder}" if remainder else f"/local/{account_id}"- return f"/local/{remainder}" if remainder else "/local"---def _path_to_uri(self, path: str, account_id: str = "") -> str:- if path.startswith("viking://"):- return path- elif path.startswith("/local/"):- inner = path[7:] # 去掉 /local/- if account_id and inner.startswith(account_id + "/"):- inner = inner[len(account_id) + 1 :] # 去掉 account_id 前缀- return f"viking://{inner}"- ...-```--##### 私有方法的处理--内部方法 `_collect_uris`, `_delete_from_vector_store`, `_update_vector_store_uris`, `_ensure_parent_dirs`, `_read_relation_table`, `_write_relation_table` 不直接接受 ctx,而是由公开方法调用时已经完成了 `_uri_to_path` 转换,传入的是 AGFS path。--但 `_collect_uris` 内部调用 `_path_to_uri` 时需要 account_id 来正确还原 URI → 需要传 account_id 或 ctx 给这些内部方法。--**策略**:内部方法统一加 `account_id: str = ""` 参数(不用整个 ctx),公开方法从 `ctx.account_id` 提取后传入。-------#### T7: VectorDB schema 扩展--**修改** `openviking/storage/collection_schemas.py`,依赖:无--在 `context_collection()` 的 Fields 列表中新增:--```python-{"FieldName": "account_id", "FieldType": "string"},-```--位置放在 `id` 之后、`uri` 之前。--同时修改 `TextEmbeddingHandler.on_dequeue()`:`inserted_data` 中应已包含 `account_id`(由 T8 中 EmbeddingMsg 携带)。此处不需要额外改动,只需确保 schema 定义了该字段。-------#### T8: 检索层与数据写入的租户过滤--**修改文件**:`retrieve/hierarchical_retriever.py`, `core/context.py`,依赖:T1, T7--##### 8a. Context 对象增加 account_id 和 owner_space--`openviking/core/context.py` 中 `Context` 类需增加两个字段:--```python-account_id: str = "" # 所属 account-owner_space: str = "" # 所有者的 user_space_name() 或 agent_space_name()-```--`to_dict()` 输出包含这两个字段,`EmbeddingMsgConverter.from_context()` 无需改动即可透传到 VectorDB。--上游构造 Context 时需从 RequestContext 填入这两个字段:-- `ResourceService` / `SkillProcessor` → `account_id=ctx.account_id`, `owner_space=ctx.user.user_space_name()` 或 `agent_space_name()`(取决于 scope)-- `SessionCompressorV2` memory writes → 同上-- `DirectoryInitializer._ensure_directory()` → 同上--##### 8b. HierarchicalRetriever 注入多级过滤--`retrieve/hierarchical_retriever.py` 的 `retrieve()` 方法需接受 `ctx: RequestContext` 参数,根据角色构造不同粒度的过滤条件(见第五节 5.5):--```python-async def retrieve(self, query: TypedQuery, ctx: RequestContext, ...) -> QueryResult:- filters = []- if ctx.role == Role.ADMIN:- filters.append({"op": "must", "field": "account_id", "conds": [ctx.account_id]})- elif ctx.role == Role.USER:- filters.append({"op": "must", "field": "account_id", "conds": [ctx.account_id]})- filters.append({"op": "must", "field": "owner_space",- "conds": [ctx.user.user_space_name(), ctx.user.agent_space_name()]})- # ROOT 无过滤-```--调用方(`VikingFS.find()`, `VikingFS.search()`)从 ctx 传入。-------#### T9: Service 层适配--**修改文件**:`service/core.py` 及 `service/fs_service.py`, `service/search_service.py`, `service/session_service.py`, `service/resource_service.py`, `service/relation_service.py`, `service/pack_service.py`, `service/debug_service.py`,依赖:T1, T6--##### 核心变更:去除 `_user` 单例--`OpenVikingService.__init__()` 中删除 `self._user`。-`set_dependencies()` 调用中删除 `user=self.user` 参数。--##### 各 sub-service 改动模式--所有 sub-service 当前的模式是:-```python-class XXXService:- def set_dependencies(self, viking_fs, ..., user=None):- self._viking_fs = viking_fs- self._user = user # ← 删除-- async def some_method(self, ...):- # 使用 self._viking_fs 和 self._user-```--改为:-```python-class XXXService:- def set_dependencies(self, viking_fs, ...): # 去掉 user- self._viking_fs = viking_fs-- async def some_method(self, ..., ctx: RequestContext): # 加 ctx- # 使用 self._viking_fs 和 ctx-```--##### 逐 service 改动清单--**FSService**(`service/fs_service.py`):-- 当前:`ls(uri)`, `tree(uri)`, `stat(uri)`, `mkdir(uri)`, `rm(uri)`, `mv(old, new)`, `read(uri)`, `abstract(uri)`, `overview(uri)`, `grep(uri, pattern)`, `glob(pattern, uri)`-- 改为:所有方法加 `ctx` 参数,传递给 VikingFS 调用--**SearchService**(`service/search_service.py`):-- 当前:`find(query, ...)`, `search(query, ...)`-- 改为:加 `ctx`,传给 VikingFS.find/search--**SessionService**(`service/session_service.py`):-- 当前:`session(session_id)`, `sessions()`, `delete(session_id)`, `extract(session_id)` 使用 `self._user`-- 改为:加 `ctx`,构造 Session 时从 ctx 获取 user,extract 时传 ctx.user 给 compressor-- session 路径变为 `viking://session/{ctx.user.user_space_name()}/{session_id}`--**ResourceService**(`service/resource_service.py`):-- 当前:`add_resource(...)`, `add_skill(...)` 使用 `self._user`-- 改为:加 `ctx`,构造 Context 时填入 `account_id=ctx.account_id`, `owner_space=ctx.user.agent_space_name()`(agent scope)-- 资源路径使用 `viking://resources/...`(account 内共享,无 user_space),技能路径使用 `viking://agent/skills/{ctx.user.agent_space_name()}/...`--**RelationService**(`service/relation_service.py`):-- 当前:`relations(uri)`, `link(from, to)`, `unlink(from, to)`-- 改为:加 `ctx`,传给 VikingFS--**PackService**(`service/pack_service.py`):-- 当前:`export_ovpack(uri)`, `import_ovpack(data)`-- 改为:加 `ctx`,传给 VikingFS--**DebugService**(`service/debug_service.py`):-- 当前:`get_status()`, `observer` 等系统级方法-- 改为:部分方法可能不需要 ctx(如 health check),但 observer 需要-------#### T13: 目录初始化适配--**修改文件**:`core/directories.py`,依赖:T6, T8--##### 核心改动--`DirectoryInitializer` 当前在 `service.initialize()` 中调用,初始化全局预设目录。多租户后改为三种初始化时机:--1. **创建新 account 时**(Admin API T11)→ 初始化该 account 的公共根目录(`viking://user`、`viking://agent`、`viking://resources` 等)-2. **用户首次访问时** → 懒初始化 user space 子目录(`viking://user/{user_space}/memories/preferences` 等)-3. **agent 首次使用时** → 懒初始化 agent space 子目录(`viking://agent/{agent_space}/memories/cases` 等)--方法签名改为接受 `ctx: RequestContext`:--```python-async def initialize_account_directories(self, ctx: RequestContext) -> int:- """初始化 account 级公共根目录"""- ...---async def initialize_user_directories(self, ctx: RequestContext) -> int:- """初始化 user space 子目录"""- ...---async def initialize_agent_directories(self, ctx: RequestContext) -> int:- """初始化 agent space 子目录"""- ...-```--`_ensure_directory` 和 `_create_agfs_structure` 中需要:-- 通过 ctx 传入 account_id 给 VikingFS-- 构造 Context 时填入 `account_id` 和 `owner_space`,写入 VectorDB 的记录也包含这两个字段-------#### T15: 数据迁移脚本--**新建** `openviking/cli/migrate.py`,依赖:T6, T7--提供 `python -m openviking migrate` 命令,将旧版单租户数据迁移到多租户路径结构。--##### 迁移逻辑--1. **检测**:检查旧结构是否存在(`/local/resources/` 存在但 `/local/default/` 不存在)-2. **AGFS 搬迁**:- - `/local/resources/...` → `/local/default/resources/...`- - `/local/user/...` → `/local/default/user/{default_user_space}/...`- - `/local/agent/...` → `/local/default/agent/{default_agent_space}/...`- - `/local/session/...` → `/local/default/session/{default_space}/...`-3. **VectorDB 更新**:batch update 所有记录,补充 `account_id="default"` 和 `owner_space={default_space}`-4. **报告**:输出搬迁文件数、更新记录数、耗时--##### 安全措施--- 迁移前检查目标路径不存在,避免覆盖-- 迁移失败时回滚已搬迁的文件-- 支持 `--dry-run` 预览迁移计划-------#### T16-P2: 用户文档更新(Phase 2)--**修改文件**:`docs/en/` + `docs/zh/` 对应文件,依赖:T6, T8, T15--Phase 2 涉及存储隔离和路径变更,需同步更新以下文档(中英文各一份):--| 文档 | 改动 |-|------|------|-| `concepts/01-architecture.md` | 新增多租户架构说明、身份解析流程、数据隔离层次 |-| `concepts/05-storage.md` | URI → AGFS 路径映射加 account_id 前缀;多租户存储布局图 |-| `concepts/04-viking-uri.md` | URI 在多租户下的 account 作用域说明 |-| `about/02-changelog.md` | 多租户版本变更说明 |-------#### T17-P2: 示例更新(Phase 2)--**修改文件**:`examples/` 目录,依赖:T6, T9--Phase 2 涉及存储隔离,需新增隔离相关示例:--| 文件 | 改动 |-|------|------|-| `examples/multi_tenant/isolation_demo.py` | **新增**:演示不同 account/user 间的数据隔离 |-| `examples/multi_tenant/agent_sharing_demo.py` | **新增**:演示同 account 下不同用户共享 agent 数据 |-| `examples/quick_start.py` | 嵌入模式加 `UserIdentifier` 参数说明 |--`isolation_demo.py` 覆盖:-- ROOT 创建两个 account-- 每个 account 的 user 分别写入 resources 和 memories-- 验证 account A 的 user 看不到 account B 的数据-- 验证同 account 内不同 user 的 memories 互相隔离-- 验证 resources 在同 account 内共享可见--`agent_sharing_demo.py` 覆盖:-- 同一 account 下两个 user 使用同一 agent_id-- 验证 agent memories/skills 在两个 user 间共享-- 验证 user memories 仍然互相隔离-------#### T14-P2: 隔离与可见性测试--**T14c: 存储隔离测试**-- `_uri_to_path` 加 account_id 前缀正确性-- `_path_to_uri` 反向转换正确性-- `_is_accessible` 对 USER/ADMIN/ROOT 的行为-- VectorDB 查询带 account_id + owner_space 多级过滤-- 同 account 下不同 user 无法互相访问 resources 和 memories-- 同 account 下同一用户不同 agent 的数据互相隔离--**T14d: 端到端集成测试**-- Root Key 创建 account(含首个 admin)→ Admin 注册 user → User Key 写数据 → 另一 account 查不到-- 同 account 两个 user 写 resources → 互相查不到-- 同 account 同一 user 不同 agent → agent 数据隔离-- 删除用户后旧 key 认证失败-- 删除 account 后数据清理-------## 九、关键文件清单--| 文件 | 改动类型 | 阶段 | 说明 |-|------|----------|------|------|-| `openviking/server/identity.py` | **新建** | P1 | Role(ROOT/ADMIN/USER), ResolvedIdentity, RequestContext |-| `openviking/server/api_keys.py` | **删除** | - | 原文件重构为目录结构 |-| `openviking/server/api_keys/__init__.py` | **新建** | P1 | 统一对外接口,导出 APIKeyManager = NewAPIKeyManager |-| `openviking/server/api_keys/legacy.py` | **新建** | P1 | 原 APIKeyManager 完整迁移,重命名为 LegacyAPIKeyManager |-| `openviking/server/api_keys/new.py` | **新建** | P1 | 新版 NewAPIKeyManager,支持三段式 key、加密存储 |-| `openviking/server/routers/admin.py` | **新建** | P1 | Admin 管理端点(account/user CRUD、角色管理) |-| `openviking/server/auth.py` | 重写 | P1 | verify_api_key → resolve_identity + require_role + get_request_context |-| `openviking/server/config.py` | 修改 | P1 | api_key → root_api_key |-| `openviking/server/app.py` | 修改 | P1 | 初始化 APIKeyManager,注册 Admin Router |-| `openviking_cli/client/http.py` | 修改 | P1 | 新增 agent_id 参数 |-| `openviking_cli/client/sync_http.py` | 修改 | P1 | 新增 agent_id 参数 |-| `openviking/server/routers/*.py` | 修改 | P1+P2 | P1: 迁移到 get_request_context;P2: ctx 传递给 service |-| `openviking/storage/viking_fs.py` | 修改 | P2 | 方法加 ctx 参数,_uri_to_path 加 account_id 前缀 |-| `openviking/storage/collection_schemas.py` | 修改 | P2 | context collection 加 account_id + owner_space 字段 |-| `openviking/retrieve/hierarchical_retriever.py` | 修改 | P2 | 查询注入 account_id + owner_space 多级过滤 |-| `openviking/service/core.py` | 修改 | P2 | 去除单例 _user,传递 RequestContext |-| `openviking/service/*.py` | 修改 | P2 | 各 sub-service 接受 RequestContext |-| `openviking/core/directories.py` | 修改 | P2 | 按 account 初始化目录 |-| `openviking/core/context.py` | 修改 | P2 | 新增 account_id、owner_space 字段 |-| `openviking/client/local.py` | 修改 | P2 | 支持 UserIdentifier 参数(嵌入模式多租户) |-| `openviking_cli/session/user_id.py` | 修改 | P2 | 新增 user_space_name() 和 agent_space_name() 方法 |-| `openviking/cli/migrate.py` | **新建** | P2 | 数据迁移脚本 |-| `docs/en/guides/*.md` + `docs/zh/guides/*.md` | 修改 | P1 | 配置、认证、部署文档更新 |-| `docs/en/api/01-overview.md` + `docs/zh/api/01-overview.md` | 修改 | P1 | API 概览加 Admin API、agent_id |-| `docs/en/concepts/*.md` + `docs/zh/concepts/*.md` | 修改 | P2 | 架构、存储、URI 文档更新 |-| `docs/en/about/02-changelog.md` + `docs/zh/about/02-changelog.md` | 修改 | P2 | 版本变更说明 |-| `examples/ov.conf.example` | 修改 | P1 | `api_key` → `root_api_key` |-| `examples/server_client/ov.conf.example` | 修改 | P1 | 同上 |-| `examples/server_client/client_sync.py` | 修改 | P1 | 新增 `agent_id` 参数 |-| `examples/server_client/client_async.py` | 修改 | P1 | 新增 `agent_id` 参数 |-| `examples/multi_tenant/` | **新建** | P1 | 多租户管理工作流示例(admin_workflow + user_workflow) |-| `examples/multi_tenant/isolation_demo.py` | **新建** | P2 | 数据隔离验证示例 |-| `examples/multi_tenant/agent_sharing_demo.py` | **新建** | P2 | agent 共享验证示例 |-------## 十、验证方案--1. **单元测试**:- - APIKeyManager 的 key 生成、注册、验证、角色解析- - per-account 存储的持久化和加载- - create_account 同时创建首个 admin 用户- - key 重新生成后旧 key 失效-2. **集成测试**:Account A 无法看到 Account B 的数据(AGFS + VectorDB)-3. **端到端测试**:- - Root Key 创建工作区(含首个 admin)→ Admin 注册 user → User Key 操作数据 → 验证隔离- - 删除用户后旧 user key 失败- - 删除 account 后级联清理数据- - Dev 模式(无 root_api_key)正常工作,使用 default account-4. **回归测试**:现有测试适配新认证流程(使用 dev mode)-------## 待评审决策项(TODO)--以下设计点在 V2 评审中已全部确定:--1. ~~**User Key 方案选型**(见 2.2 节)~~ —— 已确定:方案 B(随机 key + 查表),不需要 `private_key`。-2. ~~**Agent 目录归属模型**(见 4.3 节)~~ —— 已确定:方案 B(按 user_id + agent_id 隔离)。-3. ~~**单租户兼容**(见 8 节)~~ —— 已确定:破坏性改造,不保留单租户模式。--所有待评审项已解决,无遗留决策。-------## 评审记录--### 2026-02-13--#### 设计决策确定--1. **去掉 Account Key**:三层 Key(root/account/user)简化为两层(root/user)。ADMIN 不再由 key 类型决定,而是用户在 account 内的角色属性,存储在 `users.json` 中。一个 account 可以有多个 admin。-2. **Account = 工作区**:Account 是由 ROOT 创建的工作区(workspace)。`/_system/accounts.json` 维护全局工作区列表,每个工作区有独立的用户注册表 `/{account_id}/_system/users.json`。系统启动时自动创建 default 工作区。-3. **User Key 方案 B**:随机 key + 查表存储。不需要 `private_key` 配置,不需要加密库。key 丢失后重新生成,旧 key 立即失效。-4. **Agent 目录方案 B**:按 user_id + agent_id 隔离。`agent_space_name()` = `md5(user_id + agent_id)[:12]`,每个用户与 agent 的组合有独立数据空间。-5. **破坏性改造**:不保留单租户模式,统一多租户路径结构。所有 account(含 default)使用 `/{account_id}/...` 层级路径。-6. **嵌入模式支持多租户**:通过构造参数传入 `UserIdentifier`,默认使用 default 工作区 + default 用户。-7. **API Key 无前缀**:所有 key 为纯随机 token(`secrets.token_hex(32)`),不携带身份信息。服务端通过先比对 root key、再查 user key 索引的方式确定身份。-8. **Resources account 级共享**:resources 在 account 内共享,不按 user_space 隔离。路径为 `/{account_id}/resources/...`。-9. **ROOT 支持全部功能**:ROOT 权限为超集,既能做管理操作也能使用常规产品功能。dev 模式默认 ROOT 角色。-10. **配置简化**:`ov.conf` server 段移除 `private_key` 和 `multi_tenant`,仅保留 `root_api_key` 和 `cors_origins`。-11. **创建 account 同时指定首个 admin**:`POST /admin/accounts` 一步完成工作区创建 + 首个 admin 注册 + 返回 user key。-12. **队列/Observer account 级可见性**:底层单例,查询时按 account_id 过滤。放在 Phase 2。--#### 新增任务--- **T15**:数据迁移脚本(`python -m openviking migrate`),将旧版单租户数据迁移到多租户路径结构,Phase 2 实现-- **T16-P1**:Phase 1 用户文档更新(配置、认证、部署、API 概览、快速开始)-- **T16-P2**:Phase 2 用户文档更新(架构、存储、URI、变更日志)-- **T17-P1**:Phase 1 示例更新(config 文件 + 多租户管理工作流示例)-- **T17-P2**:Phase 2 示例更新(数据隔离验证 + agent 共享验证示例)--#### Key 存储方案--评审讨论了 key 存储结构的三种方案(user_id 做主键 / key 做主键 / 双索引),确定采用方案 A(user_id 做主键)。文件结构用于持久化和人工排查,运行时认证全走内存索引(`dict[key] → identity`),O(1) 查找。-diff --git a/docs/design/openclaw-plugin-design.md b/docs/design/openclaw-plugin-design.mddeleted file mode 100644index b325dcfce..000000000--- a/docs/design/openclaw-plugin-design.md+++ /dev/null@@ -1,257 +0,0 @@-# OpenClaw Plugin 架构与流程--## 概述--OpenClaw Plugin 将 OpenViking 注册为 OpenClaw 的 Context Engine,全面接管对话上下文的**组装、写入、压缩**三条主链路,同时提供若干显式工具供 Agent 主动调用。-------## 整体架构--```-┌──────────────────────────────────────────────────────────┐-│ OpenClaw │-│ │-│ User Message │-│ │ │-│ ├──► assemble() ──────────────────────────────┐ │-│ │ │ │-│ │ LLM Call │ │-│ │ │ │ │-│ └──► afterTurn() ──────────────────────────────┤ │-│ │ │-│ /compact ──► compact() ───────────────────────────┤ │-│ │ │-└──────────────────────────────────────────────────────┼───┘- │- ▼- ┌────────────────────────────────────────────────────┐- │ OpenViking │- │ │- │ ┌──────────────────────────────────────────────┐ │- │ │ OV Session │ │- │ │ addMessage / commit │ │- │ └──────────────────┬───────────────────────────┘ │- │ │ │- │ ┌────────┴────────┐ │- │ ▼ ▼ │- │ Archive Memories │- │ (归档原文) (长期记忆提取) │- │ │- │ viking://session/{id} │- │ viking://user/memories │- │ viking://agent/memories │- │ viking://resources │- └────────────────────────────────────────────────────┘-```-------## 三条主链路--### 链路 1:afterTurn — 无损写入--每轮 LLM 返回后执行,将本轮上下文持久化到 OV session,并在积累量达阈值时触发后台记忆提取。--```-afterTurn(messages, prePromptMessageCount)- │- ├── autoCapture 未启用 → 返回- ├── isHeartbeat → 返回- ├── session 匹配 bypassSessionPatterns → 返回- │- ├── extractNewTurnMessages(messages, prePromptMessageCount)- │ 从 prePromptMessageCount 位置切出本轮新增消息- │ 无新消息 → 返回- │- ├── 清理 recall 注入块(防止 <relevant-memories> 被二次捕获)- │- ├── client.addSessionMessage(ovSessionId, role, parts, agentId)- │ 逐条写入 OV session(user / assistant)- │- ├── client.getSession(ovSessionId) → pending_tokens- │- ├── pending_tokens < commitTokenThreshold(20k) → 返回- │- └── client.commitSession(wait=false) ──► 后台异步执行- Phase 2: archive + memory extract- └── pollPhase2ExtractionOutcome-```-------### 链路 2:assemble — 上下文组装--每次 LLM 调用前执行,根据调用场景走两条不同路径。--```-assemble(sessionId, messages, tokenBudget, runtimeContext)- │- ├── session 被 bypass → passthrough(原样返回)- │- ├── 判断调用类型- │ ├── isTransformContextAssemble(无 prompt/availableTools 等字段)- │ │ → 走「自动召回路径」- │ └── isMainAssemble(含 prompt/availableTools 等字段)- │ → 走「完整上下文路径」- │- ├──【自动召回路径】- │ ├── latest message 非 user → passthrough- │ ├── autoRecall 未启用 → passthrough- │ ├── 已含 AUTO_RECALL_SOURCE_MARKER → 跳过(防重复注入)- │ ├── prepareRecallQuery(userMessage) → query(最大 4000 chars)- │ ├── buildAutoRecallContext- │ │ ├── 并行检索 viking://user/memories- │ │ ├── 并行检索 viking://agent/memories- │ │ └── 过滤:level=2、score≥threshold、总chars≤recallMaxInjectedChars- │ └── prependRecallToLatestUserMessage → 前插 <relevant-memories> 块- │- └──【完整上下文路径】- ├── client.getSessionContext(ovSessionId, tokenBudget, agentId)- │ → latest_archive_overview- │ → pre_archive_abstracts- │ → messages(活跃消息)- │- ├── OV 无数据 OR OV 消息量 < 输入消息量 → passthrough- │- ├── allocateContextBudget(tokenBudget)- │ Archive: 剩余 × 15%,上限 8000 tokens ← 历史摘要(较旧)- │ Session: 剩余全部 ← 活跃消息(较新)- │ 保留区: max(15%, 20k tokens) ← 模型输出空间- │- ├── buildArchiveMemory → [Session History Summary] 消息- ├── buildSessionContext → OV messages → AgentMessages(超预算时从头裁剪)- │- ├── 消息后处理管道- │ normalizeAssistantContent- │ → canonicalizeAgentMessages- │ → sanitizeToolUseResultPairing- │ → mergeConsecutiveUsers- │ → ensureAlternation- │- └── 存在 archive 时注入 systemPromptAddition(Session Context Guide)-```--**Token 预算分层**--```- ↑ 旧(输入)-┌─────────────────────────────────────────────┐ tokenBudget-│ Archive Memory(历史摘要) │ 15%,max 8k-├─────────────────────────────────────────────┤-│ Session Context(活跃消息) │ 剩余全部-├─────────────────────────────────────────────┤-│ Reserved(保留区) │ 15%,min 20k-└─────────────────────────────────────────────┘- ↓ 新(模型输出)-```-------### 链路 3:compact — 归档提交--由 OpenClaw 触发(用户 /compact 或上下文超限),同步执行完整归档流程。--```-compact(sessionId, tokenBudget, currentTokenCount)- │- ├── session 被 bypass → { ok:true, compacted:false }- │- ├── 获取 tokensBefore- │ ├── 有 currentTokenCount → 直接使用- │ └── 无 → getSessionContext 估算- │- ├── client.commitSession(wait=true) ← 同步等待 Phase 2- │ ├── status=failed → { ok:false, compacted:false }- │ ├── status=timeout → { ok:false, compacted:false }- │ └── archived=false → { ok:true, compacted:false, reason:"commit_no_archive" }- │- ├── client.getSessionContext → latest_archive_overview(summary)- │- └── 返回 CompactResult- ok: true- compacted: true- result:- summary: latest_archive_overview- firstKeptEntryId: archive_uri 末段- tokensBefore / tokensAfter-```-------## Session 身份映射--OpenClaw session 标识 → OV storage id 的转换规则:--```-输入: sessionId, sessionKey- │- ├── sessionId 是 UUID 格式- │ → 小写直接使用- │- ├── sessionKey 非空- │ → sha256(sessionKey)- │- ├── sessionId 含 Windows 非法字符(: < > " \ 等)- │ → sha256("openclaw-session:" + sessionId)- │- └── 其他 sessionId- → 直接使用-```--**Agent ID 解析优先级**--```-sessionKey 格式 "agent:<id>:<rest>" 提取 agentId- └──► agent_prefix + "_" + agentId (sanitize 为 [a-zA-Z0-9_-])--runtimeContext.agentId- └──► agent_prefix + "_" + agentId--无任何来源- └──► "main"(或 "<agent_prefix>_main")-```-------## 工具注册--| 工具 | 触发场景 |-|------|---------|-| `memory_recall` | 主动检索 user/agent memories(可选 resources) |-| `memory_store` | 用户明确要求记住某内容,立即写入并同步 commit |-| `memory_forget` | 按 URI 删除,或 query 搜索后高置信度自动删除 |-| `add_resource` | 导入文档 / URL / Git 仓库到 viking://resources |-| `add_skill` | 导入 SKILL.md 到 viking://agent/skills |-| `ov_search` | 搜索 resources + agent/skills |-| `ov_archive_search` | 关键词 grep 当前 session 所有归档原始消息 |-| `ov_archive_expand` | 按 archive_id 展开归档原始消息列表 |--`memory_recall` 的搜索范围:--```-并行检索- ├── viking://user/memories- ├── viking://agent/memories- └── viking://resources(需 recallResources=true)--后处理:去重 → 只保留 level=2 叶子节点 → score 过滤 → 按 query 重排-```-------## 关键配置--| 配置项 | 默认值 | 说明 |-|--------|--------|------|-| `baseUrl` | `http://127.0.0.1:1933` | OV server 地址 |-| `agent_prefix` | `""` | Agent ID 前缀 |-| `autoCapture` | `true` | afterTurn 自动写入开关 |-| `autoRecall` | `true` | assemble 自动召回开关 |-| `commitTokenThreshold` | `20000` | 触发后台 commit 的 pending_tokens 阈值 |-| `commitKeepRecentCount` | `10` | afterTurn commit 后服务端保留的活跃消息数 |-| `recallLimit` | `6` | 自动召回最大记忆条数 |-| `recallScoreThreshold` | `0.15` | 召回分数过滤阈值 |-| `recallMaxInjectedChars` | `4000` | 自动召回注入的最大总字符数 |-| `recallPreferAbstract` | `false` | 优先使用摘要而非读取全文 |-| `bypassSessionPatterns` | `[]` | 完全跳过 OV 的 session key 模式 |diff --git a/docs/design/session-memory-extraction-flow.md b/docs/design/session-memory-extraction-flow.mdnew file mode 100644index 000000000..df1427f71--- /dev/null+++ b/docs/design/session-memory-extraction-flow.md@@ -0,0 +1,90 @@+# Session Memory Extraction Flow++This document records the current implementation. It is meant to be used as a+code-modification reference, so it avoids proposed or removed flows.++## Policy++`memory_policy` only carries target switches:++```json+{+ "self": { "enabled": true },+ "peer": { "enabled": false }+}+```++Legacy `types` fields are ignored. Type selection is not controlled by+`memory_policy`.++## Memory Type Groups++| Group | Types | Target |+| --- | --- | --- |+| Long-term memory | `profile`, `preferences`, `entities`, `events`, `cases`, `patterns`, `tools`, `skills`, `identity`, `soul` | Self and peer |+| Agent memory | `trajectories`, `experiences` | Self only |+| Session skills | `SESSION_SKILL_MEMORY_TYPE` output | Self only |++Agent memory is enabled only when `config.memory.agent_memory_enabled` is true.+Session skill extraction also requires self memory to be enabled.++## Commit Flow++Implemented in `openviking/session/session.py`:++1. Merge session-level and commit-level policy with `MemoryPolicy.merge`.+2. Archive the current message batch.+3. Hydrate tool outputs for extraction.+4. If peer memory is enabled, collect safe `message.peer_id` values from the+ archived batch into `allowed_peer_ids`.+5. Start archive summary generation.+6. If long-term extraction is enabled, call+ `SessionCompressorV2.extract_long_term_memories` once with the full archived+ batch, `allow_self_memory`, and `allowed_peer_ids`.+7. If self agent extraction is enabled, call+ `SessionCompressorV2.extract_agent_memories` once with the full archived+ batch.++The current flow does not build separate buckets such as+`self_identity_messages`, `self_experience_messages`,+`peer_user_message_groups`, or `peer_assistant_message_groups`.++## Long-Term Routing++Implemented in `openviking/session/memory/memory_isolation_handler.py`.++`MemoryIsolationHandler.calculate_memory_uris` resolves each extracted operation+independently:++| Operation fields | Result |+| --- | --- |+| No `peer_id`, no `ranges` | Write self if self memory is enabled |+| Safe `peer_id` in `allowed_peer_ids` | Write that peer |+| Unsafe `peer_id` | Skip |+| Safe but unallowed `peer_id` | Skip |+| `ranges` present | Read the message range; no-peer messages route to self, allowed peer messages route to peer |+| Only disabled targets found | Skip |++The router does not rewrite message roles. A `role=user` message remains user+content, a `role=assistant` message remains assistant content, and tool parts+stay on the message where they were recorded.++## Storage Targets++For current user space `viking://user/<user_id>`:++| Target | Storage space |+| --- | --- |+| Self | `viking://user/<user_id>/...` |+| Peer | `viking://user/<user_id>/peers/<peer_id>/...` |++Peer-only extraction does not initialize self default files. Default self files+are initialized only when `allow_self_memory` is true.++## Practical Invariants++- Long-term extraction sees the full archived batch once.+- The extractor may emit self and peer operations in the same response.+- Final write targets are decided per operation by the isolation handler.+- Peer writes require safe peer IDs observed in the archived batch.+- `trajectories`, `experiences`, and session skills never write peer memory.diff --git a/docs/design/tool-stub-design.md b/docs/design/tool-stub-design.mdindex 3fb2b7895..d9c70cb3e 100644--- a/docs/design/tool-stub-design.md+++ b/docs/design/tool-stub-design.md@@ -293,16 +293,15 @@ OpenViking 原生已经支持 tool result preview。原有链路能够在 sessio3. `message_id`4. `tool_id`5. `tool_name`-6. `agent_id`-7. `created_at`-8. `original_chars`-9. `preview_chars`-10. `sha256`-11. `mime_type`-12. `synopsis_kind`-13. `synopsis`-14. `storage_uri`-15. `output_uri`+6. `created_at`+7. `original_chars`+8. `preview_chars`+9. `sha256`+10. `mime_type`+11. `synopsis_kind`+12. `synopsis`+13. `storage_uri`+14. `output_uri`16. `offset_unit=unicode_code_point`### 读取方式diff --git a/docs/en/about/02-changelog.md b/docs/en/about/02-changelog.mdindex b7a62130b..5461635bd 100644--- a/docs/en/about/02-changelog.md+++ b/docs/en/about/02-changelog.md@@ -105,7 +105,7 @@ This changelog is automatically generated from [GitHub Releases](https://github.- **Web Studio as the default console**: Added the `web-studio` console workspace, shipped it in Docker and pip distributions, served it at `/studio`, moved OAuth authorize UI into it, and retired the legacy console while keeping favicon compatibility routes.- **MCP, API, and CLI automation**: Added Watch Management across REST, `ov`, and MCP; added progressive single-entrypoint local-file upload; added `code_outline`, `code_search`, and `code_expand`; and tightened upload-only and zip `--ignore-dirs` handling.- **Agent and OpenClaw ecosystem**: OpenClaw setup helper now supports npm plugin installs, plugin docs align with ClawHub package metadata, `ov_dream` was added as an OpenClaw skill, and oversized OpenClaw tool results can be externalized to OpenViking.-- **Memory and retrieval**: Upgraded trajectory extraction, added memory link support, added switchable Vaka memory templates, fixed missing tool-call counts and missing `role_id` retrieval, and parallelized hierarchical child search.+- **Memory and retrieval**: Upgraded trajectory extraction, added memory link support, added switchable Vaka memory templates, fixed missing tool-call counts and missing message-peer retrieval, and parallelized hierarchical child search.- **Storage, VectorDB, and model reliability**: Async storage locks/IO and loop-isolated async clients reduce contention; fixes cover semantic lock ownership, false `mv not found`, URI remapping, S3 grep performance, VectorDB Unicode recovery, oversized byte rows, embedding error surfacing, and VLM LiteLLM native routes.- **Observability, docs, and deployment polish**: Added VikingBot feedback observability, centralized the metric registry, moved usage audit SQLite into system data, refreshed Helm chart defaults, updated brand assets and QR code, and documented public base URL, signed upload TTLs, Watch APIs, MCP code tools, readiness probes, and the `/studio` migration.@@ -147,14 +147,14 @@ This changelog is automatically generated from [GitHub Releases](https://github.- **Observability**: OTLP export now supports custom `headers` for traces, logs, and metrics, enabling direct connection to backends that require extra auth or gRPC metadata.- **Upload**: Local directory scans and uploads now respect root and nested `.gitignore` rules, reducing noise from build artifacts and temp files.- **Search**: `search` and `find` now accept multiple target URIs for cross-directory and cross-repo retrieval.-- **Multi-tenant**: OpenClaw plugin clarifies `agent_prefix` as prefix-only; OpenCode memory plugin adds tenant header forwarding.-- **Admin**: New agent namespace discovery API, CLI command, and docs for listing existing agent namespaces under an account.+- **Multi-tenant**: OpenClaw plugin clarifies `peer_prefix` as peer metadata only; OpenCode memory plugin adds tenant header forwarding.+- **Admin**: Deprecated agent namespace discovery surfaces are removed.### Upgrade Notes- OTLP backends requiring extra auth can now use `headers` across all three exporter types (gRPC metadata in gRPC mode, HTTP headers in HTTP mode).- Local directory uploads will now filter files per `.gitignore` by default — previously imported temp/generated files may be excluded after upgrade.-- OpenClaw plugin `agent_prefix` is now prefix-only and no longer treated as a full agent identifier; docs migrate `agentId` → `agent_prefix`.+- OpenClaw plugin runtime identity now maps through `peer_prefix` peer metadata instead of an OpenViking agent namespace.[Full Changelog](https://github.com/volcengine/OpenViking/compare/v0.3.13...v0.3.14)@@ -173,7 +173,7 @@ This changelog is automatically generated from [GitHub Releases](https://github.### Upgrade Notes- `encryption.api_key_hashing.enabled` must now be configured explicitly (defaults to `false`). If you relied on implicit hashing, add it to your config.-- OpenClaw plugin is remote-only (no local subprocess), `agentId` → `agent_prefix`, `recallTokenBudget` → `recallMaxInjectedChars`.+- OpenClaw plugin is remote-only (no local subprocess), runtime agent identity moved to peer metadata, `recallTokenBudget` → `recallMaxInjectedChars`.[Full Changelog](https://github.com/volcengine/OpenViking/compare/v0.3.12...v0.3.13)@@ -205,7 +205,7 @@ This changelog is automatically generated from [GitHub Releases](https://github.- Adjusted the default `recallTokenBudget` and `recallMaxContentChars` to reduce the risk of overlong OpenClaw auto-recall context injection.- `ov add-memory` now returns `OK` for asynchronous commit workflows instead of implying the background task has already finished.- `ov chat` now reads authentication from `ovcli.conf` and sends the required request headers.-- The OpenClaw plugin now aligns remote connection behavior, auth, namespace, and `role_id` handling with the server multi-tenant model.+- The OpenClaw plugin now aligns remote connection behavior, auth, namespace, and `peer_id` handling with the server multi-tenant model.### Fixes@@ -413,7 +413,7 @@ This release focuses on stability and developer experience improvements. Key fix### Highlights-- OpenClaw plugin upgraded to 2.0 (context engine), OpenCode memory plugin added, multi-agent memory isolation via `agentId`.+- OpenClaw plugin upgraded to 2.0 (context engine), OpenCode memory plugin added, multi-agent memory isolation via peer metadata.- Memory cold-storage archival with hotness scoring, chunked vectorization for long memories, `used()` tracking interface.- Rerank integration in hierarchical retrieval, RetrievalObserver for quality metrics.- Resource watch scheduling, reindex endpoint, legacy `.doc`/`.xls` parser support, path locking and crash recovery.diff --git a/docs/en/agent-integrations/02-claude-code.md b/docs/en/agent-integrations/02-claude-code.mdindex 48680b905..1c14b2f13 100644--- a/docs/en/agent-integrations/02-claude-code.md+++ b/docs/en/agent-integrations/02-claude-code.md@@ -72,7 +72,7 @@ Config priority: env vars > `ovcli.conf` > `ov.conf` > built-in defaults (`http:| `OPENVIKING_MEMORY_ENABLED` | (auto) | Force on/off || `OPENVIKING_DEBUG` | `false` | Write logs to `~/.openviking/logs/cc-hooks.log` |-For multi-tenant deployments, set `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, and `OPENVIKING_AGENT_ID`. Full env-var list in the [plugin README](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#configuration).+For multi-tenant deployments, set `OPENVIKING_ACCOUNT` and `OPENVIKING_USER`. Full env-var list in the [plugin README](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#configuration).</details>diff --git a/docs/en/agent-integrations/03-openclaw.md b/docs/en/agent-integrations/03-openclaw.mdindex 40e75ec86..e3ac64b4a 100644--- a/docs/en/agent-integrations/03-openclaw.md+++ b/docs/en/agent-integrations/03-openclaw.md@@ -96,7 +96,7 @@ Plugin config lives under `plugins.entries.openviking.config`. Setup usually wri| --- | --- | --- || `baseUrl` | `http://127.0.0.1:1933` | OpenViking server endpoint || `apiKey` | empty | OpenViking API key |-| `agent_prefix` | `default` | Agent prefix for memory namespace isolation |+| `peer_prefix` | empty | Optional prefix for assistant peer identity when `peer_role=assistant` |```bashopenclaw config set plugins.entries.openviking.config.baseUrl http://your-server:1933diff --git a/docs/en/agent-integrations/07-langchain-langgraph.md b/docs/en/agent-integrations/07-langchain-langgraph.mdindex 88578aa10..1224af4bd 100644--- a/docs/en/agent-integrations/07-langchain-langgraph.md+++ b/docs/en/agent-integrations/07-langchain-langgraph.md@@ -23,6 +23,32 @@ tools = create_openviking_tools(When `url` is omitted, the adapters load connection settings from the OpenViking CLI config. Embedding and VLM providers are configured in OpenViking, not in your app.+## Peer identity++All adapters that read or write session memory accept `peer_id`. Use it when one OpenViking user interacts with multiple stable external peers, such as different agents, bots, or people in shared sessions.++```python+retriever = OpenVikingRetriever(+ url="http://localhost:1933",+ peer_id="assistant-a",+)++chain = with_openviking_context(+ runnable,+ session_id="support-thread-1",+ peer_id="assistant-a",+)+```++For dynamic runs, `with_openviking_context()` also reads `config["configurable"]["peer_id"]` by default:++```python+chain.invoke(+ {"messages": [...]},+ config={"configurable": {"session_id": "support-thread-1", "peer_id": "assistant-a"}},+)+```+## Which adapter should I use?| I want to… | Use this |diff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.mdindex 27d03e1ed..39920e3a3 100644--- a/docs/en/api/01-overview.md+++ b/docs/en/api/01-overview.md@@ -69,7 +69,6 @@ import openviking as ovclient = ov.SyncHTTPClient(url="http://localhost:1933",api_key="your-key",- agent_id="my-agent",timeout=120.0,)client.initialize()@@ -88,8 +87,7 @@ Configuration file example:"url": "http://localhost:1933","api_key": "your-key","account": "acme",- "user": "alice",- "agent_id": "my-agent"+ "user": "alice"}```@@ -101,7 +99,6 @@ Configuration field description:| `api_key` | API Key | `null` (no auth) || `account` | Default account header for tenant-scoped requests | `null` || `user` | Default user header for tenant-scoped requests | `null` |-| `agent_id` | Agent identifier header | `null` || `timeout` | HTTP request timeout in seconds | `60.0` || `output` | Default output format: `"table"` or `"json"` | `"table"` |@@ -475,7 +472,6 @@ Below are all HTTP API endpoints provided by OpenViking, grouped by functional m| DELETE | `/api/v1/admin/accounts/{account_id}` | Delete workspace (cascade data cleanup) | ROOT || POST | `/api/v1/admin/accounts/{account_id}/users` | Register user | ROOT/ADMIN || GET | `/api/v1/admin/accounts/{account_id}/users` | List users | ROOT/ADMIN |-| GET | `/api/v1/admin/accounts/{account_id}/agents` | List agent namespaces | ROOT/ADMIN || DELETE | `/api/v1/admin/accounts/{account_id}/users/{user_id}` | Remove user | ROOT/ADMIN || PUT | `/api/v1/admin/accounts/{account_id}/users/{user_id}/role` | Change user role | ROOT || POST | `/api/v1/admin/accounts/{account_id}/users/{user_id}/key` | Regenerate user key | ROOT/ADMIN |diff --git a/docs/en/api/02-resources.md b/docs/en/api/02-resources.mdindex eecc2e910..fa5bd40ca 100644--- a/docs/en/api/02-resources.md+++ b/docs/en/api/02-resources.md@@ -556,8 +556,8 @@ ov add-skill ./skills/my-skill.json --wait"status": "ok","result": {"status": "success",- "root_uri": "viking://agent/skills/my-skill",- "uri": "viking://agent/skills/my-skill",+ "root_uri": "viking://user/skills/my-skill",+ "uri": "viking://user/skills/my-skill","name": "my-skill","auxiliary_files": 2,"queue_status": {@@ -578,8 +578,8 @@ ov add-skill ./skills/my-skill.json --waitNote: Skill is being processed in the background.Use 'ov wait' to wait for completion, or 'ov observer queue' to check status.status success-root_uri viking://agent/skills/my-skill-uri viking://agent/skills/my-skill+root_uri viking://user/skills/my-skill+uri viking://user/skills/my-skillname my-skillauxiliary_files 2```@@ -589,8 +589,8 @@ auxiliary_files 2```json{"status": "success",- "root_uri": "viking://agent/skills/my-skill",- "uri": "viking://agent/skills/my-skill",+ "root_uri": "viking://user/skills/my-skill",+ "uri": "viking://user/skills/my-skill","name": "my-skill","auxiliary_files": 2}diff --git a/docs/en/api/04-skills.md b/docs/en/api/04-skills.mdindex 7de52a8ef..d5c173656 100644--- a/docs/en/api/04-skills.md+++ b/docs/en/api/04-skills.md@@ -14,10 +14,10 @@ OpenViking supports multiple skill definition formats:### Skill Storage Structure-Skills are stored at `viking://agent/skills/`:+Skills are stored at `viking://user/skills/`:```-viking://agent/skills/+viking://user/skills/+-- search-web/| +-- .abstract.md # L0: Brief description| +-- .overview.md # L1: Parameters and usage overview@@ -152,7 +152,7 @@ Skills are a special type of resource that define actions or tools agents can pe1. Receive skill data or uploaded temporary file2. Detect data format (structured data, SKILL.md content, MCP format)3. Parse skill definition-4. Store to `viking://agent/skills/` path+4. Store to `viking://user/skills/` path5. If `wait=true`, wait for vectorization to complete**Code Entry Points**:@@ -337,8 +337,8 @@ ov add-skill ./skills/my-skill/ -o json"status": "ok","result": {"status": "success",- "root_uri": "viking://agent/skills/my-skill/",- "uri": "viking://agent/skills/my-skill/",+ "root_uri": "viking://user/skills/my-skill/",+ "uri": "viking://user/skills/my-skill/","name": "my-skill","auxiliary_files": 2,"queue_status": {@@ -359,8 +359,8 @@ ov add-skill ./skills/my-skill/ -o jsonNote: Skill is being processed in the background.Use 'ov wait' to wait for completion, or 'ov observer queue' to check status.status success-root_uri viking://agent/skills/my-skill-uri viking://agent/skills/my-skill+root_uri viking://user/skills/my-skill+uri viking://user/skills/my-skillname my-skillauxiliary_files 2```@@ -369,8 +369,8 @@ auxiliary_files 2```json{"status": "success",- "root_uri": "viking://agent/skills/my-skill",- "uri": "viking://agent/skills/my-skill",+ "root_uri": "viking://user/skills/my-skill",+ "uri": "viking://user/skills/my-skill","name": "my-skill","auxiliary_files": 2}@@ -413,19 +413,19 @@ The Python HTTP SDK raises the corresponding mapped exception for this response.```python# List all skills-skills = client.ls("viking://agent/skills/")+skills = client.ls("viking://user/skills/")for skill in skills:print(f"{skill['name']}")# Simple list (names only-names = client.ls("viking://agent/skills/", simple=True)+names = client.ls("viking://user/skills/", simple=True)print(names)```**HTTP API**```bash-curl -X GET "http://localhost:1933/api/v1/fs/ls?uri=viking://agent/skills/" \+curl -X GET "http://localhost:1933/api/v1/fs/ls?uri=viking://user/skills/" \-H "X-API-Key: your-key"```@@ -434,7 +434,7 @@ curl -X GET "http://localhost:1933/api/v1/fs/ls?uri=viking://agent/skills/" \**Python SDK**```python-uri = "viking://agent/skills/search-web/"+uri = "viking://user/skills/search-web/"# L0: Brief descriptionabstract = client.abstract(uri)@@ -453,15 +453,15 @@ print(f"Content: {content}")```bash# L0: Brief description-curl -X GET "http://localhost:1933/api/v1/content/abstract?uri=viking://agent/skills/search-web/" \+curl -X GET "http://localhost:1933/api/v1/content/abstract?uri=viking://user/skills/search-web/" \-H "X-API-Key: your-key"# L1: Parameters and usage overview-curl -X GET "http://localhost:1933/api/v1/content/overview?uri=viking://agent/skills/search-web/" \+curl -X GET "http://localhost:1933/api/v1/content/overview?uri=viking://user/skills/search-web/" \-H "X-API-Key: your-key"# L2: Full skill documentation-curl -X GET "http://localhost:1933/api/v1/content/read?uri=viking://agent/skills/search-web/" \+curl -X GET "http://localhost:1933/api/v1/content/read?uri=viking://user/skills/search-web/" \-H "X-API-Key: your-key"```@@ -473,7 +473,7 @@ curl -X GET "http://localhost:1933/api/v1/content/read?uri=viking://agent/skills# Semantic search for skillsresults = client.find("search the internet",- target_uri="viking://agent/skills/",+ target_uri="viking://user/skills/",limit=5)@@ -491,7 +491,7 @@ curl -X POST http://localhost:1933/api/v1/search/find \-H "X-API-Key: your-key" \-d '{"query": "search the internet",- "target_uri": "viking://agent/skills/",+ "target_uri": "viking://user/skills/","limit": 5}'```@@ -501,13 +501,13 @@ curl -X POST http://localhost:1933/api/v1/search/find \**Python SDK**```python-client.rm("viking://agent/skills/old-skill/", recursive=True)+client.rm("viking://user/skills/old-skill/", recursive=True)```**HTTP API**```bash-curl -X DELETE "http://localhost:1933/api/v1/fs?uri=viking://agent/skills/old-skill/&recursive=true" \+curl -X DELETE "http://localhost:1933/api/v1/fs?uri=viking://user/skills/old-skill/&recursive=true" \-H "X-API-Key: your-key"```diff --git a/docs/en/api/05-sessions.md b/docs/en/api/05-sessions.mdindex ad73604e7..6a1ad90cb 100644--- a/docs/en/api/05-sessions.md+++ b/docs/en/api/05-sessions.md@@ -86,8 +86,7 @@ ov session new"session_id": "a1b2c3d4","user": {"account_id": "default",- "user_id": "alice",- "agent_id": "default"+ "user_id": "alice"}},"time": 0.1@@ -264,8 +263,7 @@ ov session get a1b2c3d4},"user": {"account_id": "default",- "user_id": "alice",- "agent_id": "default"+ "user_id": "alice"},"pending_tokens": 450}@@ -570,7 +568,7 @@ Add a message to the session. Supports two modes: simple text mode and Parts mod| parts | List[Part] | Conditional | - | List of message parts (Required for Python SDK; Optional for HTTP API, mutually exclusive with content) || content | str | Conditional | - | Message text content (HTTP API simple mode, mutually exclusive with parts) || created_at | str | No | None | Optional ISO 8601 timestamp to persist on the message |-| role_id | str | No | None | Optional explicit participant ID, server-derived if omitted |+| peer_id | str | No | None | Optional stable interaction peer identity |> **Note**: HTTP API supports two modes:> 1. **Simple mode**: Use `content` string (backward compatible)@@ -597,7 +595,7 @@ ContextPart(ToolPart(tool_id="call_123",tool_name="search_web",- skill_uri="viking://agent/skills/search-web/",+ skill_uri="viking://user/skills/search-web/",tool_input={"query": "OAuth best practices"},tool_output="",tool_status="pending" # "pending", "running", "completed", "error"@@ -838,7 +836,7 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/used \curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/used \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \- -d '{"skill": {"uri": "viking://agent/skills/search-web/", "input": {"query": "OAuth"}, "output": "Results...", "success": true}}'+ -d '{"skill": {"uri": "viking://user/skills/search-web/", "input": {"query": "OAuth"}, "output": "Results...", "success": true}}'```**Python SDK**@@ -858,7 +856,7 @@ await client.session_used(await client.session_used(session_id="a1b2c3d4",skill={- "uri": "viking://agent/skills/search-web/",+ "uri": "viking://user/skills/search-web/","input": {"query": "OAuth"},"output": "Results...","success": True@@ -1273,10 +1271,10 @@ An empty `memory_diff.json` (all counts zero) is written even when no memory ope| preferences | `user/memories/preferences/` | User preferences by topic || entities | `user/memories/entities/` | Important entities (people, projects) || events | `user/memories/events/` | Significant events |-| cases | `agent/memories/cases/` | Problem-solution cases |-| patterns | `agent/memories/patterns/` | Interaction patterns |-| tools | `agent/memories/tools/` | Tool usage knowledge and best practices |-| skills | `agent/memories/skills/` | Skill execution knowledge and workflow strategies |+| trajectories | `user/memories/trajectories/` | Reusable operation contracts |+| experiences | `user/memories/experiences/` | Reusable execution insights |+| tools | `user/memories/tools/` | Tool usage knowledge and best practices |+| skills | `user/memories/skills/` | Skill execution knowledge and workflow strategies |---diff --git a/docs/en/api/06-retrieval.md b/docs/en/api/06-retrieval.mdindex 58c9216b9..537d07a91 100644--- a/docs/en/api/06-retrieval.md+++ b/docs/en/api/06-retrieval.md@@ -56,6 +56,7 @@ The `find()` method performs pure vector similarity search for simple query scen|-----------|------|----------|---------|-------------|| query | str | Yes | - | Search query string || target_uri | str \| List[str] | No | "" | Limit search to specific URI prefix |+| peer_id | str | No | None | Stable interaction peer ID. When searching the default user memory scope, results include both current user memories and this peer's memories. CLI maps `--peer-id` to this field || node_limit | int | No | None | Maximum number of results || score_threshold | float | No | None | Minimum relevance score threshold || filter | Dict | No | None | Metadata filter |@@ -171,7 +172,7 @@ results = client.find(# Search only in skillsresults = client.find("web search",- target_uri="viking://agent/skills"+ target_uri="viking://user/skills")# Search in specific project@@ -273,6 +274,7 @@ The `search()` method adds session context understanding and intent analysis cap| target_uri | str \| List[str] | No | "" | Limit search to specific URI prefix || session | Session | No | None | Session for context-aware search (SDK) || session_id | str | No | None | Session ID for context-aware search (HTTP) |+| peer_id | str | No | None | Stable interaction peer ID. When searching the default user memory scope, results include both current user memories and this peer's memories. CLI maps `--peer-id` to this field || node_limit | int | No | None | Maximum number of results || score_threshold | float | No | None | Minimum relevance score threshold || filter | Dict | No | None | Metadata filter |diff --git a/docs/en/api/07-system.md b/docs/en/api/07-system.mdindex 19a75ec0a..da1cd70a1 100644--- a/docs/en/api/07-system.md+++ b/docs/en/api/07-system.md@@ -378,7 +378,7 @@ This API operates on existing `viking://...` content. It does not import new fil**Authentication**-- HTTP endpoint: requires root/admin access when authentication is enabled; root-key requests must include `X-OpenViking-Account`+- HTTP endpoint: requires admin/root role when authentication is enabled. In `api_key` mode, use an admin key for tenant content; a raw root key cannot access tenant-scoped data.- Python embedded mode: uses the current service context- Python HTTP client / CLI: sends the current authenticated identity@@ -397,14 +397,11 @@ The HTTP request body rejects unknown fields. `uri` may use OpenViking path vari- `viking://`- `viking://user`- `viking://user/<user_id>`-- `viking://agent`-- `viking://agent/<agent_id>`- `viking://resources`- `viking://resources/...`- `viking://user/<user_id>/memories/...`-- `viking://agent/<agent_id>/memories/...`-- `viking://agent/<agent_id>/skills`-- `viking://agent/<agent_id>/skills/<skill_name>`+- `viking://user/<user_id>/skills`+- `viking://user/<user_id>/skills/<skill_name>``viking://session/...` is not supported by `reindex()`.@@ -430,7 +427,7 @@ print(result)```pythonresult = client.reindex(- uri="viking://agent/default/skills",+ uri="viking://user/default/skills",mode="semantic_and_vectors",wait=False,)@@ -464,7 +461,7 @@ openviking reindex viking://resources --mode vectors_only``````bash-openviking reindex viking://agent/default/skills --mode semantic_and_vectors --wait false+openviking reindex viking://user/default/skills --mode semantic_and_vectors --wait false```**Synchronous response (`wait=true`)**@@ -526,7 +523,7 @@ Task records are persisted under `/local/{account_id}/_system/tasks/{user_id}/{t|-------|-------------|| status | `completed` for synchronous completion, `accepted` for background execution || uri | Requested URI after path-variable resolution |-| object_type | Inferred target type, such as `resource`, `skill`, `memory`, `user_namespace`, `agent_namespace`, `skill_namespace`, or `global_namespace` |+| object_type | Inferred target type, such as `resource`, `skill`, `memory`, `user_namespace`, `skill_namespace`, or `global_namespace` || mode | Effective reindex mode || scanned_records | Number of records or semantic sources considered || rebuilt_records | Number of vector records successfully rebuilt |@@ -540,7 +537,7 @@ Task records are persisted under `/local/{account_id}/_system/tasks/{user_id}/{t- Reindex is non-destructive. It uses rebuild/upsert behavior and does not require dropping the vector collection first.- `viking://` reindex fans out to supported top-level namespaces and excludes `session`.-- Namespace reindex operations such as `viking://user` or `viking://agent/default` propagate to their supported child content types.+- Namespace reindex operations such as `viking://user` propagate to supported child content types.- `vectors_only` is the right mode when only the embedding model or vector index needs to be refreshed.- `semantic_and_vectors` is the right mode when semantic artifacts themselves must be regenerated before re-vectorization.- Only one reindex task can run for the same URI and owner at a time. A concurrent request for the same target returns a conflict.diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.mdindex ff123d9e1..ab4f24337 100644--- a/docs/en/api/08-admin.md+++ b/docs/en/api/08-admin.md@@ -22,7 +22,7 @@ For `/api/v1/admin/*`, trusted mode also permits requests with no explicit ident| Create/delete workspace | Y | N | N || List workspaces | Y | N | N || Register/remove users | Y | Y (own account) | N |-| List agent namespaces | Y | Y (own account) | N |+| List agents (deprecated, returns empty list) | Y | Y (own account) | N || Regenerate user key | Y | Y (own account) | N || Change user role | Y | N | N |@@ -82,12 +82,10 @@ Create a new workspace with its first admin user.|-----------|------|----------|---------|-------------|| account_id | str | Yes | - | Workspace ID || admin_user_id | str | Yes | - | First admin user ID |-| isolate_user_scope_by_agent | bool | No | false | Further isolate user scope by agent |-| isolate_agent_scope_by_user | bool | No | false | Further isolate agent scope by user |**Notes:**- In `trusted` mode, `user_key` is omitted from the response-- `isolate_user_scope_by_agent` and `isolate_agent_scope_by_user` are only available via HTTP API, not in Python SDK or CLI+- Account-level namespace isolation settings are no longer supported. User memory uses user-scoped namespaces, and one-to-many external participants are represented with `peer_id`.#### 3. Usage Examples@@ -103,9 +101,7 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \-H "X-API-Key: <root-key>" \-d '{"account_id": "acme",- "admin_user_id": "alice",- "isolate_user_scope_by_agent": true,- "isolate_agent_scope_by_user": false+ "admin_user_id": "alice"}'```@@ -135,9 +131,7 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \-H "X-OpenViking-User: gateway-admin" \-d '{"account_id": "acme",- "admin_user_id": "alice",- "isolate_user_scope_by_agent": true,- "isolate_agent_scope_by_user": false+ "admin_user_id": "alice"}'```@@ -182,9 +176,7 @@ ov --sudo admin create-account acme --admin alice"result": {"account_id": "acme","admin_user_id": "alice",- "user_key": "7f3a9c1e...",- "isolate_user_scope_by_agent": true,- "isolate_agent_scope_by_user": false+ "user_key": "7f3a9c1e..."},"time": 0.1}@@ -512,74 +504,6 @@ ov --sudo admin list-users acme}```------### list_agents--#### 1. API Implementation Overview--List agent namespaces that exist under a workspace. This is an admin discovery API; it does not change normal `viking://agent/...` filesystem semantics.--**Processing Flow:**-1. Verify requester has ROOT privileges or is an ADMIN of the account-2. Verify the account exists-3. Scan the account's `viking://agent` namespace root-4. Return sorted agent namespace entries--**Code Entry Points:**-- `openviking/server/routers/admin.py:list_agents` - HTTP route-- `crates/ov_cli/src/client.rs:HttpClient.admin_list_agents` - CLI HTTP client-- `crates/ov_cli/src/commands/admin.rs:list_agents` - CLI command--#### 2. Interface and Parameters--**Parameters**--| Parameter | Type | Required | Default | Description |-|-----------|------|----------|---------|-------------|-| account_id | str | Yes | - | Workspace ID |--**Notes:**-- ROOT can list agents in any account-- ADMIN can only list agents in their own account-- USER cannot call this API-- The result lists agent namespaces that exist in storage. A new account includes the initialized `default` agent namespace.--#### 3. Usage Examples--**HTTP API**--```-GET /api/v1/admin/accounts/{account_id}/agents-```--```bash-curl -X GET http://localhost:1933/api/v1/admin/accounts/acme/agents \- -H "X-API-Key: <root-or-admin-key>"-```--**CLI**--```bash-# Either ROOT or account ADMIN can execute-# If using regular user's api_key who is an ADMIN of acme:-ov admin list-agents acme-# If using root_api_key (--sudo):-ov --sudo admin list-agents acme-```--**Response Example**--```json-{- "status": "ok",- "result": [- {"agent_id": "default", "uri": "viking://agent/default"},- {"agent_id": "openclaw", "uri": "viking://agent/openclaw"}- ],- "time": 0.1-}-```---diff --git a/docs/en/concepts/02-context-types.md b/docs/en/concepts/02-context-types.mdindex 18454cb5a..71cc3925a 100644--- a/docs/en/concepts/02-context-types.md+++ b/docs/en/concepts/02-context-types.md@@ -50,7 +50,7 @@ Memories are divided into user memories and Agent memories, representing learned- **Agent-driven**: Memory information actively extracted and recorded by Agent- **Dynamic updates**: Continuously updated from interactions by Agent-- **Personalized**: Learned for specific users or specific Agents+- **Personalized**: Learned for specific users and stable peers### 8 Categories@@ -60,10 +60,10 @@ Memories are divided into user memories and Agent memories, representing learned| **preferences** | `user/memories/preferences/` | User preferences by topic | ✅ Appendable || **entities** | `user/memories/entities/` | Entity memories (people, projects) | ✅ Appendable || **events** | `user/memories/events/` | Event records (decisions, milestones) | ❌ No update |-| **cases** | `agent/memories/cases/` | Learned cases | ❌ No update |-| **patterns** | `agent/memories/patterns/` | Learned patterns | ✅ Mergeable |-| **tools** | `agent/memories/tools/` | Tool usage knowledge and best practices | ✅ Mergeable |-| **skills** | `agent/memories/skills/` | Skill execution knowledge and workflow strategies | ✅ Mergeable |+| **trajectories** | `user/memories/trajectories/` | Reusable operation contracts | ❌ No update |+| **experiences** | `user/memories/experiences/` | Reusable execution insights | ✅ Mergeable |+| **tools** | `user/memories/tools/` | Tool usage knowledge and best practices | ✅ Mergeable |+| **skills** | `user/memories/skills/` | Skill execution knowledge and workflow strategies | ✅ Mergeable |### Usage@@ -94,7 +94,7 @@ Skills are capabilities that Agents can invoke, such as current Skills, MCP, etc### Storage Location```-viking://agent/skills/{skill-name}/+viking://user/skills/{skill-name}/├── .abstract.md # L0: Short description├── SKILL.md # L1: Detailed overview└── scripts # L2: Full definition@@ -113,7 +113,7 @@ await client.add_skill({# Search skillsresults = await client.find("web search",- target_uri="viking://agent/skills/"+ target_uri="viking://user/skills/")```diff --git a/docs/en/concepts/04-viking-uri.md b/docs/en/concepts/04-viking-uri.mdindex 50d1477ed..e2ce9dcfe 100644--- a/docs/en/concepts/04-viking-uri.md+++ b/docs/en/concepts/04-viking-uri.md@@ -87,22 +87,19 @@ viking://user/memories/entities/ # Entity memoriesviking://user/memories/events/ # Event memories```-### Agent Data+### User Skills and Memories```-viking://agent/ # Agent root-viking://agent/skills/ # All skills-viking://agent/skills/search-web # Specific skill-viking://agent/memories/ # Agent memories-viking://agent/memories/cases/ # Learned cases-viking://agent/memories/patterns/ # Learned patterns-viking://agent/instructions/ # Agent instructions+viking://user/skills/ # Current user's skills+viking://user/skills/search-web # Specific skill+viking://user/memories/ # Current user's memories+viking://user/memories/cases/ # Learned cases+viking://user/memories/patterns/ # Learned patterns```-The short `viking://user/...` and `viking://agent/...` forms above are-relative to the current request identity. OpenViking expands them internally to-explicit namespace paths such as `viking://user/{user_id}/...` and-`viking://agent/{agent_id}/...` before storage and retrieval.+The short `viking://user/...` form is relative to the current request identity.+OpenViking expands it internally to explicit namespace paths such as+`viking://user/{user_id}/...` before storage and retrieval.### Session Data@@ -205,32 +202,13 @@ viking://│ ├── entities/ # Each independent│ └── events/ # Each independent│-├── agent/{agent_id}/ # Agent root when isolate_agent_scope_by_user = false-│ ├── skills/ # Skill definitions-│ ├── memories/-│ │ ├── cases/-│ │ └── patterns/-│ ├── workspaces/-│ └── instructions/-│-├── agent/{agent_id}/user/{user_id}/ # Agent root when isolate_agent_scope_by_user = true-│ ├── skills/-│ ├── memories/-│ ├── workspaces/-│ └── instructions/-│└── session/{user_space}/{session_id}/├── messages/├── tools/└── history/```-Agent namespace shape is controlled by per-account namespace policy:--- `isolate_agent_scope_by_user = false`: `viking://agent/{agent_id}/...`-- `isolate_agent_scope_by_user = true`: `viking://agent/{agent_id}/user/{user_id}/...`--`memory.agent_scope_mode` is deprecated and ignored.+`viking://agent/...` is deprecated and rejected by current namespace resolution.## URI Operations@@ -276,7 +254,7 @@ results = client.find(# Search only in skillsresults = client.find("web search",- target_uri="viking://agent/skills/"+ target_uri="viking://user/skills/")```@@ -325,8 +303,8 @@ Each directory may contain special files:# Add resources only to resources scopeawait client.add_resource(url, to="viking://resources/project/")-# Skills go to agent scope-await client.add_skill(skill) # Automatically to viking://agent/skills/+# Skills go to user scope+await client.add_skill(skill) # Automatically to viking://user/skills/```## Related Documentsdiff --git a/docs/en/concepts/05-storage.md b/docs/en/concepts/05-storage.mdindex e3e06d51b..11ad4f5c6 100644--- a/docs/en/concepts/05-storage.md+++ b/docs/en/concepts/05-storage.md@@ -43,7 +43,7 @@ VikingFS is the unified URI abstraction layer that hides underlying storage deta```viking://resources/docs/auth → /local/{account_id}/resources/docs/authviking://user/memories → /local/{account_id}/user/{user_id}/memories-viking://agent/skills → /local/{account_id}/agent/{agent_id}/skills+viking://user/skills → /local/{account_id}/user/{user_id}/skills```### Core APIdiff --git a/docs/en/concepts/06-extraction.md b/docs/en/concepts/06-extraction.mdindex 242e07ccd..20e2027fa 100644--- a/docs/en/concepts/06-extraction.md+++ b/docs/en/concepts/06-extraction.md@@ -73,7 +73,7 @@ TreeBuilder moves temp directory to AGFS and queues semantic processing.```pythonbuilding_tree = tree_builder.finalize_from_temp(temp_dir_path="viking://temp/abc123",- scope="resources", # resources/user/agent+ scope="resources", # resources/user)```@@ -91,7 +91,6 @@ building_tree = tree_builder.finalize_from_temp(|-------|----------|| resources | `viking://resources` || user | `viking://user` |-| agent | `viking://agent` |## SemanticQueue@@ -194,8 +193,8 @@ openviking/parse/parsers/code/ast/| Phase | Resource | Memory | Skill ||-------|----------|--------|-------|| **Parser** | Common flow | Common flow | Common flow |-| **Base URI** | `viking://resources` | `viking://user/memories` | `viking://agent/skills` |-| **TreeBuilder scope** | resources | user/agent | agent |+| **Base URI** | `viking://resources` | `viking://user/memories` | `viking://user/skills` |+| **TreeBuilder scope** | resources | user | user || **SemanticMsg type** | resource | memory | skill |### Resource Extraction@@ -219,7 +218,7 @@ await client.add_skill({"content": "# search-web\\n..."})-# Flow: Direct write to viking://agent/skills/{name}/ → SemanticQueue+# Flow: Direct write to viking://user/skills/{name}/ → SemanticQueue```### Memory Extractiondiff --git a/docs/en/concepts/07-retrieval.md b/docs/en/concepts/07-retrieval.mdindex ad54f6bb7..8edd4d747 100644--- a/docs/en/concepts/07-retrieval.md+++ b/docs/en/concepts/07-retrieval.md@@ -92,9 +92,9 @@ Step 5: Convert to MatchedContext| context_type | Root Directories ||--------------|------------------|-| MEMORY | `viking://user/memories`, `viking://agent/memories` |+| MEMORY | `viking://user/memories` || RESOURCE | `viking://resources` |-| SKILL | `viking://agent/skills` |+| SKILL | `viking://user/skills` |### Recursive Search Algorithmdiff --git a/docs/en/concepts/08-session.md b/docs/en/concepts/08-session.mdindex b4a88ecc5..9da0c445b 100644--- a/docs/en/concepts/08-session.md+++ b/docs/en/concepts/08-session.md@@ -48,7 +48,7 @@ session.used(contexts=["viking://user/memories/profile.md"])# Record used skillsession.used(skill={- "uri": "viking://agent/skills/code-search",+ "uri": "viking://user/skills/code-search","input": "search config","output": "found 3 files","success": True@@ -244,7 +244,7 @@ viking://user/memories/├── entities/└── events/-viking://agent/memories/+viking://user/memories/├── cases/├── patterns/├── tools/diff --git a/docs/en/concepts/11-multi-tenant.md b/docs/en/concepts/11-multi-tenant.mdindex d0b922bc5..07cd2d120 100644--- a/docs/en/concepts/11-multi-tenant.md+++ b/docs/en/concepts/11-multi-tenant.md@@ -1,11 +1,11 @@# Multi-Tenant-OpenViking multi-tenancy does not mean "deploy one isolated server per team." Instead, a single OpenViking Server uses three identity boundaries, `account`, `user`, and `agent`, to control sharing and isolation.+OpenViking multi-tenancy does not mean "deploy one isolated server per team." Instead, a single OpenViking Server uses `account` and `user` identity boundaries to control sharing and isolation.This model fits two common scenarios:- Multiple teams or customers share one OpenViking service, but their data must stay isolated-- Multiple users and multiple agents inside one team need shared resources but isolated memories+- Multiple users inside one team need shared resources but isolated memories## What It Enables@@ -15,7 +15,6 @@ With multi-tenancy enabled, you can:- Isolate different teams with `account`- Share `resources` within the same `account`- Isolate user memories and sessions with `user`-- Further separate agent memories, skills, and instructions with `agent_id`- Manage permissions with ROOT / ADMIN / USER roles- Support different integration patterns such as OpenClaw plugin, Vikingbot, CLI, and HTTP SDKs@@ -27,7 +26,7 @@ With multi-tenancy enabled, you can:- Data is isolated across different `account` values by default- ROOT can create and delete `account`s-- `resources`, `user`, `agent`, and `session` all live inside an `account`+- `resources`, `user`, and `session` all live inside an `account`### `user_id`@@ -37,21 +36,13 @@ With multi-tenancy enabled, you can:- A normal user can only access its own user space- An admin can manage users inside the same `account`-### `agent_id`--`agent_id` separates agent-level space.--- Agent URI shape is controlled by per-account namespace policy-- `isolate_agent_scope_by_user = false` means `viking://agent/{agent_id}/...`-- `isolate_agent_scope_by_user = true` means `viking://agent/{agent_id}/user/{user_id}/...`-### Roles| Role | Scope | Typical capabilities ||------|-------|----------------------|| ROOT | Global | Create/delete accounts, cross-tenant access, user management || ADMIN | Single account | Manage users in the same account, regenerate user keys |-| USER | Single account | Access its own user/agent/session data and shared resources in the same account |+| USER | Single account | Access its own user/peer/session data and shared resources in the same account |## Authentication Modes@@ -73,7 +64,7 @@ Once `server.root_api_key` is configured, OpenViking enters formal multi-tenantIf `auth_mode = "api_key"` and `root_api_key` is not configured, the server runs in dev mode:- All requests are treated as ROOT-- The default identity is `default/default/default`+- The default identity is `default/default`- This is only allowed on localhost## Sharing and Isolation Boundaries@@ -84,7 +75,6 @@ If `auth_mode = "api_key"` and `root_api_key` is not configured, the server runs|-----------|------------------------|---------------------------|----------------------------|| `resources` | No | Yes | account || `user` | No | No | user |-| `agent` | No | Depends on account namespace policy | Default: `agent` || `session` | No | No | user / session |### Storage Layer@@ -94,7 +84,6 @@ For users, URIs still look like normal `viking://...` paths:```textviking://resources/project-a/viking://user/alice/memories/-viking://agent/91f3ab12cd34/memories/```But the underlying storage automatically gains an account prefix:@@ -102,10 +91,9 @@ But the underlying storage automatically gains an account prefix:```text/local/{account_id}/resources/project-a//local/{account_id}/user/alice/memories/-/local/{account_id}/agent/91f3ab12cd34/memories/```-So multi-tenant isolation does not rely on a special public URI format. It relies on request context, `account_id`, `user_id`, and `agent_id`, applied consistently through the stack.+So multi-tenant isolation does not rely on a special public URI format. It relies on request context, `account_id` and `user_id`, applied consistently through the stack.### Retrieval Layer@@ -113,7 +101,7 @@ Semantic retrieval is tenant-aware as well:- Non-ROOT requests are automatically filtered by `account_id`- `resources` can include account-shared resources-- `memory` and `skill` are further filtered by the current `user space` and `agent space`+- `memory` and `skill` are further filtered by the current `user space`This keeps "what you can search" aligned with "what you can read."@@ -160,34 +148,40 @@ For normal reads, writes, searches, and session commits, prefer a user key:```bashcurl http://localhost:1933/api/v1/fs/ls?uri=viking:// \- -H "X-API-Key: <bob-user-key>" \- -H "X-OpenViking-Agent: coding-agent"+ -H "X-API-Key: <bob-user-key>"```This lets the server resolve identity directly from the key, without extra tenant headers.-### 5. Only ROOT uses explicit tenant headers for tenant-scoped data APIs+### 5. Data API identity comes from the user or admin key-ROOT does not need tenant headers for Admin APIs, but it does need them for tenant-scoped data APIs such as `ls`, `find`, and `sessions`:+In `api_key` mode, tenant-scoped data APIs such as `ls`, `find`, and `sessions`+resolve the effective account and user from the API key itself. Do not send+`X-OpenViking-Account` or `X-OpenViking-User` in this mode; header-based identity+assertion belongs to trusted mode.++An `ADMIN` key can call data APIs as its own account/user:```bashcurl http://localhost:1933/api/v1/fs/ls?uri=viking:// \- -H "X-API-Key: <root-key>" \- -H "X-OpenViking-Account: acme" \- -H "X-OpenViking-User: alice" \- -H "X-OpenViking-Agent: coding-agent"+ -H "X-API-Key: <admin-user-key>"```+A `ROOT` key is for Admin APIs and selected system/monitoring APIs. It cannot+access tenant-scoped data APIs in `api_key` mode because it is not bound to a+tenant user. Use a user/admin key for data access, or trusted mode for upstream+identity assertion.+## Integration Patterns### OpenClaw Plugin 2.0: one instance uses one user keyThe current OpenClaw plugin follows a "plugin holds one user identity" model:-- Remote mode config is `baseUrl + apiKey + agent_prefix`+- Remote mode config is `baseUrl + apiKey`, with optional `peer_role` / `peer_prefix`- `apiKey` should normally be a user key- The server resolves `account_id` and `user_id` from that user key-- The plugin explicitly passes `X-OpenViking-Agent`+- The plugin keeps OpenClaw agent identity in peer/session metadata, not tenant headersTypical config:@@ -195,25 +189,28 @@ Typical config:openclaw config set plugins.entries.openviking.config.mode remoteopenclaw config set plugins.entries.openviking.config.baseUrl "http://your-server:1933"openclaw config set plugins.entries.openviking.config.apiKey "<user-api-key>"-openclaw config set plugins.entries.openviking.config.agent_prefix "<agent-prefix>"+openclaw config set plugins.entries.openviking.config.peer_role assistant+openclaw config set plugins.entries.openviking.config.peer_prefix "<peer-prefix>"```Characteristics of this model:- Simple integration, because the plugin does not manage account/user lifecycle- Best for "one OpenClaw instance maps to one OpenViking user identity"-- `agent_prefix` distinguishes different OpenClaw instances or agent roles-- `resources` can be shared inside the same account, while `user` and `agent` memory stay identity-scoped+- `peer_prefix` distinguishes OpenClaw runtime identities when building peer/session metadata+- `resources` can be shared inside the same account, while user memory stays user-scoped### Why the OpenClaw plugin usually does not set `account` / `user`In `api_key` mode, a user key is already enough to express identity:- `account` and `user` are resolved server-side from the key-- The plugin only needs to provide `agent_prefix`-- Internally, the plugin derives default `user` and `agent` memory scopes from the runtime identity+- The plugin can provide `peer_prefix` for runtime identity labeling+- Internally, the plugin writes user-scoped memory and uses `peer_id` for per-message speaker identity-If you give the plugin a root key directly, normal tenant-scoped data APIs will lack `X-OpenViking-Account` and `X-OpenViking-User`, so that is not a good default for day-to-day access.+If you give the plugin a root key directly, normal tenant-scoped data APIs will+not have a key-bound tenant user, so that is not a good default for day-to-day+access.### Vikingbot: root key manages many end users@@ -266,15 +263,15 @@ The root key is mainly for:- Regenerating keys- Operations and diagnostics-Normal application traffic should prefer user keys.+Normal application traffic should use user keys or admin keys, depending on the+caller identity it should run as.-### 2. `agentId` does not define the tenant+### 2. `peer_id` does not define the tenant-`agentId` only defines the agent-level space.+`peer_id` identifies the message peer in shared conversations. It does not create a tenant or filesystem namespace.- The tenant boundary is `account_id`- The user boundary is `user_id`-- The agent boundary is `agent_id`### 3. No `root_api_key` does not mean "formal single-tenant production mode"@@ -291,7 +288,7 @@ That is only dev mode:## Related Documentation- [Authentication](../guides/04-authentication.md) - Auth modes, headers, and key rules-- [Configuration](../guides/01-configuration.md) - `root_api_key`, `auth_mode`, and `agent_id`+- [Configuration](../guides/01-configuration.md) - `root_api_key` and `auth_mode`- [Admin API](../api/08-admin.md) - Admin API reference- [API Overview](../api/01-overview.md) - CLI and HTTP connection patterns- [Data Encryption](./10-encryption.md) - At-rest encryption in multi-tenant deploymentsdiff --git a/docs/en/concepts/12-metrics.md b/docs/en/concepts/12-metrics.mdindex 2a851e628..db4449d67 100644--- a/docs/en/concepts/12-metrics.md+++ b/docs/en/concepts/12-metrics.md@@ -499,7 +499,7 @@ Example:## Related Documentation- [Architecture Overview](./01-architecture.md) - overall OpenViking architecture-- [Multi-Tenant](./11-multi-tenant.md) - `account/user/agent` isolation model+- [Multi-Tenant](./11-multi-tenant.md) - `account/user/peer` isolation model- [Data Encryption](./10-encryption.md) - storage-layer encryption and isolation- [Metrics API](../api/09-metrics.md) - `/metrics` endpoint usage- [VikingBot Feedback Observability Design](../../../bot/docs/vikingbot-feedback-observability-design.md) - feedback observability design background and rollout plan (Chinese)diff --git a/docs/en/concepts/13-privacy.md b/docs/en/concepts/13-privacy.mdindex a4e4c7d8f..119e54827 100644--- a/docs/en/concepts/13-privacy.md+++ b/docs/en/concepts/13-privacy.md@@ -91,10 +91,10 @@ fs.read(uri)### URI Matching-Current matching is suffix-based: `/skills/{name}/SKILL.md`, so it supports:+Current matching is suffix-based: `/skills/{name}/SKILL.md`, so it supports user-scoped skill paths such as:-- `viking://agent/skills/{name}/SKILL.md`-- `viking://agent/{agent_id}/skills/{name}/SKILL.md`+- `viking://user/skills/{name}/SKILL.md`+- `viking://user/{user_id}/skills/{name}/SKILL.md`### restore Rules@@ -133,7 +133,7 @@ openviking privacy list skillopenviking privacy skill <target_key>openviking privacy upsert skill <target_key> --values-json '{"api_key":"..."}'openviking privacy activate skill <target_key> <version>-openviking read viking://agent/default/skills/<target_key>/SKILL.md+openviking read viking://user/default/skills/<target_key>/SKILL.md```---diff --git a/docs/en/getting-started/03-quickstart-server.md b/docs/en/getting-started/03-quickstart-server.mdindex 280694a93..9d0fc786c 100644--- a/docs/en/getting-started/03-quickstart-server.md+++ b/docs/en/getting-started/03-quickstart-server.md@@ -75,7 +75,6 @@ import openviking as ovclient = ov.SyncHTTPClient(url="http://localhost:1933",api_key="<user-key>",- agent_id="my-agent", # optional)```@@ -83,21 +82,22 @@ client = ov.SyncHTTPClient(**Administrative operations: use a `root_key`**-`root_key` is for management operations (creating accounts, system status, etc.). To access tenant-scoped APIs with `root_key`, you **must** also pass `account` and `user`:+`root_key` is for management operations (creating accounts, system status, etc.).+Tenant-scoped data APIs such as `add_resource`, `find`, and sessions need a key+that is bound to an account/user, such as a user key or admin key:```pythonimport openviking as ovclient = ov.SyncHTTPClient(url="http://localhost:1933",- api_key="<root-key>",- account="acme", # required: target tenant- user="alice", # required: target user+ api_key="<user-or-admin-key>",)```-> ⚠️ Using `root_key` for `add_resource`, `find`, etc. without `account`/`user` will return:-> `ROOT requests to tenant-scoped APIs must include X-OpenViking-Account and X-OpenViking-User headers`+> Using `root_key` for tenant-scoped data APIs in `api_key` mode returns+> `PERMISSION_DENIED`. Use a user/admin key for data access, or trusted mode for+> upstream identity assertion.See [Authentication](../guides/04-authentication.md) for details (trusted mode, CLI config, etc.).diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.mdindex 08fb143ad..975e2810c 100644--- a/docs/en/guides/01-configuration.md+++ b/docs/en/guides/01-configuration.md@@ -1156,7 +1156,7 @@ For memory-related settings, add a `memory` section in `ov.conf`:{"memory": {"version": "v2",- "agent_scope_mode": "user+agent"+ "agent_memory_enabled": false}}```@@ -1164,9 +1164,7 @@ For memory-related settings, add a `memory` section in `ov.conf`:| Field | Description | Default ||-------|-------------|---------|| `version` | Memory implementation version. Only `"v2"` is supported (legacy `"v1"` removed in #2264 — passing `"v1"` now raises a `ValueError` at config load). | `"v2"` |-| `agent_scope_mode` | Deprecated and ignored. Kept only for backward compatibility with older `ov.conf` files. Agent/user namespace behavior is now controlled by per-account namespace policy. | `"user+agent"` |--`agent_scope_mode` no longer changes namespace behavior. The server now uses account-level namespace policy to choose between `viking://agent/{agent_id}/...` and `viking://agent/{agent_id}/user/{user_id}/...`.+| `agent_memory_enabled` | Enables trajectory/experience memory extraction after user-memory extraction. | `false` |### ovcli.conf@@ -1180,9 +1178,6 @@ Config file for the HTTP client (`SyncHTTPClient` / `AsyncHTTPClient`) and CLI t{"url": "http://localhost:1933","api_key": "your-secret-key",- "account": "acme",- "user": "alice",- "agent_id": "my-agent","profile": false,"upload": {"mode": "local",@@ -1197,9 +1192,8 @@ Config file for the HTTP client (`SyncHTTPClient` / `AsyncHTTPClient`) and CLI t|-------|-------------|---------|| `url` | Server address | (required) || `api_key` | API key for authentication (root key or user key) | `null` (no auth) |-| `account` | Default account sent as `X-OpenViking-Account` | `null` |-| `user` | Default user sent as `X-OpenViking-User` | `null` |-| `agent_id` | Agent identifier for agent space isolation | `null` |+| `account` | Optional trusted-mode account identity header value | `null` |+| `user` | Optional trusted-mode user identity header value | `null` || `profile` | Whether to append `profile=1` to HTTP requests by default. Applies to both the Python HTTP client and the `ov` CLI; `ov --profile` can enable it per invocation. Actual effect still depends on the server enabling `server.profile_enabled`. | `false` || `upload.ignore_dirs` | Default directory ignore list for `add-resource` (CSV) | `null` || `upload.include` | Default include patterns for `add-resource` (CSV) | `null` |@@ -1208,10 +1202,10 @@ Config file for the HTTP client (`SyncHTTPClient` / `AsyncHTTPClient`) and CLI tLocal directory uploads respect `.gitignore` files (root and nested). `ignore_dirs/include/exclude` apply on top of that.-CLI flags can override these identity fields per command:+For trusted gateway deployments, CLI flags can override these identity fields per command:```bash-openviking --account acme --user alice --agent-id assistant-2 ls viking://+openviking --account acme --user alice ls viking://```For `add-resource`, upload filter flags are merged additively with `ovcli.conf` defaults:diff --git a/docs/en/guides/03-deployment.md b/docs/en/guides/03-deployment.mdindex 60200e01d..19bbe1788 100644--- a/docs/en/guides/03-deployment.md+++ b/docs/en/guides/03-deployment.md@@ -143,7 +143,7 @@ sudo journalctl -u openviking.service -f```pythonimport openviking as ov-client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key", agent_id="my-agent")+client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")client.initialize()results = client.find("how to use openviking")diff --git a/docs/en/guides/04-authentication.md b/docs/en/guides/04-authentication.mdindex 75f92feff..a6b6dc0f3 100644--- a/docs/en/guides/04-authentication.md+++ b/docs/en/guides/04-authentication.md@@ -8,8 +8,8 @@ OpenViking uses a two-layer API key system:| Key Type | Created By | Role | Purpose ||----------|-----------|------|---------|-| Root Key | Server config (`root_api_key`) | ROOT | Full access + admin operations |-| User Key | Admin API | ADMIN or USER | Per-account access |+| Root Key | Server config (`root_api_key`) | ROOT | Account management + selected system/monitoring operations |+| User Key | Admin API | ADMIN or USER | Per-account data access; ADMIN can also manage users in its account |All API keys are plain random tokens with no embedded identity. The server resolves identity by first comparing against the root key, then looking up the user key index.@@ -17,8 +17,8 @@ All API keys are plain random tokens with no embedded identity. The server resol| Mode | `server.auth_mode` | Identity Source | Typical Use ||------|--------------------|-----------------|-------------|-| API key mode | `"api_key"` | API key, with optional tenant headers for root requests | Standard multi-tenant deployment |-| Trusted mode | `"trusted"` | `X-OpenViking-Account` / `X-OpenViking-User` / optional `X-OpenViking-Agent`, plus `root_api_key` on non-localhost deployments. Role is looked up from APIKeyManager if the user exists. | Behind a trusted gateway or internal network boundary |+| API key mode | `"api_key"` | API key. Data ownership is resolved from the user/admin key. | Standard multi-tenant deployment |+| Trusted mode | `"trusted"` | `X-OpenViking-Account` / `X-OpenViking-User`, plus `root_api_key` on non-localhost deployments. Role is looked up from APIKeyManager if the user exists. | Behind a trusted gateway or internal network boundary || Dev mode | `"dev"` | No authentication, always ROOT | Local development only |If `auth_mode` is not explicitly configured:@@ -96,9 +96,7 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \-H "Content-Type: application/json" \-d '{"account_id": "acme",- "admin_user_id": "alice",- "isolate_user_scope_by_agent": true,- "isolate_agent_scope_by_user": false+ "admin_user_id": "alice"}'```@@ -128,7 +126,6 @@ import openviking as ovclient = ov.SyncHTTPClient(url="http://localhost:1933",api_key="<user-key>",- agent_id="my-agent")```@@ -137,19 +134,18 @@ client = ov.SyncHTTPClient(```json{"url": "http://localhost:1933",- "api_key": "<user-key>",- "account": "acme",- "user": "alice",- "agent_id": "my-agent"+ "api_key": "<user-key>"}```-When you use a regular user key, `account` and `user` are optional because the server can derive them from the key. They are recommended when you use `trusted` mode or a root key against tenant-scoped APIs.+When you use a user key or admin key, the server derives `account` and `user`+from the key. Do not send `X-OpenViking-Account` / `X-OpenViking-User` in+`api_key` mode; those identity headers are accepted only in `trusted` mode.**CLI override flags**```bash-openviking --account acme --user alice --agent-id my-agent ls viking://+openviking ls viking://```### Using --sudo with Root API Key@@ -160,10 +156,7 @@ The CLI supports configuring both `api_key` (for regular user operations) and `r{"url": "http://localhost:1933","api_key": "<user-key>",- "root_api_key": "<root-key>",- "account": "acme",- "user": "alice",- "agent_id": "my-agent"+ "root_api_key": "<root-key>"}```@@ -173,54 +166,37 @@ When you need to perform admin commands (`admin`, `system`, `reindex`), use the# List all accounts (requires root privileges)ov --sudo admin list-accounts-# Reindex content-ov --sudo reindex viking://-# System commandsov --sudo system status```The `--sudo` flag:-- Only works with admin commands: `admin`, `system`, `reindex`+- Only works with management/system commands: `admin`, `system`- Will error if used with non-admin commands- Will error if `root_api_key` is not configured in `ovcli.conf`- Uses `root_api_key` instead of `api_key` for the request-### Accessing Tenant Data with Root Key+### Tenant Data Access-When using the root key to access tenant-scoped data APIs (e.g. `ls`, `find`, `sessions`), you must specify the target account and user. The server will reject the request otherwise. Admin API and system status endpoints are not affected.+Tenant-scoped data APIs (for example `ls`, `find`, resources, and sessions)+must use a key that is bound to an account/user in `api_key` mode. That can be+a `USER` key or an `ADMIN` key; an `ADMIN` key accesses data as its own user and+cannot switch identity with `X-OpenViking-Account` / `X-OpenViking-User`.-**curl**--```bash-curl http://localhost:1933/api/v1/fs/ls?uri=viking:// \- -H "X-API-Key: your-secret-root-key" \- -H "X-OpenViking-Account: acme" \- -H "X-OpenViking-User: alice"-```--**Python SDK**--```python-import openviking as ov--client = ov.SyncHTTPClient(- url="http://localhost:1933",- api_key="your-secret-root-key",- account="acme",- user="alice",-)-```+A `ROOT` key is not bound to a tenant user, so it cannot access tenant-scoped+data APIs in `api_key` mode. If a deployment needs an upstream gateway to assert+`account` / `user`, use `trusted` mode instead of passing identity headers with a+root key.**ovcli.conf**```json{"url": "http://localhost:1933",- "api_key": "your-secret-root-key",+ "auth_mode": "trusted",+ "api_key": "your-trusted-server-key","account": "acme",- "user": "alice",- "agent_id": "my-agent"+ "user": "alice"}```@@ -241,7 +217,7 @@ Rules in trusted mode:- Normal data access does not require user registration or user-key provisioning first.- `X-OpenViking-Account` and `X-OpenViking-User` are required on tenant-scoped requests.-- `X-OpenViking-Agent` is optional and defaults to `default`.+- Legacy agent identity headers are ignored by authentication. Use request-level `peer_id` for stable interaction peers in session memory and retrieval APIs.- `/api/v1/admin/*` is special: when no explicit identity is provided, trusted mode treats the request as ROOT. This is intended for trusted upstreams that authenticate only with the deployment's root API key.- Role is determined by looking up the account/user in APIKeyManager. If the user exists, their configured role is used; otherwise it defaults to `USER`.- Trusted identity comes from the headers, not from a user key. If `root_api_key` is configured, it still acts as proof that the caller is an approved trusted upstream.@@ -262,8 +238,7 @@ Implications:```bashcurl http://localhost:1933/api/v1/fs/ls?uri=viking:// \-H "X-OpenViking-Account: acme" \- -H "X-OpenViking-User: alice" \- -H "X-OpenViking-Agent: my-agent"+ -H "X-OpenViking-User: alice"```**Python SDK**@@ -275,7 +250,6 @@ client = ov.SyncHTTPClient(url="http://localhost:1933",account="acme",user="alice",- agent_id="my-agent",)```diff --git a/docs/en/guides/05-observability.md b/docs/en/guides/05-observability.mdindex 758760976..054b03df6 100644--- a/docs/en/guides/05-observability.md+++ b/docs/en/guides/05-observability.md@@ -135,7 +135,7 @@ Prerequisites:This TUI is useful for two kinds of inspection:-- checking what actually exists under `viking://resources`, `viking://user`, `viking://agent`, and `viking://session`+- checking what actually exists under `viking://resources`, `viking://user`, and `viking://session`- checking whether vector records for a URI were actually written, and how many there areCommon keys:diff --git a/docs/en/guides/06-mcp-integration.md b/docs/en/guides/06-mcp-integration.mdindex 5a855d44d..c7d65ad8d 100644--- a/docs/en/guides/06-mcp-integration.md+++ b/docs/en/guides/06-mcp-integration.md@@ -113,7 +113,7 @@ Once connected, OpenViking exposes 14 tools:| Tool | Description | Key Parameters ||------|-------------|----------------|-| `search` | Semantic search across memories, resources, and skills | `query`, `target_uri` (optional), `limit`, `min_score` |+| `search` | Semantic search across memories, resources, and skills | `query`, `target_uri` (optional), `peer_id` (optional), `limit`, `min_score` || `read` | Read one or more `viking://` URIs | `uris` (single string or array) || `list` | List entries under a `viking://` directory | `uri`, `recursive` (optional) || `store` | Store messages into long-term memory (triggers extraction) | `messages` (list of `{role, content}`) |diff --git a/docs/en/guides/09-ovpack.md b/docs/en/guides/09-ovpack.mdindex f2aced4e1..6e88063dc 100644--- a/docs/en/guides/09-ovpack.md+++ b/docs/en/guides/09-ovpack.md@@ -16,7 +16,6 @@ Regular `export/import` handles one package root:- `viking://resources/...`- `viking://user/...`-- `viking://agent/...`- `viking://session/...`Full migration uses the separate `backup/restore` flow. It packages public@@ -24,7 +23,6 @@ scope roots together:- `viking://resources`- `viking://user`-- `viking://agent`- `viking://session`Internal or runtime data such as `temp`, `queue`, `upload`, lock files, watch@@ -327,7 +325,7 @@ These fields are regenerated in the target environment and are not restoredfrom the package:```text-id, uri, account_id, owner_user_id, owner_agent_id, owner_space,+id, uri, account_id, owner_user_id, owner_space,created_at, updated_at, active_count```@@ -409,11 +407,11 @@ ov export viking://user/default/memories ./exports/user-memories.ovpackov import ./exports/user-memories.ovpack viking://user/default/ --on-conflict overwrite```-Agent memories:+User memories:```bash-ov export viking://agent/default/memories ./exports/agent-memories.ovpack-ov import ./exports/agent-memories.ovpack viking://agent/default/ --on-conflict overwrite+ov export viking://user/default/memories ./exports/agent-memories.ovpack+ov import ./exports/agent-memories.ovpack viking://user/default/ --on-conflict overwrite```Sessions restore file state only and do not trigger vectorization:diff --git a/docs/en/guides/10-prompt-guide.md b/docs/en/guides/10-prompt-guide.mdindex 320da22c0..ef98325be 100644--- a/docs/en/guides/10-prompt-guide.md+++ b/docs/en/guides/10-prompt-guide.md@@ -186,7 +186,7 @@ This category is mainly used to support retrieval or indexing workflows with rel### Memory-These YAML files define the structure of different memory types. They are not single-inference prompts. Together, they determine how user memories and agent memories are stored, updated, and used by later retrieval.+These YAML files define the structure of different memory types. They are not single-inference prompts. Together, they determine how user and peer memories are stored, updated, and used by later retrieval.- `cases`- Effective stage: case-memory persistence and update stagediff --git a/docs/images/agents/en/api.md b/docs/images/agents/en/api.mdindex 55a272aab..f06248348 100644--- a/docs/images/agents/en/api.md+++ b/docs/images/agents/en/api.md@@ -10,7 +10,6 @@ import requestsurl = "https://api.vikingdb.cn-beijing.volces.com/openviking"api_key = "[TODO]your-api-key"-agent_id = "[TODO]your-agent-id"file_path = Path("[TODO]your-file-path") # e.g. test.txtresource_to = "[TODO]your-resource-path" # e.g. viking://resources/test.txtreason = "[TODO]your-reason" # e.g. External API documentation@@ -19,7 +18,6 @@ reason = "[TODO]your-reason" # e.g. External API documentationheaders = {"Content-Type": "application/json","Authorization": "Bearer " + api_key,- "X-OpenViking-Agent": agent_id,}def post_json(path: str, payload: dict, timeout: float):@@ -33,7 +31,6 @@ with file_path.open("rb") as file:f"{url}/api/v1/resources/temp_upload",headers={"Authorization": "Bearer " + api_key,- "X-OpenViking-Agent": agent_id,},files={"file": (file_path.name, file, "application/octet-stream")},timeout=120.0,diff --git a/docs/images/agents/en/claude-code.md b/docs/images/agents/en/claude-code.mdindex c4b578caf..70990982c 100644--- a/docs/images/agents/en/claude-code.md+++ b/docs/images/agents/en/claude-code.md@@ -70,7 +70,7 @@ Configuration priority: environment variables > `ovcli.conf` > `ov.conf` > built| `OPENVIKING_MEMORY_ENABLED` | (auto) | Force enable or disable || `OPENVIKING_DEBUG` | `false` | Write logs to `~/.openviking/logs/cc-hooks.log` |-For multi-tenant deployments, set `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, and `OPENVIKING_AGENT_ID`. See the [plugin README](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#configuration) for the full environment variable list.+For multi-tenant deployments, set `OPENVIKING_ACCOUNT` and `OPENVIKING_USER`. See the [plugin README](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#configuration) for the full environment variable list.</details>diff --git a/docs/images/agents/en/sdk.md b/docs/images/agents/en/sdk.mdindex f5c777aae..6bedd2d56 100644--- a/docs/images/agents/en/sdk.md+++ b/docs/images/agents/en/sdk.md@@ -15,12 +15,10 @@ from openviking.client import SyncHTTPClienturl = "https://api.vikingdb.cn-beijing.volces.com/openviking"api_key = "[TODO]your-api-key"-agent_id = "[TODO]your-agent-id"client = SyncHTTPClient(url=url,api_key=api_key,- agent_id=agent_id,timeout=120.0,)client.initialize()diff --git a/docs/images/agents/zh/api.md b/docs/images/agents/zh/api.mdindex 507ec205a..692cc1ad0 100644--- a/docs/images/agents/zh/api.md+++ b/docs/images/agents/zh/api.md@@ -10,7 +10,6 @@ import requestsurl = "https://api.vikingdb.cn-beijing.volces.com/openviking"api_key = "[TODO]your-api-key"-agent_id = "[TODO]your-agent-id"file_path = Path("[TODO]your-file-path") # e.g. test.txtresource_to = "[TODO]your-resource-path" # e.g. viking://resources/test.txtreason = "[TODO]your-reason" # e.g. External API documentation@@ -19,7 +18,6 @@ reason = "[TODO]your-reason" # e.g. External API documentationheaders = {"Content-Type": "application/json","Authorization": "Bearer " + api_key,- "X-OpenViking-Agent": agent_id,}def post_json(path: str, payload: dict, timeout: float):@@ -34,7 +32,6 @@ with file_path.open("rb") as file:f"{url}/api/v1/resources/temp_upload",headers={"Authorization": "Bearer " + api_key,- "X-OpenViking-Agent": agent_id,},files={"file": (file_path.name, file, "application/octet-stream")},timeout=120.0,diff --git a/docs/images/agents/zh/claude-code.md b/docs/images/agents/zh/claude-code.mdindex 9229d8b58..29d41d1d8 100644--- a/docs/images/agents/zh/claude-code.md+++ b/docs/images/agents/zh/claude-code.md@@ -72,7 +72,7 @@ type claude # 期望输出:claude is a shell function| `OPENVIKING_MEMORY_ENABLED` | (auto) | 强制开启/关闭 || `OPENVIKING_DEBUG` | `false` | 写日志到 `~/.openviking/logs/cc-hooks.log` |-多租户场景设置 `OPENVIKING_ACCOUNT`、`OPENVIKING_USER`、`OPENVIKING_AGENT_ID`。完整环境变量列表见 [插件 README](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#configuration)。+多租户场景设置 `OPENVIKING_ACCOUNT` 和 `OPENVIKING_USER`。完整环境变量列表见 [插件 README](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#configuration)。</details>diff --git a/docs/images/agents/zh/sdk.md b/docs/images/agents/zh/sdk.mdindex 51b9f7150..9ab756d6a 100644--- a/docs/images/agents/zh/sdk.md+++ b/docs/images/agents/zh/sdk.md@@ -13,12 +13,10 @@ from openviking.client import SyncHTTPClienturl = "https://api.vikingdb.cn-beijing.volces.com/openviking"api_key = "[TODO]your-api-key"-agent_id = "[TODO]your-agent-id"client = SyncHTTPClient(url=url,api_key=api_key,- agent_id=agent_id,timeout=120.0,)client.initialize()diff --git a/docs/plans/agent-tool-name-convergence.md b/docs/plans/agent-tool-name-convergence.mddeleted file mode 100644index a2eaba0b0..000000000--- a/docs/plans/agent-tool-name-convergence.md+++ /dev/null@@ -1,134 +0,0 @@-# OpenViking Agent 工具名与通用接口收敛--这份文档从现有插件真实暴露的工具和 hook 出发,整理 OpenViking 面向不同 Agent 提供通用能力时的命名和下沉边界。--当前结论:OpenViking 自己提供的通用 Agent / MCP 工具名默认不带 `viking_` 前缀,例如 `find`、`search`、`remember`、`forget`、`health`。原因是工具执行入口已经是 OpenViking MCP server 或 OpenViking 插件,`viking://` URI 也已经表达了资源域;继续在工具名里重复 `viking_` 只会增加噪音。Hermes 是例外:它在 Hermes 官方仓里作为 memory provider 接入,宿主内可能同时存在其他 memory provider,因此可以保留 `viking_*` 作为 provider 级显式区分。--判断标准:只有不改变原功能、默认 scope、参数语义、返回语义和 lifecycle 行为时,才标记为“可以直接收敛”。如果多个插件重复实现同一能力,才考虑把能力下沉为 OpenViking 通用接口;单宿主专用能力继续留在插件内。--本次盘点覆盖:--- 本仓插件:OpenClaw、Claude Code、Codex MCP、opencode-memory-plugin、opencode skill plugin。-- 本仓外插件:Hermes 官方仓内置 OpenViking memory provider,本仓没有实现代码,本 PR 只记录命名原则。-- 通用 MCP 客户端:Cursor / Trae / Manus / Claude Desktop / ChatGPT 等直接消费 OV server `/mcp`。--## OpenViking 通用工具名--| 通用工具名 / 能力名 | 当前是否由 OV 提供 | 说明 |-|---|---|---|-| `find` | 是:REST `/api/v1/search/find`、MCP `find`、CLI `ov find` | 轻量语义检索。调用方决定 `target_uri`、limit、score threshold 和展示格式。 |-| `search` | 是:REST `/api/v1/search/search`、MCP `search`、CLI `ov search` | session-aware / deep search。可结合 `session_id` 做上下文检索。 |-| `remember` | 是:REST `/api/v1/sessions/*`、MCP `remember` | 写入消息并 commit,触发 memory extraction。 |-| `forget` | 是:REST `DELETE /api/v1/fs`、MCP `forget`、CLI `ov rm` | 按明确 `viking://` URI 删除。 |-| `health` | 是:REST `/health`、MCP `health`、CLI `ov health` | 检查 OpenViking server 可达性和基础健康状态。 |-| `read` | 是:REST `/api/v1/content/read`、MCP `read`、CLI `ov read` | 读取指定 URI 的内容。 |-| `list` | 是:REST `/api/v1/fs/ls`、MCP `list`、CLI `ov ls` | 列出目录或命名空间下的节点。 |-| `add_resource` | 是:REST `/api/v1/resources`、MCP `add_resource`、CLI `ov add-resource` | 添加外部资源。 |-| `add_skill` | 是:REST `/api/v1/skills`、CLI `ov add-skill` | 添加或注册 Agent skill。 |-| `grep` / `glob` | 是:REST `/api/v1/search/grep` 等、MCP `grep` / `glob`、CLI `ov grep` / `ov glob` | 精确文本检索和路径匹配。 |-| `archive_search` / `archive_read` | 否 | OpenClaw archive 工具绑定 session archive 语义,目前 OV 只有底层 grep/read 能力。 |--## 1. Search--Search 是显式搜索:用户或模型主动发起 query,目标是查找 memories、resources、skills 或 session context,并把结果作为可继续读取 / 引用的候选返回。OpenViking 已提供 `find` 和 `search` 两层:`find` 是轻量检索,`search` 是 session-aware deep search。--| 插件 / 接入 | 当前暴露工具名 / 入口 | 当前实际调用的 OV 接口 | 能否直接收敛到通用工具名 | 结论 / 原因 |-|---|---|---|---|---|-| OV server `/mcp` | `find` / `search` | 直接调用 `service.search.find()` / `service.search.search()` | 已收敛 | 本 PR 新增 `find`,并让 `search` 保持 deep/session-aware 语义。 |-| Codex MCP | `find` | REST `/api/v1/search/find`,默认 `target_uri=viking://user/memories` | 已收敛到工具名 | 工具名已统一为 `find`;默认 memory-only scope 是 Codex 插件自己的安全约束。 |-| OpenClaw | `ov_search` | REST `/api/v1/search/find`;默认查 resources + agent skills | 否 | OpenViking 插件使用 `ov_search`;它不等价于通用 `find`。 |-| Claude Code hooks / MCP | 无显式 search 工具;MCP 可直接用 OV `/mcp` 的 `find` / `search` | hooks 底层用 REST;MCP 直连 OV `/mcp` | 不改 | Claude Code 的显式搜索由通用 MCP 承担;hook search 行为归入 Recall。 |-| opencode-memory-plugin | `memsearch` | REST `/api/v1/search/find` 或 `/api/v1/search/search` | 否 | 它有 `auto` / `fast` / `deep` 模式,并会按 OpenCode session 自动选择接口和注入 `session_id`。 |-| opencode skill plugin | `ov search` / `ov find` 等 CLI 命令 | OV CLI | 已下沉,不改名 | 这是 shell skill,不是 native tool;`ov` 是 CLI 命令名前缀。 |-| Hermes OpenViking provider | `viking_search` | Hermes provider 内部调用 OpenViking semantic search | 不在本 PR 改 | Hermes 是外部官方仓 provider,工具名保留 `viking_*` 用于和其他 memory provider 区分。 |--## 2. Recall--Recall 是上下文召回:宿主在 prompt lifecycle 中自动取回相关 memory / skill / resource,并决定排序、预算、注入格式和触发时机。它不是简单的用户显式搜索,因此当前不定义一个通用 `recall` 工具名;底层可以复用 `find`、`search`、`read`。--| 插件 / 接入 | 当前暴露工具名 / 入口 | 当前实际调用的 OV 接口 | 能否直接收敛到通用工具名 | 结论 / 原因 |-|---|---|---|---|---|-| OpenClaw | `memory_recall` | REST `/api/v1/search/find`;默认并行查 user/agent memories,配置开启时追加 resources | 否 | 它是 OpenClaw 的记忆召回工具,默认 scope、资源开关、去重和返回格式都属于宿主语义。 |-| Claude Code hooks | `UserPromptSubmit` 自动召回,无模型可见工具名 | REST `/api/v1/search/find` + `/api/v1/content/read` | 不改 | hook 负责多 scope、ranking、token budget 和注入格式,底层已复用 OV。 |-| opencode-memory-plugin | 自动上下文注入路径 | REST `/api/v1/search/find` 或 `/api/v1/search/search` | 不改 | 召回绑定 OpenCode session 和注入策略,不是一个独立通用工具名。 |-| Codex MCP | 无自动 recall;模型显式调用 `find` | REST `/api/v1/search/find` | 不涉及 | Codex MCP 插件是显式工具,不做 lifecycle recall。 |-| opencode skill plugin | 无自动 recall;模型按 skill 说明调用 CLI | OV CLI | 不涉及 | shell skill 不做宿主 lifecycle 注入。 |-| Hermes OpenViking provider | 自动 provider context / prefetch | provider turn 前 prefetch 相关 memories 并注入 system prompt | 不在本 PR 改 | Hermes memory provider lifecycle 自带 recall:turn 前预取、非阻塞注入;不是 OV 通用 `recall` 工具。 |--## 3. Remember--Remember 是写入长期记忆:把文本、消息或会话内容写入 OpenViking session,并触发 commit / memory extraction。OV 通用能力名就是 `remember`;`memory_store` 只是 OpenClaw 当前宿主工具名,不代表 OV 还要提供另一个通用写入工具。--| 插件 / 接入 | 当前暴露工具名 / 入口 | 当前实际调用的 OV 接口 | 能否直接收敛到通用工具名 | 结论 / 原因 |-|---|---|---|---|---|-| OV server `/mcp` | `remember` | session message + commit | 已收敛 | 通用 MCP 客户端直接使用 `remember`。 |-| Codex MCP | `remember` | REST `/api/v1/sessions/*` | 已收敛到工具名 | 工具名已统一为 `remember`;插件仍保留同步等待提取结果的返回语义。 |-| OpenClaw | `memory_store` | REST `/api/v1/sessions/*` | 否 | 它会写 session message、commit、等待提取,并绑定 OpenClaw 的 session/agent 映射。是否改名仍需单独评估。 |-| Claude Code hooks | `Stop` / `PreCompact` / `SessionEnd` / `SubagentStop` 自动捕获,无模型可见工具名 | REST `/api/v1/sessions/*` | 不改 | hook 负责 transcript 解析、增量状态、subagent 隔离和异步写,底层已复用 OV。 |-| opencode-memory-plugin | `memcommit` | REST `/api/v1/sessions/{id}/messages` + `/commit` | 否 | 它绑定当前 OpenCode session,会先 flush pending messages,并等待或跟踪记忆提取。 |-| opencode skill plugin | 无 native remember 工具;模型按 skill 说明调用 CLI 写入/导入 | OV CLI | 不涉及 | shell skill 不注册 native tool。 |-| Hermes OpenViking provider | `viking_remember`;turn 后 `sync_turn()`;session end commit | `POST /sessions/{id}/messages` + `POST /sessions/{id}/commit` | 不在本 PR 改 | Hermes provider 会在响应后同步 conversation turn,并在 session end 触发 extraction;`viking_remember` 是显式记忆标注工具。 |--## 4. Forget--接口功能:按明确 `viking://` URI 删除 OpenViking 中的记忆或资源。--| 插件 / 接入 | 当前暴露工具名 / 入口 | 当前实际调用的 OV 接口 | 能否直接收敛到通用工具名 | 结论 / 原因 |-|---|---|---|---|---|-| OV server `/mcp` | `forget` | `DELETE /api/v1/fs` | 已收敛 | 通用 MCP 工具名就是 `forget`。 |-| Codex MCP | `forget` | `DELETE /api/v1/fs` | 已收敛 | 本 PR 将 Codex MCP 的删除工具改为 `forget`。 |-| OpenClaw | `memory_forget` | `DELETE /api/v1/fs`,必要时先 search 候选 | 否 | 它还支持按 query 搜索候选并删除唯一高置信 memory,不等价于通用 URI 删除。 |-| Claude Code hooks / MCP | hooks 无 forget;MCP 可直接用 OV `/mcp` 的 `forget` | OV `/mcp` 或 REST `DELETE /api/v1/fs` | 已下沉,不改 | 删除是显式危险操作,Claude Code 通过 MCP 工具使用 OV 通用能力。 |-| opencode-memory-plugin | 无独立 forget native tool | 无 | 不涉及 | 当前插件主能力是 search/read/browse/commit。 |-| opencode skill plugin | `ov rm` | OV CLI | 已下沉,不改名 | 这是 CLI 能力,不是 Agent native tool 命名。 |-| Hermes OpenViking provider | 无公开 `viking_forget` 工具 | 无公开删除路径 | 不在本 PR 改 | 最新 Hermes OpenViking provider 公开工具列举不包含 forget。 |--## 5. Health--接口功能:检查 OpenViking server 是否可达、可用。--| 插件 / 接入 | 当前暴露工具名 / 入口 | 当前实际调用的 OV 接口 | 能否直接收敛到通用工具名 | 结论 / 原因 |-|---|---|---|---|---|-| OV server `/mcp` | `health` | `/health` | 已收敛 | 通用 MCP 工具名就是 `health`。 |-| Codex MCP | `health` | `/health` | 已收敛 | 本 PR 将 Codex MCP 的健康检查工具改为 `health`。 |-| OpenClaw | 无模型可见 health 工具 | 初始化时调用 `/health` | 不涉及 | OpenClaw 只在插件初始化时探活,不需要暴露工具。 |-| Claude Code hooks / MCP | 无专用 health hook;MCP 可直接用 OV `/mcp` 的 `health` | OV `/mcp` 或 REST `/health` | 已下沉,不改 | 健康检查属于通用 MCP 能力。 |-| opencode-memory-plugin | 无独立 health native tool | 插件初始化 / 客户端可探活 | 不涉及 | 不作为模型可见工具收敛。 |-| opencode skill plugin | `ov health` | OV CLI | 已下沉,不改名 | 这是 CLI 命令名前缀。 |-| Hermes OpenViking provider | 无公开 `viking_health` 工具 | 配置 / provider 初始化检查 endpoint | 不在本 PR 改 | 最新公开工具列举不包含 health。 |--## 6. Add Resource / Add Skill / Archive / Read / Browse--Resource 和 skill 导入不再合并成 `import`。二者落点命名空间、底层 API 和参数不同:resource 进入 `viking://resources/...`,skill 进入 `viking://agent/skills/...`。因此 OpenClaw 的 Agent 可见工具应直接拆成 `add_resource` 和 `add_skill`,而不是继续暴露 `ov_import(kind=...)`。--| 插件 / 接入 | 当前暴露工具名 / 入口 | 当前实际调用的 OV 接口 | 能否直接收敛到通用工具名 | 结论 / 原因 |-|---|---|---|---|---|-| OpenClaw | 原 `ov_import(kind=resource)`,现 `add_resource` | local 文件 / 目录先 `temp_upload`,再走 `/api/v1/resources`;remote URL / Git URL 直接走 `/api/v1/resources` | 是 | resource 导入已有稳定 OV 能力名和底层接口。OpenClaw 插件仍负责本地文件 / 目录上传与 zip,但 Agent 可见工具名收敛为 `add_resource`。 |-| OpenClaw | 原 `ov_import(kind=skill)`,现 `add_skill` | local skill 文件 / 目录先 `temp_upload`,或 `data` 直接走 `/api/v1/skills` | 是 | skill 导入已有稳定 OV 能力名和底层接口,且参数与 resource 不同,拆成独立工具比 `ov_import + kind` 更清晰。 |-| OpenClaw slash command | 原 `/ov-import`,现 `/add-resource` / `/add-skill` | 分别调用 `add_resource` / `add_skill` 执行路径 | 是 | 用户手动命令也和 Agent 可见工具名保持一致;不再用 `--kind` 在一个命令里复用两种导入语义。 |-| OV server `/mcp` | `add_resource` | MCP tool `add_resource` 调 resource service | 已收敛 | 当前只支持 remote URL / Git URL,不支持本地 path,也没有 `add_skill`。 |-| OpenClaw | `ov_archive_search` | REST `/api/v1/search/grep` 等底层能力 | 否 | 语义是搜索当前 session history archive,不是通用 grep。 |-| OpenClaw | `ov_archive_expand` | REST `/api/v1/sessions/{id}/archives/{archive_id}` | 否 | 语义是读取当前 session archive 片段,不是通用 read。 |-| Codex MCP | 无 import / archive / browse 工具;可通过 OV `/mcp` 使用 `read` 等通用能力 | REST / MCP | 不涉及 | Codex 示例插件只保留显式 memory 四件套。 |-| Claude Code hooks / MCP | MCP 可直接用 OV `/mcp` 的 `read` / `list` / `add_resource` / `grep` / `glob` | OV `/mcp` | 已下沉,不改 | Claude Code 插件 `.mcp.json` 指向 OV server,直接消费通用 MCP 工具。 |-| opencode-memory-plugin | `memread` | REST `/api/v1/content/{abstract,overview,read}` + `/api/v1/fs/stat` | 否 | 它支持 `auto` 层级,会先 stat 再选择 overview/read。 |-| opencode-memory-plugin | `membrowse` | REST `/api/v1/fs/ls` / `tree` / `stat` | 否 | 它把 `list` / `tree` / `stat` / `simple` 视图合成一个工具。 |-| opencode skill plugin | `ov search` / `ov read` / `ov ls` / `ov rm` 等 CLI 命令 | OV CLI | 已下沉,不改名 | 这是 shell skill,不是 native tool;`ov` 是 CLI 命令名前缀,不属于 Agent 工具名收敛问题。 |-| Hermes OpenViking provider | `viking_read` / `viking_browse` / `viking_add_resource` | provider 内部调用 OpenViking read / browse / resource ingest | 不在本 PR 改 | Hermes 最新公开工具包含 read、browse、add_resource;未公开 archive_search / archive_read。 |--`import_ovpack` 不归入普通 Agent 导入能力。它走 `POST /api/v1/pack/import`,用于导入 `.ovpack` 上下文包,更接近备份、迁移和恢复,不是聊天中“把这个文档 / skill 加入 OpenViking”的 resource / skill 导入。--## 本 PR 的实际收敛--- OV server `/mcp`:提供 `find` 和 `search` 两层显式搜索;`find` 是轻量检索,`search` 是 session-aware deep search。-- Codex MCP:当前暴露 `find`、`remember`、`forget`、`health`,全部不带 `viking_` 前缀。-- OpenClaw:OpenViking 插件当前暴露 `ov_search` 并同步 `openclaw.plugin.json`;`memory_recall` 继续作为召回语义保留,不和 search 混成一个通用工具;原 Agent 可见 `ov_import` 已拆成 `add_resource` / `add_skill`。-- 不引入新的 ToolCatalog / agent tools 抽象,不迁移 Claude Code、opencode、Hermes 的既有工具名和执行语义。--## 后续下沉原则--1. OpenViking 直接提供的通用 Agent / MCP 工具名不带 `viking_` 前缀。-2. Hermes 这类外部 provider 场景可以保留 `viking_*`,用于和宿主内其他 provider 显式区分。-3. 先看插件是否能无语义变化调用 OV 已有接口;能就直接收敛。-4. OV 没有接口,但多个插件都重复实现同一能力,再补一个具体 OV 通用接口。-5. 只有单个宿主需要,或依赖宿主 lifecycle、默认 scope、返回格式的能力,继续留在插件里。diff --git a/docs/zh/about/02-changelog.md b/docs/zh/about/02-changelog.mdindex cf962b327..ddb16d452 100644--- a/docs/zh/about/02-changelog.md+++ b/docs/zh/about/02-changelog.md@@ -105,7 +105,7 @@ OpenViking 的所有重要变更都将记录在此文件中。- **Web Studio 成为默认 Console**:新增 `web-studio` 前端 console workspace,随 Docker 与 pip 分发并通过 `/studio` 提供服务;OAuth authorize UI 迁入 Web Studio,legacy console 下线,同时保留 favicon 兼容路由。- **MCP / API / CLI 自动化能力**:Watch Management 覆盖 REST、`ov` CLI 与 MCP;新增本地文件 progressive single-entrypoint upload;增加 `code_outline`、`code_search`、`code_expand` 代码导航工具,并修正 upload-only 与 zip `--ignore-dirs` 的作用域处理。- **Agent 与 OpenClaw 生态**:OpenClaw setup helper 支持 npm 插件安装,插件文档对齐 ClawHub package metadata,新增 `ov_dream` OpenClaw skill,并支持将过大的 OpenClaw tool result externalize 到 OpenViking。-- **Memory 与检索**:升级 trajectory extraction,新增 memory link 能力,支持通过开关启用 Vaka memory templates,修复缺失 tool-call 计数和缺失 `role_id` 的检索问题,并行化 hierarchical child search。+- **Memory 与检索**:升级 trajectory extraction,新增 memory link 能力,支持通过开关启用 Vaka memory templates,修复缺失 tool-call 计数和消息 peer 检索缺失问题,并行化 hierarchical child search。- **Storage、VectorDB 与模型链路稳定性**:存储锁与 IO 异步化,异步客户端按 event loop 隔离;修复 semantic lock ownership、`mv not found` 误报、URI remapping、S3 grep 性能、VectorDB Unicode recovery、超大 bytes row、embedding 错误透出和 VLM LiteLLM native routes 等问题。- **可观测性、文档与部署打磨**:新增 VikingBot feedback observability,集中化 metric registry,usage audit SQLite 迁入 system data,刷新 Helm chart 默认配置,更新品牌资产与二维码,并补齐 public base URL、signed upload TTL、Watch API、MCP code tools、ready 探针和 `/studio` 迁移文档。@@ -147,14 +147,14 @@ OpenViking 的所有重要变更都将记录在此文件中。- **可观测性**:OTLP 导出支持自定义 `headers`,覆盖 traces、logs、metrics 三条链路,便于直连需要额外鉴权头或 gRPC metadata 的观测后端。- **上传**:本地目录扫描和上传现在遵循根目录及子目录中的 `.gitignore` 规则,减少构建产物和临时文件被误导入。- **检索**:`search` / `find` 支持一次传入多个 target URI,适合跨目录、跨仓库范围检索。-- **多租户**:OpenClaw 插件明确 `agent_prefix` 仅作为前缀使用;OpenCode memory plugin 补上 tenant headers 透传。-- **管理**:新增 agent namespace 发现能力,服务端 API、CLI 和文档同步支持列出指定 account 下已有的 agent namespace。+- **多租户**:OpenClaw 插件明确 `peer_prefix` 仅作为 peer metadata 使用;OpenCode memory plugin 补上 tenant headers 透传。+- **管理**:废弃的 agent namespace 发现入口已删除。### 升级说明- OTLP 后端接入可通过 `headers` 统一配置鉴权信息(gRPC 模式为 metadata,HTTP 模式为请求头)。- 本地目录上传默认遵循 `.gitignore` 规则,此前被导入的临时/生成文件升级后可能被自动过滤。-- OpenClaw 插件 `agent_prefix` 仅表示前缀,文档中 `agentId` 已统一迁移为 `agent_prefix`。+- OpenClaw 插件运行时身份通过 `peer_prefix` peer metadata 表达,不再对应 OpenViking agent namespace。[完整变更记录](https://github.com/volcengine/OpenViking/compare/v0.3.13...v0.3.14)@@ -173,7 +173,7 @@ OpenViking 的所有重要变更都将记录在此文件中。### 升级说明- `encryption.api_key_hashing.enabled` 需要显式配置(默认 `false`)。如依赖旧的隐式哈希行为,需手动开启。-- OpenClaw 插件仅保留远程模式,不再启动本地子进程;`agentId` → `agent_prefix`,`recallTokenBudget` → `recallMaxInjectedChars`。+- OpenClaw 插件仅保留远程模式,不再启动本地子进程;运行时 agent 身份迁移为 peer metadata,`recallTokenBudget` → `recallMaxInjectedChars`。[完整变更记录](https://github.com/volcengine/OpenViking/compare/v0.3.12...v0.3.13)@@ -205,7 +205,7 @@ OpenViking 的所有重要变更都将记录在此文件中。- 调整 `recallTokenBudget` 和 `recallMaxContentChars` 默认值,降低 OpenClaw 自动召回注入过长上下文的风险。- `ov add-memory` 在异步 commit 场景下返回 `OK`,避免误判后台任务仍在执行时的状态。- `ov chat` 会从 `ovcli.conf` 读取鉴权配置并自动发送必要请求头。-- OpenClaw 插件默认远端连接行为、鉴权、namespace 和 `role_id` 处理更贴合服务端多租户模型。+- OpenClaw 插件默认远端连接行为、鉴权、namespace 和 `peer_id` 处理更贴合服务端多租户模型。### 修复@@ -413,7 +413,7 @@ LiteLLM 相关能力会暂时不可用,直到上游给出可信的修复版本### 重点更新-- OpenClaw 插件升级到 2.0(context engine),新增 OpenCode memory plugin,多智能体 memory isolation 基于 `agentId`。+- OpenClaw 插件升级到 2.0(context engine),新增 OpenCode memory plugin,多智能体 memory isolation 基于 peer metadata。- Memory 冷热分层 archival 和 hotness scoring、长记忆 chunked vectorization、`used()` 使用追踪接口。- 分层检索集成 rerank、RetrievalObserver 检索质量观测。- 资源 watch scheduling、reindex endpoint、legacy `.doc`/`.xls` 解析支持、path locking 和 crash recovery。diff --git a/docs/zh/agent-integrations/02-claude-code.md b/docs/zh/agent-integrations/02-claude-code.mdindex cf0c7d833..de41746e8 100644--- a/docs/zh/agent-integrations/02-claude-code.md+++ b/docs/zh/agent-integrations/02-claude-code.md@@ -72,7 +72,7 @@ type claude # 期望输出:claude is a shell function| `OPENVIKING_MEMORY_ENABLED` | (auto) | 强制开启/关闭 || `OPENVIKING_DEBUG` | `false` | 写日志到 `~/.openviking/logs/cc-hooks.log` |-多租户场景设置 `OPENVIKING_ACCOUNT`、`OPENVIKING_USER`、`OPENVIKING_AGENT_ID`。完整环境变量列表见 [插件 README](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#configuration)。+多租户场景设置 `OPENVIKING_ACCOUNT`、`OPENVIKING_USER`。完整环境变量列表见 [插件 README](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#configuration)。</details>diff --git a/docs/zh/agent-integrations/03-openclaw.md b/docs/zh/agent-integrations/03-openclaw.mdindex cea71a5a0..37acc17aa 100644--- a/docs/zh/agent-integrations/03-openclaw.md+++ b/docs/zh/agent-integrations/03-openclaw.md@@ -96,7 +96,7 @@ python examples/openclaw-plugin/health_check_tools/ov-healthcheck.py| --- | --- | --- || `baseUrl` | `http://127.0.0.1:1933` | OpenViking 服务端点 || `apiKey` | 空 | OpenViking API Key |-| `agent_prefix` | `default` | Agent 前缀,用于记忆命名空间隔离 |+| `peer_prefix` | 空 | `peer_role=assistant` 时 assistant peer 身份的可选前缀 |```bashopenclaw config set plugins.entries.openviking.config.baseUrl http://your-server:1933diff --git a/docs/zh/agent-integrations/07-langchain-langgraph.md b/docs/zh/agent-integrations/07-langchain-langgraph.mdindex 8de4633a4..23a56ab6f 100644--- a/docs/zh/agent-integrations/07-langchain-langgraph.md+++ b/docs/zh/agent-integrations/07-langchain-langgraph.md@@ -23,6 +23,32 @@ tools = create_openviking_tools(省略 `url` 时,适配器自动从 OpenViking CLI 配置加载连接信息。Embedding 和 VLM 在 OpenViking 侧配置,不在你的应用中。+## Peer 身份++所有会读写 session memory 的适配器都支持 `peer_id`。当同一个 OpenViking user 需要和多个稳定外部对象交互时使用它,例如不同 agent、机器人,或共享会话中的不同人。++```python+retriever = OpenVikingRetriever(+ url="http://localhost:1933",+ peer_id="assistant-a",+)++chain = with_openviking_context(+ runnable,+ session_id="support-thread-1",+ peer_id="assistant-a",+)+```++动态运行时,`with_openviking_context()` 默认也会读取 `config["configurable"]["peer_id"]`:++```python+chain.invoke(+ {"messages": [...]},+ config={"configurable": {"session_id": "support-thread-1", "peer_id": "assistant-a"}},+)+```+## 选哪个适配器?| 我想… | 用这个 |diff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.mdindex 148bc6d3e..d1919874c 100644--- a/docs/zh/api/01-overview.md+++ b/docs/zh/api/01-overview.md@@ -69,7 +69,6 @@ import openviking as ovclient = ov.SyncHTTPClient(url="http://localhost:1933",api_key="your-key",- agent_id="my-agent",timeout=120.0,)client.initialize()@@ -88,8 +87,7 @@ export OPENVIKING_CLI_CONFIG_FILE=/path/to/ovcli.conf"url": "http://localhost:1933","api_key": "your-key","account": "acme",- "user": "alice",- "agent_id": "my-agent"+ "user": "alice"}```@@ -101,7 +99,6 @@ export OPENVIKING_CLI_CONFIG_FILE=/path/to/ovcli.conf| `api_key` | API Key | `null`(无认证) || `account` | 租户级请求的默认账户请求头 | `null` || `user` | 租户级请求的默认用户请求头 | `null` |-| `agent_id` | Agent 标识符请求头 | `null` || `timeout` | HTTP 请求超时时间(秒) | `60.0` || `output` | 默认输出格式:`"table"` 或 `"json"` | `"table"` |@@ -475,7 +472,6 @@ JSON 输出 - 错误:| DELETE | `/api/v1/admin/accounts/{account_id}` | 删除工作区(级联清理数据) | ROOT || POST | `/api/v1/admin/accounts/{account_id}/users` | 注册用户 | ROOT/ADMIN || GET | `/api/v1/admin/accounts/{account_id}/users` | 列出用户 | ROOT/ADMIN |-| GET | `/api/v1/admin/accounts/{account_id}/agents` | 列出 agent namespace | ROOT/ADMIN || DELETE | `/api/v1/admin/accounts/{account_id}/users/{user_id}` | 移除用户 | ROOT/ADMIN || PUT | `/api/v1/admin/accounts/{account_id}/users/{user_id}/role` | 修改用户角色 | ROOT || POST | `/api/v1/admin/accounts/{account_id}/users/{user_id}/key` | 重新生成 User Key | ROOT/ADMIN |diff --git a/docs/zh/api/02-resources.md b/docs/zh/api/02-resources.mdindex 7a4fa8197..77c8a6224 100644--- a/docs/zh/api/02-resources.md+++ b/docs/zh/api/02-resources.md@@ -549,8 +549,8 @@ ov add-skill ./skills/my-skill.json --wait"status": "ok","result": {"status": "success",- "root_uri": "viking://agent/skills/my-skill",- "uri": "viking://agent/skills/my-skill",+ "root_uri": "viking://user/skills/my-skill",+ "uri": "viking://user/skills/my-skill","name": "my-skill","auxiliary_files": 2,"queue_status": {@@ -571,8 +571,8 @@ ov add-skill ./skills/my-skill.json --waitNote: Skill is being processed in the background.Use 'ov wait' to wait for completion, or 'ov observer queue' to check status.status success-root_uri viking://agent/skills/my-skill-uri viking://agent/skills/my-skill+root_uri viking://user/skills/my-skill+uri viking://user/skills/my-skillname my-skillauxiliary_files 2```@@ -582,8 +582,8 @@ auxiliary_files 2```json{"status": "success",- "root_uri": "viking://agent/skills/my-skill",- "uri": "viking://agent/skills/my-skill",+ "root_uri": "viking://user/skills/my-skill",+ "uri": "viking://user/skills/my-skill","name": "my-skill","auxiliary_files": 2}diff --git a/docs/zh/api/04-skills.md b/docs/zh/api/04-skills.mdindex b3da15e0f..251b7f7b0 100644--- a/docs/zh/api/04-skills.md+++ b/docs/zh/api/04-skills.md@@ -14,10 +14,10 @@ OpenViking 支持多种技能定义格式:### 技能存储结构-技能存储在 `viking://agent/skills/` 路径下:+技能存储在 `viking://user/skills/` 路径下:```-viking://agent/skills/+viking://user/skills/+-- search-web/| +-- .abstract.md # L0:简要描述| +-- .overview.md # L1:参数和使用概览@@ -152,7 +152,7 @@ This tool wraps the MCP tool `search-web`. Call this when the user needs functio1. 接收技能数据或上传的临时文件2. 检测数据格式(结构化数据、SKILL.md 内容、MCP 格式)3. 解析技能定义-4. 存储到 `viking://agent/skills/` 路径下+4. 存储到 `viking://user/skills/` 路径下5. 如指定 `wait=True`,等待向量化完成**代码入口**:@@ -338,8 +338,8 @@ ov add-skill ./skills/my-skill/ -o json"status": "ok","result": {"status": "success",- "root_uri": "viking://agent/skills/my-skill/",- "uri": "viking://agent/skills/my-skill/",+ "root_uri": "viking://user/skills/my-skill/",+ "uri": "viking://user/skills/my-skill/","name": "my-skill","auxiliary_files": 2,"queue_status": {@@ -360,8 +360,8 @@ ov add-skill ./skills/my-skill/ -o jsonNote: Skill is being processed in the background.Use 'ov wait' to wait for completion, or 'ov observer queue' to check status.status success-root_uri viking://agent/skills/my-skill-uri viking://agent/skills/my-skill+root_uri viking://user/skills/my-skill+uri viking://user/skills/my-skillname my-skillauxiliary_files 2```@@ -370,8 +370,8 @@ auxiliary_files 2```json{"status": "success",- "root_uri": "viking://agent/skills/my-skill",- "uri": "viking://agent/skills/my-skill",+ "root_uri": "viking://user/skills/my-skill",+ "uri": "viking://user/skills/my-skill","name": "my-skill","auxiliary_files": 2}@@ -414,19 +414,19 @@ Python HTTP SDK 会把该响应映射为对应异常(`ProcessingError`)。```python# 列出所有技能-skills = client.ls("viking://agent/skills/")+skills = client.ls("viking://user/skills/")for skill in skills:print(f"{skill['name']}")# 简单列表(仅名称)-names = client.ls("viking://agent/skills/", simple=True)+names = client.ls("viking://user/skills/", simple=True)print(names)```**HTTP API**:```bash-curl -X GET "http://localhost:1933/api/v1/fs/ls?uri=viking://agent/skills/" \+curl -X GET "http://localhost:1933/api/v1/fs/ls?uri=viking://user/skills/" \-H "X-API-Key: your-key"```@@ -435,7 +435,7 @@ curl -X GET "http://localhost:1933/api/v1/fs/ls?uri=viking://agent/skills/" \**Python SDK**:```python-uri = "viking://agent/skills/search-web/"+uri = "viking://user/skills/search-web/"# L0:简要描述abstract = client.abstract(uri)@@ -454,15 +454,15 @@ print(f"Content: {content}")```bash# L0:简要描述-curl -X GET "http://localhost:1933/api/v1/content/abstract?uri=viking://agent/skills/search-web/" \+curl -X GET "http://localhost:1933/api/v1/content/abstract?uri=viking://user/skills/search-web/" \-H "X-API-Key: your-key"# L1:参数和使用概览-curl -X GET "http://localhost:1933/api/v1/content/overview?uri=viking://agent/skills/search-web/" \+curl -X GET "http://localhost:1933/api/v1/content/overview?uri=viking://user/skills/search-web/" \-H "X-API-Key: your-key"# L2:完整技能文档-curl -X GET "http://localhost:1933/api/v1/content/read?uri=viking://agent/skills/search-web/" \+curl -X GET "http://localhost:1933/api/v1/content/read?uri=viking://user/skills/search-web/" \-H "X-API-Key: your-key"```@@ -474,7 +474,7 @@ curl -X GET "http://localhost:1933/api/v1/content/read?uri=viking://agent/skills# 语义搜索技能results = client.find("search the internet",- target_uri="viking://agent/skills/",+ target_uri="viking://user/skills/",limit=5)@@ -492,7 +492,7 @@ curl -X POST http://localhost:1933/api/v1/search/find \-H "X-API-Key: your-key" \-d '{"query": "search the internet",- "target_uri": "viking://agent/skills/",+ "target_uri": "viking://user/skills/","limit": 5}'```@@ -502,13 +502,13 @@ curl -X POST http://localhost:1933/api/v1/search/find \**Python SDK**:```python-client.rm("viking://agent/skills/old-skill/", recursive=True)+client.rm("viking://user/skills/old-skill/", recursive=True)```**HTTP API**:```bash-curl -X DELETE "http://localhost:1933/api/v1/fs?uri=viking://agent/skills/old-skill/&recursive=true" \+curl -X DELETE "http://localhost:1933/api/v1/fs?uri=viking://user/skills/old-skill/&recursive=true" \-H "X-API-Key: your-key"```diff --git a/docs/zh/api/05-sessions.md b/docs/zh/api/05-sessions.mdindex 06c64bd6f..17043cc65 100644--- a/docs/zh/api/05-sessions.md+++ b/docs/zh/api/05-sessions.md@@ -86,8 +86,7 @@ ov session new"session_id": "a1b2c3d4","user": {"account_id": "default",- "user_id": "alice",- "agent_id": "default"+ "user_id": "alice"}},"time": 0.1@@ -264,8 +263,7 @@ ov session get a1b2c3d4},"user": {"account_id": "default",- "user_id": "alice",- "agent_id": "default"+ "user_id": "alice"},"pending_tokens": 450}@@ -570,7 +568,7 @@ ov session delete a1b2c3d4| parts | List[Part] | 条件必填 | - | 消息部分列表(Python SDK 必填;HTTP API 可选,与 content 二选一) || content | str | 条件必填 | - | 消息文本内容(HTTP API 简单模式,与 parts 二选一) || created_at | str | 否 | None | 可选的 ISO 8601 时间戳,会原样保存到消息中 |-| role_id | str | 否 | None | 可选的显式参与者 ID,省略时由服务器推导 |+| peer_id | str | 否 | None | 可选的稳定交互对象 ID |> **注意**:HTTP API 支持两种模式:> 1. **简单模式**:使用 `content` 字符串(向后兼容)@@ -597,7 +595,7 @@ ContextPart(ToolPart(tool_id="call_123",tool_name="search_web",- skill_uri="viking://agent/skills/search-web/",+ skill_uri="viking://user/skills/search-web/",tool_input={"query": "OAuth best practices"},tool_output="",tool_status="pending" # "pending"、"running"、"completed"、"error"@@ -838,7 +836,7 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/used \curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/used \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \- -d '{"skill": {"uri": "viking://agent/skills/search-web/", "input": {"query": "OAuth"}, "output": "Results...", "success": true}}'+ -d '{"skill": {"uri": "viking://user/skills/search-web/", "input": {"query": "OAuth"}, "output": "Results...", "success": true}}'```**Python SDK**@@ -858,7 +856,7 @@ await client.session_used(await client.session_used(session_id="a1b2c3d4",skill={- "uri": "viking://agent/skills/search-web/",+ "uri": "viking://user/skills/search-web/","input": {"query": "OAuth"},"output": "Results...","success": True@@ -1271,10 +1269,10 @@ viking://session/{user_id}/{session_id}/| preferences | `user/memories/preferences/` | 按主题分类的用户偏好 || entities | `user/memories/entities/` | 重要实体(人物、项目等) || events | `user/memories/events/` | 重要事件 |-| cases | `agent/memories/cases/` | 问题-解决方案案例 |-| patterns | `agent/memories/patterns/` | 交互模式 |-| tools | `agent/memories/tools/` | 工具使用经验与最佳实践 |-| skills | `agent/memories/skills/` | 技能执行经验与工作流策略 |+| trajectories | `user/memories/trajectories/` | 可复用的操作契约 |+| experiences | `user/memories/experiences/` | 可复用的执行经验 |+| tools | `user/memories/tools/` | 工具使用经验与最佳实践 |+| skills | `user/memories/skills/` | 技能执行经验与工作流策略 |---diff --git a/docs/zh/api/06-retrieval.md b/docs/zh/api/06-retrieval.mdindex d703d09d6..870a21e6e 100644--- a/docs/zh/api/06-retrieval.md+++ b/docs/zh/api/06-retrieval.md@@ -56,6 +56,7 @@ OpenViking 提供多种检索方法,包括简单的向量相似度搜索、带|------|------|------|--------|------|| query | str | 是 | - | 搜索查询字符串 || target_uri | str \| List[str] | 否 | "" | 限制搜索范围到指定的 URI 前缀 |+| peer_id | str | 否 | None | 稳定交互对象 ID。检索默认 user memory 范围时,会同时检索当前 user memory 和该 peer 的 memory。CLI `--peer-id` 会映射到这个字段 || limit | int | 否 | 10 | 最大返回结果数 || node_limit | int | 否 | None | 可选 HTTP 别名;如果提供,会覆盖 limit || score_threshold | float | 否 | None | 最低相关性分数阈值 |@@ -172,7 +173,7 @@ results = client.find(# 仅在技能中搜索results = client.find("web search",- target_uri="viking://agent/skills"+ target_uri="viking://user/skills")# 在特定项目中搜索@@ -274,6 +275,7 @@ openviking find "how to authenticate users" -L 1,2| target_uri | str \| List[str] | 否 | "" | 限制搜索范围到指定的 URI 前缀 || session | Session | 否 | None | 用于上下文感知搜索的会话(SDK)|| session_id | str | 否 | None | 用于上下文感知搜索的会话 ID(HTTP)|+| peer_id | str | 否 | None | 稳定交互对象 ID。检索默认 user memory 范围时,会同时检索当前 user memory 和该 peer 的 memory。CLI `--peer-id` 会映射到这个字段 || limit | int | 否 | 10 | 最大返回结果数 || node_limit | int | 否 | None | 可选 HTTP 别名;如果提供,会覆盖 limit || score_threshold | float | 否 | None | 最低相关性分数阈值 |diff --git a/docs/zh/api/07-system.md b/docs/zh/api/07-system.mdindex 61ad3137a..42876b99e 100644--- a/docs/zh/api/07-system.md+++ b/docs/zh/api/07-system.md@@ -372,7 +372,7 @@ ov system wait --timeout 60**认证**-- HTTP 端点:在开启认证时要求 root/admin 权限;root key 请求必须带 `X-OpenViking-Account`+- HTTP 端点:在开启认证时要求 admin/root 角色。`api_key` 模式下,租户内容重建请使用 admin key;裸 root key 不能访问租户级数据。- Python embedded 模式:使用当前 service context- Python HTTP client / CLI:使用当前认证身份发起请求@@ -391,14 +391,11 @@ HTTP 请求体不接受未知字段。`uri` 可以使用其他 content API 支- `viking://`- `viking://user`- `viking://user/<user_id>`-- `viking://agent`-- `viking://agent/<agent_id>`- `viking://resources`- `viking://resources/...`- `viking://user/<user_id>/memories/...`-- `viking://agent/<agent_id>/memories/...`-- `viking://agent/<agent_id>/skills`-- `viking://agent/<agent_id>/skills/<skill_name>`+- `viking://user/<user_id>/skills`+- `viking://user/<user_id>/skills/<skill_name>``reindex()` 不支持 `viking://session/...`。@@ -424,7 +421,7 @@ print(result)```pythonresult = client.reindex(- uri="viking://agent/default/skills",+ uri="viking://user/default/skills",mode="semantic_and_vectors",wait=False,)@@ -458,7 +455,7 @@ openviking reindex viking://resources --mode vectors_only``````bash-openviking reindex viking://agent/default/skills --mode semantic_and_vectors --wait false+openviking reindex viking://user/default/skills --mode semantic_and_vectors --wait false```**同步响应(`wait=true`)**@@ -520,7 +517,7 @@ GET /api/v1/tasks?task_type=admin_reindex&resource_id=viking://resources|------|------|| status | 同步完成时为 `completed`,后台执行时为 `accepted` || uri | 解析路径变量后的请求 URI |-| object_type | 推断出的目标类型,例如 `resource`、`skill`、`memory`、`user_namespace`、`agent_namespace`、`skill_namespace` 或 `global_namespace` |+| object_type | 推断出的目标类型,例如 `resource`、`skill`、`memory`、`user_namespace`、`skill_namespace` 或 `global_namespace` || mode | 实际执行的 reindex 模式 || scanned_records | 被检查的记录或语义源数量 || rebuilt_records | 成功重建的向量记录数量 |@@ -534,7 +531,7 @@ GET /api/v1/tasks?task_type=admin_reindex&resource_id=viking://resources- Reindex 是非破坏式的,采用重建/覆盖写入,不需要先 drop 向量集合。- 对 `viking://` 发起 reindex 时,会向下分发到支持的顶层命名空间,并显式排除 `session`。-- 命名空间级 reindex,例如 `viking://user` 或 `viking://agent/default`,会继续传播到其支持的子内容类型。+- 命名空间级 reindex,例如 `viking://user`,会继续传播到其支持的子内容类型。- 如果只是 embedding 模型或向量索引需要刷新,应使用 `vectors_only`。- 如果语义产物本身也需要重建,再做重向量化,应使用 `semantic_and_vectors`。- 同一个 URI 和 owner 同时只能运行一个 reindex 任务。对同一目标的并发请求会返回 conflict。diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.mdindex c36507d47..5ee1517e8 100644--- a/docs/zh/api/08-admin.md+++ b/docs/zh/api/08-admin.md@@ -22,7 +22,7 @@ Admin API 用于多租户环境下的账户和用户管理。包括工作区(a| 创建/删除工作区 | Y | N | N || 列出工作区 | Y | N | N || 注册/移除用户 | Y | Y(本 account) | N |-| 列出 agent namespace | Y | Y(本 account) | N |+| 列出 agents(已废弃,返回空列表) | Y | Y(本 account) | N || 重新生成 User Key | Y | Y(本 account) | N || 修改用户角色 | Y | N | N |@@ -82,12 +82,10 @@ Admin API 用于多租户环境下的账户和用户管理。包括工作区(a|------|------|------|--------|------|| account_id | str | 是 | - | 工作区 ID || admin_user_id | str | 是 | - | 首个管理员用户 ID |-| isolate_user_scope_by_agent | bool | 否 | false | 是否按 agent 进一步隔离 user scope |-| isolate_agent_scope_by_user | bool | 否 | false | 是否按 user 进一步隔离 agent scope |**说明:**- 在 `trusted` 模式下,响应中不会包含 `user_key` 字段-- `isolate_user_scope_by_agent` 和 `isolate_agent_scope_by_user` 仅可通过 HTTP API 设置,Python SDK 和 CLI 暂不支持+- 不再支持 account 级 namespace 隔离配置。用户记忆使用 user-scoped namespace,一对多外部参与者通过 `peer_id` 表达。#### 3. 使用示例@@ -103,9 +101,7 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \-H "X-API-Key: <root-key>" \-d '{"account_id": "acme",- "admin_user_id": "alice",- "isolate_user_scope_by_agent": true,- "isolate_agent_scope_by_user": false+ "admin_user_id": "alice"}'```@@ -135,9 +131,7 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \-H "X-OpenViking-User: gateway-admin" \-d '{"account_id": "acme",- "admin_user_id": "alice",- "isolate_user_scope_by_agent": true,- "isolate_agent_scope_by_user": false+ "admin_user_id": "alice"}'```@@ -182,9 +176,7 @@ ov --sudo admin create-account acme --admin alice"result": {"account_id": "acme","admin_user_id": "alice",- "user_key": "7f3a9c1e...",- "isolate_user_scope_by_agent": true,- "isolate_agent_scope_by_user": false+ "user_key": "7f3a9c1e..."},"time": 0.1}@@ -512,75 +504,6 @@ ov --sudo admin list-users acme----### list_agents--#### 1. API 实现介绍--列出工作区中已经存在的 agent namespace。这是管理侧发现接口,不改变普通 `viking://agent/...` 文件系统语义。--**处理流程:**-1. 验证请求者具有 ROOT 权限,或为本账户的 ADMIN-2. 验证 account 存在-3. 扫描该 account 的 `viking://agent` namespace 根目录-4. 返回按 agent_id 排序的 agent namespace 列表--**代码入口:**-- `openviking/server/routers/admin.py:list_agents` - HTTP 路由-- `crates/ov_cli/src/client.rs:HttpClient.admin_list_agents` - CLI HTTP 客户端-- `crates/ov_cli/src/commands/admin.rs:list_agents` - CLI 命令--#### 2. 接口和参数说明--**参数**--| 参数 | 类型 | 必填 | 默认值 | 说明 |-|------|------|------|--------|------|-| account_id | str | 是 | - | 工作区 ID |--**说明:**-- ROOT 可以列出任意 account 的 agents-- ADMIN 只能列出自己所属 account 的 agents-- USER 不能调用该接口-- 返回的是存储中已经存在的 agent namespace;新建 account 会包含初始化出的 `default` agent namespace--#### 3. 使用示例--**HTTP API**--```-GET /api/v1/admin/accounts/{account_id}/agents-```--```bash-curl -X GET http://localhost:1933/api/v1/admin/accounts/acme/agents \- -H "X-API-Key: <root-or-admin-key>"-```--**CLI**--```bash-# ROOT 或本账户的 ADMIN 都可以执行-# 如果使用普通用户的 api_key 但该用户是 acme 的 ADMIN:-ov admin list-agents acme-# 如果使用 root_api_key(--sudo):-ov --sudo admin list-agents acme-```--**响应示例**--```json-{- "status": "ok",- "result": [- {"agent_id": "default", "uri": "viking://agent/default"},- {"agent_id": "openclaw", "uri": "viking://agent/openclaw"}- ],- "time": 0.1-}-```------### remove_user#### 1. API 实现介绍diff --git a/docs/zh/concepts/02-context-types.md b/docs/zh/concepts/02-context-types.mdindex f52ecf6fd..9a14e1785 100644--- a/docs/zh/concepts/02-context-types.md+++ b/docs/zh/concepts/02-context-types.md@@ -50,7 +50,7 @@ results = client.find(- **Agent 主动:**由 Agent 主动提取和记录的记忆信息- **动态更新:**由 Agent 从交互中持续更新-- **个性化:**针对特定用户或 特定 Agent 学习记录+- **个性化:**针对特定用户和稳定 peer 学习记录### 8 种分类@@ -60,10 +60,10 @@ results = client.find(| **preferences** | `user/memories/preferences/` | 按主题的用户偏好 | ✅ 可追加 || **entities** | `user/memories/entities/` | 实体记忆(人物、项目) | ✅ 可追加 || **events** | `user/memories/events/` | 事件记录(决策、里程碑) | ❌ 不更新 |-| **cases** | `agent/memories/cases/` | 学习的案例 | ❌ 不更新 |-| **patterns** | `agent/memories/patterns/` | 学习的模式 | ✅ 可合并 |-| **tools** | `agent/memories/tools/` | 工具使用经验与最佳实践 | ✅ 可合并 |-| **skills** | `agent/memories/skills/` | 技能执行经验与工作流策略 | ✅ 可合并 |+| **trajectories** | `user/memories/trajectories/` | 可复用的操作契约 | ❌ 不更新 |+| **experiences** | `user/memories/experiences/` | 可复用的执行经验 | ✅ 可合并 |+| **tools** | `user/memories/tools/` | 工具使用经验与最佳实践 | ✅ 可合并 |+| **skills** | `user/memories/skills/` | 技能执行经验与工作流策略 | ✅ 可合并 |### 使用@@ -94,7 +94,7 @@ results = await client.find(### 存储位置```-viking://agent/skills/{skill-name}/+viking://user/skills/{skill-name}/├── .abstract.md # L0: 简短描述├── SKILL.md # L1: 详细概览└── scripts # L2: 完整定义@@ -114,7 +114,7 @@ await client.add_skill({# 搜索技能results = await client.find("网络搜索",- target_uri="viking://agent/skills/"+ target_uri="viking://user/skills/")```diff --git a/docs/zh/concepts/04-viking-uri.md b/docs/zh/concepts/04-viking-uri.mdindex 090992f3c..1bf29e47b 100644--- a/docs/zh/concepts/04-viking-uri.md+++ b/docs/zh/concepts/04-viking-uri.md@@ -86,21 +86,19 @@ viking://user/memories/entities/ # 实体记忆viking://user/memories/events/ # 事件记忆```-### Agent 数据+### 用户技能和记忆```-viking://agent/ # Agent 根目录-viking://agent/skills/ # 所有技能-viking://agent/skills/search-web # 具体技能-viking://agent/memories/ # Agent 记忆-viking://agent/memories/cases/ # 学习的案例-viking://agent/memories/patterns/ # 学习的模式-viking://agent/instructions/ # Agent 指令+viking://user/skills/ # 当前用户的技能+viking://user/skills/search-web # 某个技能+viking://user/memories/ # 当前用户的记忆+viking://user/memories/cases/ # 学习的案例+viking://user/memories/patterns/ # 学习的模式```-上面的 `viking://user/...` 和 `viking://agent/...` 短路径会按当前请求身份解析。-OpenViking 会在存储和检索前将它们展开为显式命名空间路径,例如-`viking://user/{user_id}/...` 和 `viking://agent/{agent_id}/...`。+上面的 `viking://user/...` 短路径会按当前请求身份解析。+OpenViking 会在存储和检索前将它展开为显式命名空间路径,例如+`viking://user/{user_id}/...`。### 会话数据@@ -203,30 +201,13 @@ viking://│ ├── entities/ # 每条独立│ └── events/ # 每条独立│-├── agent/{agent_id}/ # isolate_agent_scope_by_user = false 时的 agent 根目录-│ ├── skills/ # 技能定义-│ ├── memories/-│ │ ├── cases/-│ │ └── patterns/-│ └── instructions/-│-├── agent/{agent_id}/user/{user_id}/ # isolate_agent_scope_by_user = true 时的 agent 根目录-│ ├── skills/-│ ├── memories/-│ └── instructions/-│└── session/{session_id}/├── messages/├── tools/└── history/```-其中 agent 命名空间形状由 account 级 namespace policy 决定:--- `isolate_agent_scope_by_user = false`:`viking://agent/{agent_id}/...`-- `isolate_agent_scope_by_user = true`:`viking://agent/{agent_id}/user/{user_id}/...`--`memory.agent_scope_mode` 已废弃且被忽略。+`viking://agent/...` 已废弃,当前 namespace 解析会拒绝该路径。## URI 操作@@ -272,7 +253,7 @@ results = client.find(# 仅在技能中搜索results = client.find("网络搜索",- target_uri="viking://agent/skills/"+ target_uri="viking://user/skills/")```@@ -321,8 +302,8 @@ overview = await client.overview("viking://resources/docs/")# 资源只添加到 resources 作用域await client.add_resource(url, to="viking://resources/project/")-# 技能添加到 agent 作用域-await client.add_skill(skill) # 自动到 viking://agent/skills/+# 技能添加到 user 作用域+await client.add_skill(skill) # 自动到 viking://user/skills/```## 相关文档diff --git a/docs/zh/concepts/05-storage.md b/docs/zh/concepts/05-storage.mdindex a16f7b3f2..e4b13351f 100644--- a/docs/zh/concepts/05-storage.md+++ b/docs/zh/concepts/05-storage.md@@ -41,7 +41,7 @@ VikingFS 是统一的 URI 抽象层,屏蔽底层存储细节。```viking://resources/docs/auth → /local/{account_id}/resources/docs/authviking://user/memories → /local/{account_id}/user/{user_id}/memories-viking://agent/skills → /local/{account_id}/agent/{agent_id}/skills+viking://user/skills → /local/{account_id}/user/{user_id}/skills```### 核心 APIdiff --git a/docs/zh/concepts/06-extraction.md b/docs/zh/concepts/06-extraction.mdindex 879d93d42..a38e3e5bd 100644--- a/docs/zh/concepts/06-extraction.md+++ b/docs/zh/concepts/06-extraction.md@@ -72,7 +72,7 @@ TreeBuilder 负责将临时目录移动到 AGFS,并入队语义处理。```pythonbuilding_tree = tree_builder.finalize_from_temp(temp_dir_path="viking://temp/abc123",- scope="resources", # resources/user/agent+ scope="resources", # resources/user)```@@ -90,7 +90,6 @@ building_tree = tree_builder.finalize_from_temp(|-------|----------|| resources | `viking://resources` || user | `viking://user` |-| agent | `viking://agent` |## SemanticQueue(语义队列)@@ -193,8 +192,8 @@ openviking/parse/parsers/code/ast/| 环节 | Resource | Memory | Skill ||------|----------|--------|-------|| **Parser** | 通用流程 | 通用流程 | 通用流程 |-| **基础 URI** | `viking://resources` | `viking://user/memories` | `viking://agent/skills` |-| **TreeBuilder scope** | resources | user/agent | agent |+| **基础 URI** | `viking://resources` | `viking://user/memories` | `viking://user/skills` |+| **TreeBuilder scope** | resources | user | user || **SemanticMsg type** | resource | memory | skill |### 资源提取@@ -218,7 +217,7 @@ await client.add_skill({"content": "# search-web\\n..."})-# 流程: 直接写入 viking://agent/skills/{name}/ → SemanticQueue+# 流程: 直接写入 viking://user/skills/{name}/ → SemanticQueue```### 记忆提取diff --git a/docs/zh/concepts/07-retrieval.md b/docs/zh/concepts/07-retrieval.mdindex a96f4d2a4..c85c89ff7 100644--- a/docs/zh/concepts/07-retrieval.md+++ b/docs/zh/concepts/07-retrieval.md@@ -92,9 +92,9 @@ Step 5: 转换为 MatchedContext| context_type | 根目录 ||--------------|--------|-| MEMORY | `viking://user/memories`, `viking://agent/memories` |+| MEMORY | `viking://user/memories` || RESOURCE | `viking://resources` |-| SKILL | `viking://agent/skills` |+| SKILL | `viking://user/skills` |### 递归搜索算法diff --git a/docs/zh/concepts/08-session.md b/docs/zh/concepts/08-session.mdindex beb394597..d93c0b2e3 100644--- a/docs/zh/concepts/08-session.md+++ b/docs/zh/concepts/08-session.md@@ -48,7 +48,7 @@ session.used(contexts=["viking://user/memories/profile.md"])# 记录使用的技能session.used(skill={- "uri": "viking://agent/skills/code-search",+ "uri": "viking://user/skills/code-search","input": "search config","output": "found 3 files","success": True@@ -244,7 +244,7 @@ viking://user/memories/├── entities/└── events/-viking://agent/memories/+viking://user/memories/├── cases/├── patterns/├── tools/diff --git a/docs/zh/concepts/11-multi-tenant.md b/docs/zh/concepts/11-multi-tenant.mdindex d96c21e0d..c6a2bb32e 100644--- a/docs/zh/concepts/11-multi-tenant.md+++ b/docs/zh/concepts/11-multi-tenant.md@@ -1,11 +1,11 @@# 多租户-OpenViking 的多租户不是“为每个团队部署一套独立服务”,而是在同一个 OpenViking Server 内,用 `account`、`user`、`agent` 三层身份边界来隔离和共享数据。+OpenViking 的多租户不是“为每个团队部署一套独立服务”,而是在同一个 OpenViking Server 内,用 `account` 和 `user` 两层身份边界来隔离和共享数据。它适合两类典型场景:- 多个团队或客户共享一套 OpenViking 服务,但数据必须隔离-- 一个团队内的多个用户和多个 Agent 需要共享资源、隔离记忆+- 一个团队内的多个用户需要共享资源、隔离记忆## 能做什么@@ -15,7 +15,6 @@ OpenViking 的多租户不是“为每个团队部署一套独立服务”,而- 用 `account` 隔离不同团队的数据- 在同一个 `account` 内共享 `resources`- 用 `user` 隔离用户级记忆和会话-- 用 `agent_id` 进一步区分 agent 级记忆、技能和指令空间- 用 ROOT / ADMIN / USER 角色分层管理权限- 支持 OpenClaw 插件、Vikingbot、CLI、HTTP SDK 等不同接入方式@@ -27,7 +26,7 @@ OpenViking 的多租户不是“为每个团队部署一套独立服务”,而- 不同 `account` 之间的数据默认完全隔离- Root 用户可以创建、删除 `account`-- `resources`、`user`、`agent`、`session` 都落在某个 `account` 下+- `resources`、`user`、`session` 都落在某个 `account` 下### `user_id`@@ -37,21 +36,13 @@ OpenViking 的多租户不是“为每个团队部署一套独立服务”,而- 普通 user 只能访问自己的 user space- admin 可以管理本 account 下的用户-### `agent_id`--`agent_id` 用于区分 agent 级空间。--- Agent URI 形状由 account 级 namespace policy 决定-- `isolate_agent_scope_by_user = false` 时使用 `viking://agent/{agent_id}/...`-- `isolate_agent_scope_by_user = true` 时使用 `viking://agent/{agent_id}/user/{user_id}/...`-### 角色| 角色 | 作用域 | 典型能力 ||------|--------|----------|| ROOT | 全局 | 创建/删除 account、跨租户访问、管理用户 || ADMIN | 单个 account | 管理本 account 的用户、重置 user key |-| USER | 单个 account | 访问自己的 user/agent/session 数据和 account 内共享资源 |+| USER | 单个 account | 访问自己的 user/peer/session 数据和 account 内共享资源 |## 认证模式@@ -73,7 +64,7 @@ OpenViking Server 支持两种多租户相关认证模式:如果 `auth_mode = "api_key"` 且未配置 `root_api_key`,服务端会进入开发模式:- 默认所有请求都被视为 ROOT-- 默认身份是 `default/default/default`+- 默认身份是 `default/default`- 只允许绑定在 localhost 上使用## 共享与隔离边界@@ -84,7 +75,6 @@ OpenViking Server 支持两种多租户相关认证模式:|----------|---------------------|-------------------|--------------|| `resources` | 否 | 是 | account || `user` | 否 | 否 | user |-| `agent` | 否 | 由 account 级 namespace policy 决定 | 默认 `agent` || `session` | 否 | 否 | user / session |### 存储层@@ -94,7 +84,6 @@ OpenViking Server 支持两种多租户相关认证模式:```textviking://resources/project-a/viking://user/alice/memories/-viking://agent/91f3ab12cd34/memories/```但底层存储会自动带上 account 前缀:@@ -102,10 +91,9 @@ viking://agent/91f3ab12cd34/memories/```text/local/{account_id}/resources/project-a//local/{account_id}/user/alice/memories/-/local/{account_id}/agent/91f3ab12cd34/memories/```-因此多租户隔离不是靠“不同 URI 前缀”,而是靠请求上下文中的 `account_id`、`user_id`、`agent_id` 共同生效。+因此多租户隔离不是靠“不同 URI 前缀”,而是靠请求上下文中的 `account_id` 和 `user_id` 共同生效。### 检索层@@ -113,7 +101,7 @@ viking://agent/91f3ab12cd34/memories/- 非 ROOT 请求会自动按 `account_id` 过滤- `resources` 会允许检索 account 内共享资源-- `memory` 和 `skill` 会进一步按当前 `user space` / `agent space` 过滤+- `memory` 和 `skill` 会进一步按当前 `user space` 过滤这意味着“能搜到什么”与“能读到什么”保持一致,不会因为向量召回而越权。@@ -160,34 +148,39 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts/acme/users \```bashcurl http://localhost:1933/api/v1/fs/ls?uri=viking:// \- -H "X-API-Key: <bob-user-key>" \- -H "X-OpenViking-Agent: coding-agent"+ -H "X-API-Key: <bob-user-key>"```这样服务端可以直接从 key 反解身份,无需额外传 `account` / `user`。-### 5. 只有 ROOT 访问租户级数据 API 时才显式带租户头+### 5. 数据 API 身份来自 user 或 admin key-ROOT 访问 Admin API 不需要租户头,但访问 `ls`、`find`、`sessions` 这类租户级数据 API 时,必须显式指定目标租户:+在 `api_key` 模式下,`ls`、`find`、`sessions` 这类租户级数据 API 会从 API+key 自身解析有效的 account 和 user。不要在该模式下发送+`X-OpenViking-Account` 或 `X-OpenViking-User`;基于 header 的身份断言只属于+trusted mode。++`ADMIN` key 可以用它自己的 account/user 身份访问数据 API:```bashcurl http://localhost:1933/api/v1/fs/ls?uri=viking:// \- -H "X-API-Key: <root-key>" \- -H "X-OpenViking-Account: acme" \- -H "X-OpenViking-User: alice" \- -H "X-OpenViking-Agent: coding-agent"+ -H "X-API-Key: <admin-user-key>"```+`ROOT` key 用于 Admin API 以及少量 system/monitoring API。它在 `api_key`+模式下不能访问租户级数据 API,因为它没有绑定到某个租户用户。数据访问请使用+user/admin key;如果需要上游断言身份,请使用 trusted mode。+## 接入实践### OpenClaw 插件 2.0:每个实例使用 user keyOpenClaw 插件当前的多租户实践是“插件侧只持有一个用户身份”:-- 远程模式配置 `baseUrl + apiKey + agent_prefix`+- 远程模式配置 `baseUrl + apiKey`,可选 `peer_role` / `peer_prefix`- `apiKey` 推荐配置为某个 user 的 user key- 服务端从 user key 自动解析 `account_id` 和 `user_id`-- 插件显式传递 `X-OpenViking-Agent`+- 插件把 OpenClaw agent 身份保留在 peer/session metadata 中,而不是租户 header 中典型配置:@@ -195,25 +188,27 @@ OpenClaw 插件当前的多租户实践是“插件侧只持有一个用户身openclaw config set plugins.entries.openviking.config.mode remoteopenclaw config set plugins.entries.openviking.config.baseUrl "http://your-server:1933"openclaw config set plugins.entries.openviking.config.apiKey "<user-api-key>"-openclaw config set plugins.entries.openviking.config.agent_prefix "<agent-prefix>"+openclaw config set plugins.entries.openviking.config.peer_role assistant+openclaw config set plugins.entries.openviking.config.peer_prefix "<peer-prefix>"```这种模式的特点:- 接入简单,插件不需要管理 account/user 生命周期- 最适合“一个 OpenClaw 实例对应一个 OpenViking 用户”的场景-- `agent_prefix` 参与决定 agent 级空间,便于区分不同 OpenClaw 实例或不同 agent 角色-- 同一 account 内的 `resources` 可共享,`user` / `agent` memory 会按身份隔离+- `peer_prefix` 用于区分 OpenClaw 运行时身份,参与 peer/session 元数据+- 同一 account 内的 `resources` 可共享,memory 按 user scope 隔离### OpenClaw 插件为何通常不配 `account` / `user`因为在 `api_key` 模式下,user key 已经足够表达身份:- `account`、`user` 由服务端从 key 反解-- 插件只需要额外告诉服务端当前的 `agent_prefix`-- 插件内部会根据运行时身份去解析默认的 `user` / `agent` 记忆空间+- 插件可以提供 `peer_prefix` 作为运行时身份标签+- 插件内部写入 user-scoped memory,并用 `peer_id` 表达每条消息的说话人-如果给插件直接配置 root key,则普通租户数据 API 会缺少 `X-OpenViking-Account` / `X-OpenViking-User`,这不适合作为日常读写方式。+如果给插件直接配置 root key,则普通租户数据 API 没有从 key 绑定出来的租户用户,+这不适合作为日常读写方式。### Vikingbot:root key 代管用户身份@@ -266,15 +261,14 @@ Root key 主要用于:- 重置 key- 运维和调试-正常业务请求优先使用 user key。+正常业务请求应按调用者身份使用 user key 或 admin key。-### 2. `agentId` 不决定 account+### 2. `peer_id` 不决定 account-`agentId` 只决定 agent 级空间,不决定租户归属。+`peer_id` 表示共享会话里的消息说话人,不创建租户或文件系统 namespace。- account 边界由 `account_id` 决定- user 边界由 `user_id` 决定-- agent 边界由 `agent_id` 决定### 3. 不配置 `root_api_key` 不等于“单租户正式部署”@@ -291,7 +285,7 @@ Root key 主要用于:## 相关文档- [认证](../guides/04-authentication.md) - 认证模式、请求头和 key 规则-- [配置](../guides/01-configuration.md) - `root_api_key`、`auth_mode`、`agent_id`+- [配置](../guides/01-configuration.md) - `root_api_key` 和 `auth_mode`- [管理员(多租户)](../api/08-admin.md) - Admin API 参考- [API 概览](../api/01-overview.md) - CLI / HTTP 连接方式- [数据加密](./10-encryption.md) - 多租户下的静态数据加密diff --git a/docs/zh/concepts/12-metrics.md b/docs/zh/concepts/12-metrics.mdindex b002d4bae..c4cd9c0c7 100644--- a/docs/zh/concepts/12-metrics.md+++ b/docs/zh/concepts/12-metrics.md@@ -503,7 +503,7 @@ max by (job) (openviking_feedback_events_total{valid="0"})## 相关文档- [架构概述](./01-architecture.md) - OpenViking 总体架构-- [多租户](./11-multi-tenant.md) - `account/user/agent` 隔离模型+- [多租户](./11-multi-tenant.md) - `account/user/peer` 隔离模型- [数据加密](./10-encryption.md) - 存储层加密与隔离- [Metrics API](../api/09-metrics.md) - `/metrics` 端点用法- [VikingBot 问答效果反馈观测方案设计](../../../bot/docs/vikingbot-feedback-observability-design.md) - feedback 指标与阶段性落地背景diff --git a/docs/zh/concepts/13-privacy.md b/docs/zh/concepts/13-privacy.mdindex 3e3a14bf8..56a18233e 100644--- a/docs/zh/concepts/13-privacy.md+++ b/docs/zh/concepts/13-privacy.md@@ -91,10 +91,10 @@ fs.read(uri)### URI 匹配-当前支持通过后缀识别 Skill:`/skills/{name}/SKILL.md`,可兼容:+当前支持通过后缀识别 Skill:`/skills/{name}/SKILL.md`,可兼容 user-scoped skill 路径,例如:-- `viking://agent/skills/{name}/SKILL.md`-- `viking://agent/{agent_id}/skills/{name}/SKILL.md`+- `viking://user/skills/{name}/SKILL.md`+- `viking://user/{user_id}/skills/{name}/SKILL.md`### restore 规则@@ -133,7 +133,7 @@ openviking privacy list skillopenviking privacy skill <target_key>openviking privacy upsert skill <target_key> --values-json '{"api_key":"..."}'openviking privacy activate skill <target_key> <version>-openviking read viking://agent/default/skills/<target_key>/SKILL.md+openviking read viking://user/default/skills/<target_key>/SKILL.md```---diff --git a/docs/zh/faq/faq.md b/docs/zh/faq/faq.mdindex c1c7f6c66..37805dd40 100644--- a/docs/zh/faq/faq.md+++ b/docs/zh/faq/faq.md@@ -45,10 +45,10 @@ viking://├── resources/ # 知识库:文档、代码、网页等│ └── my_project/├── user/ # 用户上下文-│ └── memories/ # 用户记忆(偏好、实体、事件)-└── agent/ # Agent 上下文- ├── skills/ # 可调用技能- └── memories/ # Agent 记忆(案例、模式)+│ ├── skills/ # 可调用技能+│ ├── memories/ # 用户记忆(偏好、实体、事件)+│ └── peers/ # 针对稳定 peer 的一对多记忆+└── session/ # 会话与历史归档```## 安装与配置diff --git a/docs/zh/getting-started/03-quickstart-server.md b/docs/zh/getting-started/03-quickstart-server.mdindex f02edee8e..8b43a3de7 100644--- a/docs/zh/getting-started/03-quickstart-server.md+++ b/docs/zh/getting-started/03-quickstart-server.md@@ -65,9 +65,9 @@ client = ov.SyncHTTPClient(url="http://localhost:1933")服务端启用认证后,需要传入 `api_key`。OpenViking 使用两层 API Key 体系,请根据场景选择:-**常规数据访问:使用 `user_key`(推荐)**+**常规数据访问:使用 `user_key` 或 `admin_key`**-大多数场景应使用 `user_key`,可直接调用 `add_resource`、`find`、`ls` 等租户级 API:+大多数场景应使用 `user_key`,也可以使用绑定到管理员用户的 `admin_key`。两者都可直接调用 `add_resource`、`find`、`ls` 等租户级 API:```pythonimport openviking as ov@@ -75,15 +75,14 @@ import openviking as ovclient = ov.SyncHTTPClient(url="http://localhost:1933",api_key="<user-key>",- agent_id="my-agent", # 可选)```-> `user_key` 通过 Admin API 创建(参见 [认证文档](../guides/04-authentication.md)),服务端可自动识别其所属租户。+> `user_key` / `admin_key` 通过 Admin API 创建(参见 [认证文档](../guides/04-authentication.md)),服务端可自动识别其所属租户和用户。**管理操作:使用 `root_key`**-`root_key` 适用于管理操作(创建账户、系统状态等)。如需用 `root_key` 访问租户级 API,**必须**同时传入 `account` 和 `user`,否则服务端会拒绝请求:+`root_key` 只适用于管理操作(创建账户、系统状态等)和少量 system/monitoring API。常规数据访问不要使用 `root_key`,也不要通过 `account` / `user` header 模拟某个用户;数据面应使用对应的 `user_key` 或 `admin_key`。```pythonimport openviking as ov@@ -91,13 +90,10 @@ import openviking as ovclient = ov.SyncHTTPClient(url="http://localhost:1933",api_key="<root-key>",- account="acme", # 必须:目标租户- user="alice", # 必须:目标用户)```-> ⚠️ 使用 `root_key` 调用 `add_resource`、`find` 等租户级 API 时,如果未提供 `account`/`user`,会收到:-> `ROOT requests to tenant-scoped APIs must include X-OpenViking-Account and X-OpenViking-User headers`+> 如果确实需要由上游网关注入 `account` / `user` 身份,应使用 `trusted` 模式;在默认 `api_key` 模式下,只有绑定了用户身份的 user/admin key 能访问自己的数据空间。更多认证细节(trusted 模式、CLI 配置等)请参见 [认证文档](../guides/04-authentication.md)。diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.mdindex ca736fd01..7c66dc6e4 100644--- a/docs/zh/guides/01-configuration.md+++ b/docs/zh/guides/01-configuration.md@@ -1128,7 +1128,7 @@ openviking-server --config /path/to/ov.conf{"memory": {"version": "v2",- "agent_scope_mode": "user+agent"+ "agent_memory_enabled": false}}```@@ -1136,9 +1136,7 @@ openviking-server --config /path/to/ov.conf| 字段 | 说明 | 默认值 ||------|------|--------|| `version` | 记忆实现版本。仅支持 `"v2"`(#2264 已移除旧版 `"v1"`;传入 `"v1"` 会在配置加载时抛出 `ValueError`)。 | `"v2"` |-| `agent_scope_mode` | 已废弃且被忽略。仅为兼容旧版 `ov.conf` 保留。当前 agent/user 命名空间行为由 account 级 namespace policy 控制。 | `"user+agent"` |--`agent_scope_mode` 不再影响命名空间行为。服务端现在根据 account 级 namespace policy 在 `viking://agent/{agent_id}/...` 与 `viking://agent/{agent_id}/user/{user_id}/...` 之间选择。+| `agent_memory_enabled` | 在用户记忆抽取之后启用 trajectory/experience 记忆抽取。 | `false` |### ovcli.conf@@ -1152,9 +1150,6 @@ HTTP 客户端(`SyncHTTPClient` / `AsyncHTTPClient`)和 CLI 工具连接远{"url": "http://localhost:1933","api_key": "your-secret-key",- "account": "acme",- "user": "alice",- "agent_id": "my-agent","profile": false,"upload": {"mode": "local",@@ -1169,9 +1164,8 @@ HTTP 客户端(`SyncHTTPClient` / `AsyncHTTPClient`)和 CLI 工具连接远|------|------|--------|| `url` | 服务端地址 | (必填) || `api_key` | API Key 认证(root key 或 user key) | `null`(无认证) |-| `account` | 默认发送为 `X-OpenViking-Account` 的租户标识 | `null` |-| `user` | 默认发送为 `X-OpenViking-User` 的用户标识 | `null` |-| `agent_id` | Agent 标识,用于 agent space 隔离 | `null` |+| `account` | 可选的 trusted 模式 account 身份 header | `null` |+| `user` | 可选的 trusted 模式 user 身份 header | `null` || `profile` | 是否默认给 HTTP 请求追加 `profile=1`。对 Python HTTP client 和 `ov` CLI 都生效;也可通过 CLI 的 `--profile` 单次开启。是否真正生效还取决于服务端是否开启 `server.profile_enabled`。 | `false` || `upload.ignore_dirs` | `add-resource` 默认忽略目录列表(CSV) | `null` || `upload.include` | `add-resource` 默认包含模式(CSV) | `null` |@@ -1180,10 +1174,10 @@ HTTP 客户端(`SyncHTTPClient` / `AsyncHTTPClient`)和 CLI 工具连接远本地目录上传会默认遵循 `.gitignore`(根目录和子目录,含 `!` 反向规则)。`ignore_dirs/include/exclude` 会在此基础上进一步过滤。-也可以在单次命令里用 CLI 参数覆盖这些身份字段:+trusted 网关部署下,也可以在单次命令里用 CLI 参数覆盖这些身份字段:```bash-openviking --account acme --user alice --agent-id assistant-2 ls viking://+openviking --account acme --user alice ls viking://```对于 `add-resource`,上传过滤参数会与 `ovcli.conf` 默认值做合并(追加),不会覆盖:diff --git a/docs/zh/guides/03-deployment.md b/docs/zh/guides/03-deployment.mdindex cdef9d358..4dc0eaa9f 100644--- a/docs/zh/guides/03-deployment.md+++ b/docs/zh/guides/03-deployment.md@@ -147,7 +147,7 @@ sudo journalctl -u openviking.service -f```pythonimport openviking as ov-client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key", agent_id="my-agent")+client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")client.initialize()results = client.find("how to use openviking")diff --git a/docs/zh/guides/04-authentication.md b/docs/zh/guides/04-authentication.mdindex 79943af9f..8f206518e 100644--- a/docs/zh/guides/04-authentication.md+++ b/docs/zh/guides/04-authentication.md@@ -8,8 +8,8 @@ OpenViking 使用两层 API Key 体系:| Key 类型 | 创建方式 | 角色 | 用途 ||----------|---------|------|------|-| Root Key | 服务端配置(`root_api_key`) | ROOT | 全部操作 + 管理操作 |-| User Key | Admin API | ADMIN 或 USER | 按 account 访问 |+| Root Key | 服务端配置(`root_api_key`) | ROOT | 账户管理 + 少量 system/monitoring 操作 |+| User Key | Admin API | ADMIN 或 USER | 租户内数据访问;ADMIN 还可管理本 account 下的用户 |所有 API Key 均为纯随机 token,不携带身份信息。服务端通过先比对 root key、再查 user key 索引的方式确定身份。@@ -17,8 +17,8 @@ OpenViking 使用两层 API Key 体系:| 模式 | `server.auth_mode` | 身份来源 | 典型使用场景 ||------|--------------------|----------|--------------|-| API Key 模式 | `"api_key"` | API Key,root 请求可附带租户请求头 | 标准多租户部署 |-| Trusted 模式 | `"trusted"` | `X-OpenViking-Account` / `X-OpenViking-User` / 可选 `X-OpenViking-Agent`;非 localhost 部署还必须配置 `root_api_key`。角色会从 APIKeyManager 查询(如果用户存在) | 部署在受信网关或内网边界之后 |+| API Key 模式 | `"api_key"` | API Key;数据归属从 user/admin key 解析 | 标准多租户部署 |+| Trusted 模式 | `"trusted"` | `X-OpenViking-Account` / `X-OpenViking-User`;非 localhost 部署还必须配置 `root_api_key`。角色会从 APIKeyManager 查询(如果用户存在) | 部署在受信网关或内网边界之后 || Dev 模式 | `"dev"` | 无认证,始终为 ROOT | 仅限本地开发 |如果未显式配置 `auth_mode`:@@ -96,9 +96,7 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \-H "Content-Type: application/json" \-d '{"account_id": "acme",- "admin_user_id": "alice",- "isolate_user_scope_by_agent": true,- "isolate_agent_scope_by_user": false+ "admin_user_id": "alice"}'```@@ -128,7 +126,6 @@ import openviking as ovclient = ov.SyncHTTPClient(url="http://localhost:1933",api_key="<user-key>",- agent_id="my-agent")```@@ -137,19 +134,16 @@ client = ov.SyncHTTPClient(```json{"url": "http://localhost:1933",- "api_key": "<user-key>",- "account": "acme",- "user": "alice",- "agent_id": "my-agent"+ "api_key": "<user-key>"}```-如果使用普通 `user key`,`account` 和 `user` 可以省略,因为服务端可以从 key 反查出来;如果使用 `trusted` 模式,或者用 `root key` 访问租户级 API,则建议明确配置。+如果使用普通 `user key` 或 `admin key`,`account` 和 `user` 可以省略,因为服务端可以从 key 反查出来;如果使用 `trusted` 模式,则建议明确配置。**CLI 覆盖参数**```bash-openviking --account acme --user alice --agent-id my-agent ls viking://+openviking --account acme --user alice ls viking://```### 使用 --sudo 和 Root API Key@@ -160,10 +154,7 @@ CLI 支持在 `ovcli.conf` 中同时配置 `api_key`(用于普通用户操作{"url": "http://localhost:1933","api_key": "<user-key>",- "root_api_key": "<root-key>",- "account": "acme",- "user": "alice",- "agent_id": "my-agent"+ "root_api_key": "<root-key>"}```@@ -186,41 +177,26 @@ ov --sudo system status- `ovcli.conf` 中未配置 `root_api_key` 时会报错- 请求时使用 `root_api_key` 替代 `api_key`-### 使用 Root Key 访问租户数据--使用 root key 访问租户级数据 API(如 `ls`、`find`、`sessions` 等)时,必须指定目标 account 和 user,否则服务端将拒绝请求。Admin API 和系统状态端点不受此限制。--**curl**--```bash-curl http://localhost:1933/api/v1/fs/ls?uri=viking:// \- -H "X-API-Key: your-secret-root-key" \- -H "X-OpenViking-Account: acme" \- -H "X-OpenViking-User: alice"-```--**Python SDK**+### 租户数据访问-```python-import openviking as ov+租户级数据 API(如 `ls`、`find`、resources、sessions 等)在 `api_key`+模式下必须使用绑定了 account/user 的 key。这个 key 可以是 `USER` key,也可以是+`ADMIN` key;`ADMIN` key 会以它自己的 user 身份访问数据,不能通过+`X-OpenViking-Account` / `X-OpenViking-User` 切换身份。-client = ov.SyncHTTPClient(- url="http://localhost:1933",- api_key="your-secret-root-key",- account="acme",- user="alice",-)-```+`ROOT` key 没有绑定租户 user,因此在 `api_key` 模式下不能访问租户级数据 API。+如果部署需要由上游网关断言 `account` / `user`,请使用 `trusted` 模式,而不是在+root key 请求上携带身份 header。**ovcli.conf**```json{"url": "http://localhost:1933",- "api_key": "your-secret-root-key",+ "auth_mode": "trusted",+ "api_key": "your-trusted-server-key","account": "acme",- "user": "alice",- "agent_id": "my-agent"+ "user": "alice"}```@@ -241,7 +217,6 @@ Trusted 模式规则:- 普通数据访问不需要先注册 user key,也不依赖 user key 分发流程- 租户级请求必须包含 `X-OpenViking-Account` 和 `X-OpenViking-User`-- `X-OpenViking-Agent` 可选,缺省为 `default`- `/api/v1/admin/*` 是特例:如果没有显式身份,trusted 模式会将请求视为 ROOT,用于只通过部署级 root API key 认证的受信上游- 角色通过在 APIKeyManager 中查找 account/user 确定。如果用户存在,使用其配置的角色;否则默认为 `USER`- trusted 身份完全来自请求头,而不是 user key;如果同时配置了 `root_api_key`,它仍然只是“这个上游是被允许的 trusted 调用方”的证明@@ -262,8 +237,7 @@ Trusted 模式规则:```bashcurl http://localhost:1933/api/v1/fs/ls?uri=viking:// \-H "X-OpenViking-Account: acme" \- -H "X-OpenViking-User: alice" \- -H "X-OpenViking-Agent: my-agent"+ -H "X-OpenViking-User: alice"```**Python SDK**@@ -275,7 +249,6 @@ client = ov.SyncHTTPClient(url="http://localhost:1933",account="acme",user="alice",- agent_id="my-agent",)```diff --git a/docs/zh/guides/05-observability.md b/docs/zh/guides/05-observability.mdindex 029bed627..9694b0813 100644--- a/docs/zh/guides/05-observability.md+++ b/docs/zh/guides/05-observability.md@@ -135,7 +135,7 @@ ov tui viking://resources这个 TUI 适合做两类观测:-- 看 `viking://resources`、`viking://user`、`viking://agent`、`viking://session` 下实际落了哪些数据+- 看 `viking://resources`、`viking://user`、`viking://session` 下实际落了哪些数据- 看某个 URI 对应的向量记录是否已经写入,以及数量是否符合预期常用按键:diff --git a/docs/zh/guides/06-mcp-integration.md b/docs/zh/guides/06-mcp-integration.mdindex 16c9f5293..544ab06ce 100644--- a/docs/zh/guides/06-mcp-integration.md+++ b/docs/zh/guides/06-mcp-integration.md@@ -105,7 +105,7 @@ claude mcp add --transport http openviking \| 工具 | 说明 | 主要参数 ||------|------|----------|-| `search` | 语义搜索记忆、资源和技能 | `query`, `target_uri`(可选), `limit`, `min_score` |+| `search` | 语义搜索记忆、资源和技能 | `query`, `target_uri`(可选), `peer_id`(可选), `limit`, `min_score` || `read` | 读取一个或多个 `viking://` URI 的内容 | `uris`(单个字符串或数组) || `list` | 列出 `viking://` 目录下的条目 | `uri`, `recursive`(可选) || `store` | 存储消息到长期记忆(触发记忆提取) | `messages`(`{role, content}` 列表) |diff --git a/docs/zh/guides/09-ovpack.md b/docs/zh/guides/09-ovpack.mdindex b9ca3031f..eb0fa58ff 100644--- a/docs/zh/guides/09-ovpack.md+++ b/docs/zh/guides/09-ovpack.md@@ -13,14 +13,12 @@ checksum,保证包内容没有偏离 manifest;如果攻击者能同时篡改- `viking://resources/...`- `viking://user/...`-- `viking://agent/...`- `viking://session/...`全量迁移使用单独的 `backup/restore`,它会把公开 scope root 一起打进备份包:- `viking://resources`- `viking://user`-- `viking://agent`- `viking://session``temp`、`queue`、`upload`、锁文件、watch control 文件、`.relations.json` 等内部或运行态数据@@ -307,7 +305,7 @@ type, context_type, level, name, description, tags, abstract这些字段不会从包里直接恢复,而是在目标环境重新生成:```text-id, uri, account_id, owner_user_id, owner_agent_id, owner_space,+id, uri, account_id, owner_user_id, owner_space,created_at, updated_at, active_count```@@ -386,11 +384,11 @@ ov export viking://user/default/memories ./exports/user-memories.ovpackov import ./exports/user-memories.ovpack viking://user/default/ --on-conflict overwrite```-Agent 记忆:+用户记忆:```bash-ov export viking://agent/default/memories ./exports/agent-memories.ovpack-ov import ./exports/agent-memories.ovpack viking://agent/default/ --on-conflict overwrite+ov export viking://user/default/memories ./exports/agent-memories.ovpack+ov import ./exports/agent-memories.ovpack viking://user/default/ --on-conflict overwrite```Session 只恢复文件状态,不触发向量化:diff --git a/examples/basic-usage/README.md b/examples/basic-usage/README.mdindex a85d43f9e..629af095e 100644--- a/examples/basic-usage/README.md+++ b/examples/basic-usage/README.md@@ -110,7 +110,6 @@ If server authentication is enabled, use a `user_key` for normal data access:client = ov.SyncHTTPClient(url="http://localhost:1933",api_key="<user-key>",- agent_id="my-agent",)```@@ -153,8 +152,7 @@ This same URI model applies to memories and skills as well:- `viking://resources/`- `viking://user/memories/`-- `viking://agent/memories/`-- `viking://agent/skills/`+- `viking://user/skills/`### Retrievaldiff --git a/examples/basic-usage/README_CN.md b/examples/basic-usage/README_CN.mdindex 3f0e12227..46d6a9ad1 100644--- a/examples/basic-usage/README_CN.md+++ b/examples/basic-usage/README_CN.md@@ -111,7 +111,6 @@ client.initialize()client = ov.SyncHTTPClient(url="http://localhost:1933",api_key="<user-key>",- agent_id="my-agent",)```@@ -155,8 +154,7 @@ content = client.read("viking://resources/my-project/README.md")- `viking://resources/`- `viking://user/memories/`-- `viking://agent/memories/`-- `viking://agent/skills/`+- `viking://user/skills/`### 检索diff --git a/examples/claude-code-memory-plugin/.mcp.json b/examples/claude-code-memory-plugin/.mcp.jsonindex bfd632888..bf7c60ca7 100644--- a/examples/claude-code-memory-plugin/.mcp.json+++ b/examples/claude-code-memory-plugin/.mcp.json@@ -5,8 +5,7 @@"headers": {"Authorization": "Bearer ${OPENVIKING_API_KEY:-}","X-OpenViking-Account": "${OPENVIKING_ACCOUNT:-}",- "X-OpenViking-User": "${OPENVIKING_USER:-}",- "X-OpenViking-Agent": "${OPENVIKING_AGENT_ID:-}"+ "X-OpenViking-User": "${OPENVIKING_USER:-}"}}}diff --git a/examples/claude-code-memory-plugin/README.md b/examples/claude-code-memory-plugin/README.mdindex 63b027363..b2f01de0b 100644--- a/examples/claude-code-memory-plugin/README.md+++ b/examples/claude-code-memory-plugin/README.md@@ -37,8 +37,7 @@ Easiest path — write `~/.openviking/ovcli.conf` (the same file `ov` CLI uses):"url": "https://your-openviking-server.example.com","api_key": "<your-api-key>","account": "my-team",- "user": "alice",- "agent_id": "claude-code"+ "user": "alice"}```@@ -71,8 +70,7 @@ claude mcp add --scope user --transport http openviking \'${OPENVIKING_URL:-http://127.0.0.1:1933}/mcp' \--header 'Authorization: Bearer ${OPENVIKING_API_KEY:-}' \--header 'X-OpenViking-Account: ${OPENVIKING_ACCOUNT:-}' \- --header 'X-OpenViking-User: ${OPENVIKING_USER:-}' \- --header 'X-OpenViking-Agent: ${OPENVIKING_AGENT_ID:-}'+ --header 'X-OpenViking-User: ${OPENVIKING_USER:-}'# Merge plugin hooks into ~/.claude/settings.json (with backup).mkdir -p ~/.claude && [ -f ~/.claude/settings.json ] || echo '{}' > ~/.claude/settings.json@@ -147,7 +145,7 @@ Re-source your rc (`source ~/.zshrc`, or `source ~/.bashrc` on bash) and restartEvery plugin field follows this chain (highest → lowest):1. **Environment variables** (`OPENVIKING_*` — see tables below)-2. **`ovcli.conf`** — CLI client config (`~/.openviking/ovcli.conf` or `OPENVIKING_CLI_CONFIG_FILE`); only carries connection fields (`url`, `api_key`, `account`, `user`, `agent_id`)+2. **`ovcli.conf`** — CLI client config (`~/.openviking/ovcli.conf` or `OPENVIKING_CLI_CONFIG_FILE`); only carries connection fields (`url`, `api_key`, `account`, `user`)3. **`ov.conf`** — server config (`~/.openviking/ov.conf` or `OPENVIKING_CONFIG_FILE`); the plugin reads `server.url`, `server.root_api_key`, and a legacy `claude_code` block if present (see [Legacy `claude_code` block](#legacy-claude_code-block-in-ovconf))4. **Built-in defaults** (`http://127.0.0.1:1933`, no auth)@@ -165,7 +163,9 @@ All plugin behavior can be set via env vars. Connection / identity vars affect b| `OPENVIKING_API_KEY` / `OPENVIKING_BEARER_TOKEN` | API key; sent as `Authorization: Bearer <key>` || `OPENVIKING_ACCOUNT` | Multi-tenant account (`X-OpenViking-Account` header) || `OPENVIKING_USER` | Multi-tenant user (`X-OpenViking-User` header) |-| `OPENVIKING_AGENT_ID` | Agent identity, default `claude-code` (`X-OpenViking-Agent` header) |+| `OPENVIKING_PEER_ID` | Optional stable peer for recall and captured session messages |++When `OPENVIKING_PEER_ID` is set, hooks pass it as request-level `peer_id`. Subagent capture falls back to Claude's `agent_id` when no explicit peer is configured, so different subagents can keep separate peer memory by default.#### Recall tuningdiff --git a/examples/claude-code-memory-plugin/README_CN.md b/examples/claude-code-memory-plugin/README_CN.mdindex 75ef7a945..2d109f56e 100644--- a/examples/claude-code-memory-plugin/README_CN.md+++ b/examples/claude-code-memory-plugin/README_CN.md@@ -37,8 +37,7 @@ curl http://localhost:1933/health # 或者你的远程 URL"url": "https://your-openviking-server.example.com","api_key": "<your-api-key>","account": "my-team",- "user": "alice",- "agent_id": "claude-code"+ "user": "alice"}```@@ -71,8 +70,7 @@ claude mcp add --scope user --transport http openviking \'${OPENVIKING_URL:-http://127.0.0.1:1933}/mcp' \--header 'Authorization: Bearer ${OPENVIKING_API_KEY:-}' \--header 'X-OpenViking-Account: ${OPENVIKING_ACCOUNT:-}' \- --header 'X-OpenViking-User: ${OPENVIKING_USER:-}' \- --header 'X-OpenViking-Agent: ${OPENVIKING_AGENT_ID:-}'+ --header 'X-OpenViking-User: ${OPENVIKING_USER:-}'# 把插件 hooks 合并进 ~/.claude/settings.json(自动备份)mkdir -p ~/.claude && [ -f ~/.claude/settings.json ] || echo '{}' > ~/.claude/settings.json@@ -147,7 +145,7 @@ claude() {每个插件字段按从高到低:1. **环境变量**(`OPENVIKING_*`——见下方表格)-2. **`ovcli.conf`** — CLI 客户端配置(`~/.openviking/ovcli.conf` 或 `OPENVIKING_CLI_CONFIG_FILE`);只承载连接字段(`url`、`api_key`、`account`、`user`、`agent_id`)+2. **`ovcli.conf`** — CLI 客户端配置(`~/.openviking/ovcli.conf` 或 `OPENVIKING_CLI_CONFIG_FILE`);只承载连接字段(`url`、`api_key`、`account`、`user`)3. **`ov.conf`** — 服务器配置(`~/.openviking/ov.conf` 或 `OPENVIKING_CONFIG_FILE`);插件读 `server.url`、`server.root_api_key`,以及可选的遗留 `claude_code` 块(见 [遗留 `claude_code` 块](#遗留-claude_code-块在-ovconf-里))4. **内置默认值**(`http://127.0.0.1:1933`,无鉴权)@@ -165,7 +163,9 @@ claude() {| `OPENVIKING_API_KEY` / `OPENVIKING_BEARER_TOKEN` | API key;以 `Authorization: Bearer <key>` 发送 || `OPENVIKING_ACCOUNT` | 多租户 account(`X-OpenViking-Account` 头) || `OPENVIKING_USER` | 多租户 user(`X-OpenViking-User` 头) |-| `OPENVIKING_AGENT_ID` | Agent 身份,默认 `claude-code`(`X-OpenViking-Agent` 头) |+| `OPENVIKING_PEER_ID` | 可选的稳定 peer,用于自动召回和 session message 写入 |++设置 `OPENVIKING_PEER_ID` 后,hook 会把它作为请求级 `peer_id` 发送。未显式配置 peer 时,subagent 捕获会回退到 Claude 的 `agent_id`,让不同 subagent 默认落到不同 peer memory。#### 召回调优diff --git a/examples/claude-code-memory-plugin/scripts/auto-capture.mjs b/examples/claude-code-memory-plugin/scripts/auto-capture.mjsindex c7f44ec3b..0311fc276 100644--- a/examples/claude-code-memory-plugin/scripts/auto-capture.mjs+++ b/examples/claude-code-memory-plugin/scripts/auto-capture.mjs@@ -392,13 +392,16 @@ function sanitizePartsForSend(parts) {async function pushTurnsToOv(ovSessionId, turns) {let ok = 0;let failed = 0;+ const peerId = cfg.peerId || null;for (const turn of turns) {// Send structured parts: tool calls/results are dedicated `tool` parts, not// inlined into content, so the server can process them separately.const parts = sanitizePartsForSend(turn.parts);if (parts.length === 0) continue;- const res = await addMessage(fetchJSON, ovSessionId, { role: turn.role, parts });+ const payload = { role: turn.role, parts };+ if (peerId) payload.peer_id = peerId;+ const res = await addMessage(fetchJSON, ovSessionId, payload);if (res.ok) ok++;else failed++;}diff --git a/examples/claude-code-memory-plugin/scripts/auto-recall.mjs b/examples/claude-code-memory-plugin/scripts/auto-recall.mjsindex 0523c7a44..14ec792a7 100644--- a/examples/claude-code-memory-plugin/scripts/auto-recall.mjs+++ b/examples/claude-code-memory-plugin/scripts/auto-recall.mjs@@ -113,15 +113,14 @@ function dedupeItems(items) {}// ----------------------------------------------------------------------------// URI space resolution (mirrors memory-server.ts normalizeTargetUri)+// User URI space resolution// ----------------------------------------------------------------------------const USER_RESERVED_DIRS = new Set(["memories"]);-const AGENT_RESERVED_DIRS = new Set(["memories", "skills", "instructions", "workspaces"]);-const _spaceCache = {};+const USER_RESERVED_DIRS = new Set(["memories", "skills"]);+let _userSpaceCache = "";-async function resolveScopeSpace(scope) {- if (_spaceCache[scope]) return _spaceCache[scope];+async function resolveUserSpace() {+ if (_userSpaceCache) return _userSpaceCache;let fallbackSpace = "default";const status = await fetchJSON("/api/v1/system/status");@@ -129,36 +128,33 @@ async function resolveScopeSpace(scope) {fallbackSpace = status.result.user.trim();}- const reservedDirs = scope === "user" ? USER_RESERVED_DIRS : AGENT_RESERVED_DIRS;- const lsRes = await fetchJSON(`/api/v1/fs/ls?uri=${encodeURIComponent(`viking://${scope}`)}&output=original`);+ const lsRes = await fetchJSON(`/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`);if (lsRes.ok && Array.isArray(lsRes.result)) {const spaces = lsRes.result.filter(e => e?.isDir).map(e => (typeof e.name === "string" ? e.name.trim() : ""))- .filter(n => n && !n.startsWith(".") && !reservedDirs.has(n));+ .filter(n => n && !n.startsWith(".") && !USER_RESERVED_DIRS.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]; }+ if (spaces.includes(fallbackSpace)) { _userSpaceCache = fallbackSpace; return fallbackSpace; }+ if (spaces.includes("default")) { _userSpaceCache = "default"; return "default"; }+ if (spaces.length === 1) { _userSpaceCache = spaces[0]; return spaces[0]; }}}- _spaceCache[scope] = fallbackSpace;+ _userSpaceCache = fallbackSpace;return fallbackSpace;}async function resolveTargetUri(targetUri) {const trimmed = targetUri.trim().replace(/\/+$/, "");- const m = trimmed.match(/^viking:\/\/(user|agent)(?:\/(.*))?$/);+ const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);if (!m) return trimmed;- const scope = m[1];- const rawRest = (m[2] ?? "").trim();+ const rawRest = (m[1] ?? "").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("/")}`;+ if (!USER_RESERVED_DIRS.has(parts[0])) return trimmed;+ const space = await resolveUserSpace();+ return `viking://user/${space}/${parts.join("/")}`;}// ---------------------------------------------------------------------------@@ -168,15 +164,16 @@ async function resolveTargetUri(targetUri) {const SOURCES = [{ type: "memory", uri: "viking://user/memories", bucket: "memories" },- { type: "memory", uri: "viking://agent/memories", bucket: "memories" },- { type: "skill", uri: "viking://agent/skills", bucket: "skills" },+ { type: "skill", uri: "viking://user/skills", bucket: "skills" },];async function searchOneSource(query, source, limit) {const resolvedUri = await resolveTargetUri(source.uri);+ const body = { query, target_uri: resolvedUri, limit, score_threshold: 0 };+ if (cfg.peerId) body.peer_id = cfg.peerId;const res = await fetchJSON("/api/v1/search/find", {method: "POST",- body: JSON.stringify({ query, target_uri: resolvedUri, limit, score_threshold: 0 }),+ body: JSON.stringify(body),});if (!res.ok) return [];const items = res.result?.[source.bucket] || [];diff --git a/examples/claude-code-memory-plugin/scripts/config.mjs b/examples/claude-code-memory-plugin/scripts/config.mjsindex 000342014..416bbfcab 100644--- a/examples/claude-code-memory-plugin/scripts/config.mjs+++ b/examples/claude-code-memory-plugin/scripts/config.mjs@@ -3,7 +3,7 @@** Resolution priority (highest → lowest):* 1. Environment variables (OPENVIKING_*)- * 2. ovcli.conf (CLI client config: url, api_key, account, user, agent_id) — connection only+ * 2. ovcli.conf (CLI client config: url, api_key, account, user) — connection only* 3. ov.conf fields (server section + claude_code section) — legacy; new deployments should* prefer env vars. Tuning fields under claude_code.* are still honored for backward compat.* 4. Built-in defaults@@ -16,7 +16,7 @@* Env vars covered (full list):* Connection / identity:* OPENVIKING_URL / OPENVIKING_BASE_URL, OPENVIKING_API_KEY / OPENVIKING_BEARER_TOKEN,- * OPENVIKING_ACCOUNT, OPENVIKING_USER, OPENVIKING_AGENT_ID+ * OPENVIKING_ACCOUNT, OPENVIKING_USER, OPENVIKING_PEER_ID* Recall tuning:* OPENVIKING_AUTO_RECALL, OPENVIKING_RECALL_LIMIT, OPENVIKING_RECALL_TOKEN_BUDGET,* OPENVIKING_RECALL_MAX_CONTENT_CHARS, OPENVIKING_RECALL_PREFER_ABSTRACT,@@ -155,11 +155,6 @@ export function loadConfig() {|| str(cc.apiKey, null)|| str(server.root_api_key, "");- // agentId: env → ovcli.agent_id → cc.agentId → "claude-code"- const agentId = str(process.env.OPENVIKING_AGENT_ID, null)- || str(cliFile.agent_id, null)- || str(cc.agentId, "claude-code");-// accountId: env → ovcli.account → cc.accountId → ""const accountId = str(process.env.OPENVIKING_ACCOUNT, null)|| str(cliFile.account, null)@@ -170,6 +165,10 @@ export function loadConfig() {|| str(cliFile.user, null)|| str(cc.userId, "");+ const peerId = str(process.env.OPENVIKING_PEER_ID, null)+ || str(cc.peerId, null)+ || str(cc.peer_id, "");+// Each tuning field follows env > ovcli.conf is N/A (CLI doesn't carry tuning) >// ov.conf cc.* > built-in default. Env var names are flat OPENVIKING_* (no CC// namespace) to match the existing connection-field convention; they are only@@ -204,9 +203,9 @@ export function loadConfig() {configPath,baseUrl,apiKey,- agentId,accountId,userId,+ peerId,timeoutMs,// Recalldiff --git a/examples/claude-code-memory-plugin/scripts/debug-capture.mjs b/examples/claude-code-memory-plugin/scripts/debug-capture.mjsindex 715bbe2b9..77893568a 100755--- a/examples/claude-code-memory-plugin/scripts/debug-capture.mjs+++ b/examples/claude-code-memory-plugin/scripts/debug-capture.mjs@@ -197,7 +197,6 @@ async function fetchJSON(path, init = {}) {if (cfg.apiKey) headers["Authorization"] = `Bearer ${cfg.apiKey}`;if (cfg.accountId) headers["X-OpenViking-Account"] = cfg.accountId;if (cfg.userId) headers["X-OpenViking-User"] = cfg.userId;- if (cfg.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}`);@@ -239,9 +238,11 @@ async function captureToOpenViking(text) {try {// Step 2: Add messageconsole.log("\nStep 2: Adding message...");+ const body = { role: "user", content: text };+ if (cfg.peerId) body.peer_id = cfg.peerId;const addResult = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`, {method: "POST",- body: JSON.stringify({ role: "user", content: text }),+ body: JSON.stringify(body),});if (addResult) {ok("Message added to session");@@ -334,7 +335,6 @@ async function main() {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;diff --git a/examples/claude-code-memory-plugin/scripts/debug-recall.mjs b/examples/claude-code-memory-plugin/scripts/debug-recall.mjsindex ff7ab5f65..e6479c1d5 100755--- a/examples/claude-code-memory-plugin/scripts/debug-recall.mjs+++ b/examples/claude-code-memory-plugin/scripts/debug-recall.mjs@@ -71,7 +71,6 @@ async function fetchJSON(path, init = {}) {if (cfg.apiKey) headers["Authorization"] = `Bearer ${cfg.apiKey}`;if (cfg.accountId) headers["X-OpenViking-Account"] = cfg.accountId;if (cfg.userId) headers["X-OpenViking-User"] = cfg.userId;- if (cfg.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") {@@ -248,25 +247,23 @@ async function resolveTargetUri(targetUri) {async function searchScope(queryText, targetUri, limit) {const resolvedUri = await resolveTargetUri(targetUri);dim(` target: ${targetUri} -> ${resolvedUri}`);+ const body = { query: queryText, target_uri: resolvedUri, limit, score_threshold: 0 };+ if (cfg.peerId) body.peer_id = cfg.peerId;const result = await fetchJSON("/api/v1/search/find", {method: "POST",- body: JSON.stringify({ query: queryText, target_uri: resolvedUri, limit, score_threshold: 0 }),+ body: JSON.stringify(body),});return result?.memories || [];}-async function searchBothScopes(queryText, limit) {+async function searchUserScope(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 => {+ combined: userMems.filter(m => {if (uriSet.has(m.uri)) return false;uriSet.add(m.uri);return true;@@ -313,7 +310,6 @@ async function main() {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}`);@@ -340,13 +336,11 @@ async function main() {const candidateLimit = Math.max(cfg.recallLimit * 4, 20);dim(` candidateLimit: ${candidateLimit}`);- const { userMems, agentMems, combined } = await searchBothScopes(query, candidateLimit);+ const { userMems, combined } = await searchUserScope(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) {diff --git a/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs b/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjsindex cf828df84..24fcfa195 100644--- a/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs+++ b/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs@@ -8,7 +8,7 @@** Format:* parent: cc-<ccSessionId>- * subagent: cc-<ccSessionId>__agent-<agentId>+ * subagent: cc-<ccSessionId>__subagent-<subagentId>** The CC session_id is preserved verbatim so the OV id is human-readable and* the parent/subagent lineage is visible at a glance.@@ -63,8 +63,8 @@ export function isBypassed(cfg, { sessionId, cwd } = {}) {/*** Derive a stable OV session ID from a CC session_id.*- * Optionally append a suffix (e.g. subagent agent_id) for isolation. The suffix- * is normalized: `:` → `-` (so `agent:abc123` → `agent-abc123`) and any+ * Optionally append a suffix (e.g. subagent_id) for session isolation. The suffix+ * is normalized: `:` → `-` (so `subagent:abc123` → `subagent-abc123`) and any* characters outside [A-Za-z0-9._-] become `-`. Result: `cc-<uuid>__<suffix>`.*/export function deriveOvSessionId(ccSessionId, suffix = "") {@@ -91,7 +91,6 @@ export function makeFetchJSON(cfg, timeoutKey = "timeoutMs") {if (cfg.apiKey) headers["Authorization"] = `Bearer ${cfg.apiKey}`;if (cfg.accountId) headers["X-OpenViking-Account"] = cfg.accountId;if (cfg.userId) headers["X-OpenViking-User"] = cfg.userId;- if (cfg.agentId) headers["X-OpenViking-Agent"] = cfg.agentId;const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });const body = await res.json().catch(() => ({}));if (!res.ok || body.status === "error") {diff --git a/examples/claude-code-memory-plugin/scripts/lib/server-probe.mjs b/examples/claude-code-memory-plugin/scripts/lib/server-probe.mjsindex f6d0e8fc5..3f559e54a 100644--- a/examples/claude-code-memory-plugin/scripts/lib/server-probe.mjs+++ b/examples/claude-code-memory-plugin/scripts/lib/server-probe.mjs@@ -66,7 +66,6 @@ export async function probeServer(cfg, { ttlMs = DEFAULT_TTL_MS } = {}) {if (cfg.apiKey) headers["Authorization"] = `Bearer ${cfg.apiKey}`;if (cfg.accountId) headers["X-OpenViking-Account"] = cfg.accountId;if (cfg.userId) headers["X-OpenViking-User"] = cfg.userId;- if (cfg.agentId) headers["X-OpenViking-Agent"] = cfg.agentId;const t0 = Date.now();let healthy = false;diff --git a/examples/claude-code-memory-plugin/scripts/ov-status.mjs b/examples/claude-code-memory-plugin/scripts/ov-status.mjsindex bf162a1d8..121697daa 100644--- a/examples/claude-code-memory-plugin/scripts/ov-status.mjs+++ b/examples/claude-code-memory-plugin/scripts/ov-status.mjs@@ -4,7 +4,7 @@* Status report for the OpenViking memory plugin — invoked by the `/ov`* slash command. Prints a tight human-readable summary covering:* - Server URL + /health probe- * - Resolved identity (account/user/agent)+ * - Resolved identity (account/user)* - Last session-start injection (size, age, audit path)* - Last auto-recall (item count, top score, token budget use)* - Toggle state for the three injection paths@@ -73,7 +73,7 @@ async function main() {console.log(`OpenViking — ${cfg.baseUrl} (${health.ok ? "✓" : "✗"} /health ${latency}ms)`);console.log(`Identity: account=${cfg.accountId || "(unset)"} ` +- `user=${cfg.userId || "(server-resolved)"} agent=${cfg.agentId}`,+ `user=${cfg.userId || "(server-resolved)"}`,);console.log("");diff --git a/examples/claude-code-memory-plugin/scripts/subagent-start.mjs b/examples/claude-code-memory-plugin/scripts/subagent-start.mjsindex 93e8d3b8a..25db99afe 100644--- a/examples/claude-code-memory-plugin/scripts/subagent-start.mjs+++ b/examples/claude-code-memory-plugin/scripts/subagent-start.mjs@@ -38,8 +38,8 @@ function approve() {process.stdout.write(JSON.stringify({ decision: "approve" }) + "\n");}-function stateFile(agentId) {- const safe = String(agentId).replace(/[^a-zA-Z0-9_-]/g, "_");+function stateFile(subagentId) {+ const safe = String(subagentId).replace(/[^a-zA-Z0-9_-]/g, "_");return join(STATE_DIR, `${safe}.json`);}@@ -60,11 +60,11 @@ async function main() {} catch { /* best effort */ }const sessionId = input.session_id;- const agentId = input.agent_id;+ const subagentId = input.agent_id;const agentType = input.agent_type || "subagent";const cwd = input.cwd;- if (!sessionId || !agentId) {+ if (!sessionId || !subagentId) {log("skip", { reason: "missing session_id or agent_id" });approve();return;@@ -76,21 +76,19 @@ async function main() {return;}- // Isolated ovSessionId: append agent_id so the subagent has its own OV- // session distinct from the parent (cc-<ccid>__agent-<agentid>).- const ovSessionId = deriveOvSessionId(sessionId, `agent:${agentId}`);- const ovAgentId = `${cfg.agentId || "claude-code"}_${agentType}`;+ // Isolated ovSessionId: append Claude's subagent id so the subagent has its+ // own OV session distinct from the parent.+ const ovSessionId = deriveOvSessionId(sessionId, `subagent:${subagentId}`);try {await mkdir(STATE_DIR, { recursive: true });await writeFile(- stateFile(agentId),+ stateFile(subagentId),JSON.stringify({parentSessionId: sessionId,- agentId,+ subagentId,agentType,ovSessionId,- ovAgentId,startedAt: Date.now(),}),);@@ -98,7 +96,7 @@ async function main() {logError("state_write", err);}- log("start", { agentId, agentType, ovSessionId, ovAgentId });+ log("start", { subagentId, agentType, ovSessionId });approve();}diff --git a/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs b/examples/claude-code-memory-plugin/scripts/subagent-stop.mjsindex 0e6ed0897..edbd645b7 100644--- a/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs+++ b/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs@@ -12,9 +12,8 @@* ovSessionId we created in subagent-start.mjs. An immediate commit runs* so the subagent's context is archived before the parent continues.*- * OV agent identity is overridden per-call via X-OpenViking-Agent header- * (e.g. "claude-code_general-purpose") so memories segregate by subagent- * type in viking://agent/<type>/memories/.+ * Each subagent is written to a distinct OpenViking session derived from the+ * parent session id and Claude's subagent id.*/import { readFile, unlink } from "node:fs/promises";@@ -45,14 +44,19 @@ function approve() {process.stdout.write(JSON.stringify({ decision: "approve" }) + "\n");}-function stateFile(agentId) {- const safe = String(agentId).replace(/[^a-zA-Z0-9_-]/g, "_");+function stateFile(subagentId) {+ const safe = String(subagentId).replace(/[^a-zA-Z0-9_-]/g, "_");return join(STATE_DIR, `${safe}.json`);}-async function loadState(agentId) {+function peerIdFromSubagent(subagentId) {+ if (cfg.peerId) return cfg.peerId;+ return String(subagentId || "").replace(/[^A-Za-z0-9._-]/g, "-") || null;+}++async function loadState(subagentId) {try {- const data = await readFile(stateFile(agentId), "utf-8");+ const data = await readFile(stateFile(subagentId), "utf-8");return JSON.parse(data);} catch {return null;@@ -223,11 +227,8 @@ function extractTurns(messages) {return turns;}-async function pushTurns(ovSessionId, ovAgentId, turns) {- // Per-call agent override: we mint a new fetchJSON whose cfg has agentId- // replaced so X-OpenViking-Agent reflects the subagent type.- const subCfg = { ...cfg, agentId: ovAgentId };- const fetchJSON = makeFetchJSON(subCfg);+async function pushTurns(ovSessionId, turns, peerId = null) {+ const fetchJSON = makeFetchJSON(cfg);let ok = 0;let failed = 0;for (const turn of turns) {@@ -237,13 +238,14 @@ async function pushTurns(ovSessionId, ovAgentId, turns) {(p) => p.type !== "text" || (p.text && p.text.trim()),);if (parts.length === 0) continue;- const res = await addMessage(fetchJSON, ovSessionId, { role: turn.role, parts });+ const payload = { role: turn.role, parts };+ if (peerId) payload.peer_id = peerId;+ const res = await addMessage(fetchJSON, ovSessionId, payload);if (res.ok) ok++;else failed++;}- // Commit once at the end — subagents are short-lived, no point tracking- // the threshold. This also makes their context available to the parent- // via viking://agent/<type> immediately.+ // Commit once at the end; subagents are short-lived, so threshold tracking+ // adds little value.let committed = false;if (ok > 0) {const commitRes = await commitSession(fetchJSON, ovSessionId);@@ -270,11 +272,10 @@ async function main() {const sessionId = input.session_id;const cwd = input.cwd;- const agentId = input.agent_id;+ const subagentId = input.agent_id;const transcriptPath = input.agent_transcript_path;- const agentType = input.agent_type || "subagent";- if (!sessionId || !agentId || !transcriptPath) {+ if (!sessionId || !subagentId || !transcriptPath) {log("skip", { reason: "missing required input fields" });approve();return;@@ -288,11 +289,10 @@ async function main() {// Prefer state from SubagentStart (may carry ovSessionId from config snapshot);// fall back to live derivation if state file is missing.- const state = await loadState(agentId);- const ovSessionId = state?.ovSessionId || deriveOvSessionId(sessionId, `agent:${agentId}`);- const ovAgentId = state?.ovAgentId || `${cfg.agentId || "claude-code"}_${agentType}`;+ const state = await loadState(subagentId);+ const ovSessionId = state?.ovSessionId || deriveOvSessionId(sessionId, `subagent:${subagentId}`);- const fetchJSON = makeFetchJSON({ ...cfg, agentId: ovAgentId });+ const fetchJSON = makeFetchJSON(cfg);const health = await fetchJSON("/health");if (!health.ok) {logError("health_check", "server unreachable");@@ -312,22 +312,22 @@ async function main() {const messages = parseTranscript(transcript);const turns = extractTurns(messages);log("transcript_parse", {- agentId,+ subagentId,ovSessionId,- ovAgentId,totalTurns: turns.length,});if (turns.length === 0) {- await unlink(stateFile(agentId)).catch(() => {});+ await unlink(stateFile(subagentId)).catch(() => {});approve();return;}- const result = await pushTurns(ovSessionId, ovAgentId, turns);- log("push_turns", { ovSessionId, ovAgentId, ...result });+ const peerId = peerIdFromSubagent(subagentId);+ const result = await pushTurns(ovSessionId, turns, peerId);+ log("push_turns", { ovSessionId, ...result });- await unlink(stateFile(agentId)).catch(() => {});+ await unlink(stateFile(subagentId)).catch(() => {});approve();}diff --git a/examples/claude-code-memory-plugin/setup-helper/install.sh b/examples/claude-code-memory-plugin/setup-helper/install.shindex e3a8d33a0..5d495712b 100755--- a/examples/claude-code-memory-plugin/setup-helper/install.sh+++ b/examples/claude-code-memory-plugin/setup-helper/install.sh@@ -253,8 +253,7 @@ install_legacy() {'${OPENVIKING_URL:-http://127.0.0.1:1933}/mcp' \--header 'Authorization: Bearer ${OPENVIKING_API_KEY:-}' \--header 'X-OpenViking-Account: ${OPENVIKING_ACCOUNT:-}' \- --header 'X-OpenViking-User: ${OPENVIKING_USER:-}' \- --header 'X-OpenViking-Agent: ${OPENVIKING_AGENT_ID:-}' || {+ --header 'X-OpenViking-User: ${OPENVIKING_USER:-}' || {err 'claude mcp add failed'return 1}diff --git a/examples/cloud/alice.py b/examples/cloud/alice.pyindex 74bc97f65..5069be79e 100644--- a/examples/cloud/alice.py+++ b/examples/cloud/alice.py@@ -59,7 +59,7 @@ def main():print("User: alice")print("Key: [hidden]")- client = ov.SyncHTTPClient(url=url, api_key=api_key, agent_id="alice-agent")+ client = ov.SyncHTTPClient(url=url, api_key=api_key)client.initialize()try:diff --git a/examples/cloud/bob.py b/examples/cloud/bob.pyindex 3f65a24d5..aa82709bf 100644--- a/examples/cloud/bob.py+++ b/examples/cloud/bob.py@@ -58,7 +58,7 @@ def main():print("User: bob")print("Key: [hidden]")- client = ov.SyncHTTPClient(url=url, api_key=api_key, agent_id="bob-agent")+ client = ov.SyncHTTPClient(url=url, api_key=api_key)client.initialize()try:diff --git a/examples/codex-memory-plugin/.mcp.json b/examples/codex-memory-plugin/.mcp.jsonindex 40bf6d264..f5a0e1719 100644--- a/examples/codex-memory-plugin/.mcp.json+++ b/examples/codex-memory-plugin/.mcp.json@@ -5,8 +5,7 @@"bearer_token_env_var": "OPENVIKING_API_KEY","env_http_headers": {"X-OpenViking-Account": "OPENVIKING_ACCOUNT",- "X-OpenViking-User": "OPENVIKING_USER",- "X-OpenViking-Agent": "OPENVIKING_AGENT_ID"+ "X-OpenViking-User": "OPENVIKING_USER"}}}diff --git a/examples/codex-memory-plugin/README.md b/examples/codex-memory-plugin/README.mdindex 4054c5eff..cae0bdcf5 100644--- a/examples/codex-memory-plugin/README.md+++ b/examples/codex-memory-plugin/README.md@@ -73,7 +73,6 @@ If you don't want the installer touching your rc, do these three things yourself[ -n "$_ov_key" ] && _env_args+=("OPENVIKING_API_KEY=$_ov_key")[ -n "$_ov_account" ] && _env_args+=("OPENVIKING_ACCOUNT=$_ov_account")[ -n "$_ov_user" ] && _env_args+=("OPENVIKING_USER=$_ov_user")- _env_args+=("OPENVIKING_AGENT_ID=${OPENVIKING_AGENT_ID:-codex}")env "${_env_args[@]}" codex "$@"}```@@ -86,7 +85,7 @@ If you don't want the installer touching your rc, do these three things yourselfConnection / identity resolution order (highest to lowest, applies to both hooks and MCP):-1. **Environment variables**: `OPENVIKING_URL` / `OPENVIKING_BASE_URL`, `OPENVIKING_API_KEY` / `OPENVIKING_BEARER_TOKEN`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, `OPENVIKING_AGENT_ID`+1. **Environment variables**: `OPENVIKING_URL` / `OPENVIKING_BASE_URL`, `OPENVIKING_API_KEY` / `OPENVIKING_BEARER_TOKEN`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, `OPENVIKING_PEER_ID`2. **`ovcli.conf`**: `~/.openviking/ovcli.conf` or `OPENVIKING_CLI_CONFIG_FILE`3. **`ov.conf`**: `~/.openviking/ov.conf` or `OPENVIKING_CONFIG_FILE` (only `server.url` / `server.root_api_key` as connection fallback; tuning fields under a legacy `codex.*` block are honored but deprecated — see [Tuning the plugin](#tuning-the-plugin))4. **Built-in defaults**: `http://127.0.0.1:1933`, unauthenticated@@ -95,6 +94,8 @@ The shell function wrapper handles step 1 for you by promoting ovcli.conf fieldsAuth is sent as `Authorization: Bearer <api_key>` to both the REST API (used by hooks) and the `/mcp` endpoint (used by the model).+Set `OPENVIKING_PEER_ID` when multiple Codex peers share the same OpenViking user and should keep separate peer memory. Hooks pass it as request-level `peer_id` for auto-recall and captured session messages. The legacy `codex.peerId` / `codex.peer_id` fields in `ov.conf` are also honored, but env vars are preferred.+For **unauthenticated local OV** (`ovcli.conf` without `api_key`, or no ovcli.conf at all), `.mcp.json` is rendered *without* `bearer_token_env_var`. Codex 0.130 hard-fails MCP startup with `Environment variable ... is empty` if `bearer_token_env_var` points at an empty/unset env var, so it must be omitted entirely when there's no key.The `codex()` shell-function wrapper **re-renders this field on every codex launch** based on the currently-active `ovcli.conf` (the one `OPENVIKING_CLI_CONFIG_FILE` points at, falling back to `~/.openviking/ovcli.conf`). That means you can switch between authenticated and unauthenticated OV — e.g. to isolate a benchmark run from production memory — by just changing `OPENVIKING_CLI_CONFIG_FILE` before invoking `codex`, with no re-install needed. The wrapper also omits empty env-var assignments entirely (so `OPENVIKING_API_KEY=` is never passed to codex), keeping `env_http_headers` for identity (`X-OpenViking-Account` / `User` / `Agent`) intact.diff --git a/examples/codex-memory-plugin/scripts/auto-capture.mjs b/examples/codex-memory-plugin/scripts/auto-capture.mjsindex 180af46b6..c4988f520 100644--- a/examples/codex-memory-plugin/scripts/auto-capture.mjs+++ b/examples/codex-memory-plugin/scripts/auto-capture.mjs@@ -52,7 +52,6 @@ async function fetchJSON(path, init = {}) {}if (cfg.account) headers["X-OpenViking-Account"] = cfg.account;if (cfg.user) headers["X-OpenViking-User"] = cfg.user;- 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().catch(() => null);if (!body) return null;@@ -141,9 +140,11 @@ async function readTranscriptTurns(transcriptPath) {async function appendTurns(ovSessionId, turns) {let appended = 0;for (const turn of turns) {+ const body = { role: turn.role, content: turn.text };+ if (cfg.peerId) body.peer_id = cfg.peerId;const result = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(ovSessionId)}/messages`, {method: "POST",- body: JSON.stringify({ role: turn.role, content: turn.text }),+ body: JSON.stringify(body),});if (!result) break;appended += 1;diff --git a/examples/codex-memory-plugin/scripts/auto-recall.mjs b/examples/codex-memory-plugin/scripts/auto-recall.mjsindex b14e36dd9..2bbd6ce05 100644--- a/examples/codex-memory-plugin/scripts/auto-recall.mjs+++ b/examples/codex-memory-plugin/scripts/auto-recall.mjs@@ -47,7 +47,6 @@ async function fetchJSON(path, init = {}) {}if (cfg.account) headers["X-OpenViking-Account"] = cfg.account;if (cfg.user) headers["X-OpenViking-User"] = cfg.user;- 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().catch(() => null);if (!body) return null;@@ -167,15 +166,14 @@ function postProcess(items, limit, threshold) {}// ----------------------------------------------------------------------------// URI space resolution (mirrors MCP normalizeTargetUri)+// User URI space resolution// ----------------------------------------------------------------------------const USER_RESERVED_DIRS = new Set(["memories"]);-const AGENT_RESERVED_DIRS = new Set(["memories", "skills", "instructions", "workspaces"]);-const _spaceCache = {};+const USER_RESERVED_DIRS = new Set(["memories", "skills"]);+let _userSpaceCache = "";-async function resolveScopeSpace(scope) {- if (_spaceCache[scope]) return _spaceCache[scope];+async function resolveUserSpace() {+ if (_userSpaceCache) return _userSpaceCache;let fallbackSpace = "default";try {@@ -185,60 +183,57 @@ async function resolveScopeSpace(scope) {}} catch { /* 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`);+ const entries = await fetchJSON(`/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&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));+ .filter((n) => n && !n.startsWith(".") && !USER_RESERVED_DIRS.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]; }+ if (spaces.includes(fallbackSpace)) { _userSpaceCache = fallbackSpace; return fallbackSpace; }+ if (spaces.includes("default")) { _userSpaceCache = "default"; return "default"; }+ if (spaces.length === 1) { _userSpaceCache = spaces[0]; return spaces[0]; }}}} catch { /* fallback */ }- _spaceCache[scope] = fallbackSpace;+ _userSpaceCache = fallbackSpace;return fallbackSpace;}async function resolveTargetUri(targetUri) {const trimmed = targetUri.trim().replace(/\/+$/, "");- const m = trimmed.match(/^viking:\/\/(user|agent)(?:\/(.*))?$/);+ const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);if (!m) return trimmed;- const scope = m[1];- const rawRest = (m[2] ?? "").trim();+ const rawRest = (m[1] ?? "").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("/")}`;+ if (!USER_RESERVED_DIRS.has(parts[0])) return trimmed;+ const space = await resolveUserSpace();+ return `viking://user/${space}/${parts.join("/")}`;}async function searchScope(query, targetUri, limit, bucket = "memories") {const resolvedUri = await resolveTargetUri(targetUri);+ const body = { query, target_uri: resolvedUri, limit, score_threshold: 0 };+ if (cfg.peerId) body.peer_id = cfg.peerId;const result = await fetchJSON("/api/v1/search/find", {method: "POST",- body: JSON.stringify({ query, target_uri: resolvedUri, limit, score_threshold: 0 }),+ body: JSON.stringify(body),});return result?.[bucket] || [];}async function searchAll(query, limit) {- const [userMems, agentMems, agentSkills] = await Promise.all([+ const [userMems, userSkills] = await Promise.all([searchScope(query, "viking://user/memories", limit),- searchScope(query, "viking://agent/memories", limit),- searchScope(query, "viking://agent/skills", limit, "skills"),+ searchScope(query, "viking://user/skills", limit, "skills"),]);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) });- log("search_complete", { scope: "skills", rawCount: agentSkills.length, topScores: agentSkills.slice(0, 3).map((m) => m.score) });- const all = [...userMems, ...agentMems, ...agentSkills];+ log("search_complete", { scope: "skills", rawCount: userSkills.length, topScores: userSkills.slice(0, 3).map((m) => m.score) });+ const all = [...userMems, ...userSkills];const seen = new Set();return all.filter((m) => {if (seen.has(m.uri)) return false;diff --git a/examples/codex-memory-plugin/scripts/config.mjs b/examples/codex-memory-plugin/scripts/config.mjsindex c86607166..85dfd36da 100644--- a/examples/codex-memory-plugin/scripts/config.mjs+++ b/examples/codex-memory-plugin/scripts/config.mjs@@ -3,7 +3,7 @@** Resolution priority (highest → lowest), per-field:* 1. Environment variables (OPENVIKING_*)- * 2. ovcli.conf — the CLI client config (carries url/api_key/account/user/agent_id)+ * 2. ovcli.conf — the CLI client config (carries url/api_key/account/user)* 3. ov.conf — the server config (server.* + optional codex.* block for tuning)* 4. Built-in defaults*@@ -24,7 +24,7 @@* Connection / identity env vars:* OPENVIKING_URL / OPENVIKING_BASE_URL* OPENVIKING_API_KEY / OPENVIKING_BEARER_TOKEN- * OPENVIKING_ACCOUNT, OPENVIKING_USER, OPENVIKING_AGENT_ID+ * OPENVIKING_ACCOUNT, OPENVIKING_USER, OPENVIKING_PEER_ID** Misc env vars:* OPENVIKING_TIMEOUT_MS, OPENVIKING_CAPTURE_TIMEOUT_MS@@ -173,11 +173,10 @@ export function loadConfig() {str(cliFile.user, null) ||str(cx.userId, "");- // agentId: env > cliFile.agent_id > codex.agentId > "codex"- const agentId =- str(process.env.OPENVIKING_AGENT_ID, null) ||- str(cliFile.agent_id, null) ||- str(cx.agentId, "codex");+ const peerId =+ str(process.env.OPENVIKING_PEER_ID, null) ||+ str(cx.peerId, null) ||+ str(cx.peer_id, "");const debug = envBool("OPENVIKING_DEBUG") ?? (cx.debug === true);const defaultLogPath = join(homedir(), ".openviking", "logs", "codex-hooks.log");@@ -200,7 +199,7 @@ export function loadConfig() {apiKey,account,user,- agentId,+ peerId,timeoutMs,autoRecall: envBool("OPENVIKING_AUTO_RECALL") ?? (cx.autoRecall !== false),diff --git a/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs b/examples/codex-memory-plugin/scripts/pre-compact-capture.mjsindex 280a68db7..9c813dcd5 100644--- a/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs+++ b/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs@@ -47,7 +47,6 @@ async function fetchJSON(path, init = {}) {}if (cfg.account) headers["X-OpenViking-Account"] = cfg.account;if (cfg.user) headers["X-OpenViking-User"] = cfg.user;- 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().catch(() => null);if (!body) return null;@@ -132,9 +131,11 @@ async function readTranscriptTurns(transcriptPath) {async function appendTurns(ovSessionId, turns) {let appended = 0;for (const turn of turns) {+ const body = { role: turn.role, content: turn.text };+ if (cfg.peerId) body.peer_id = cfg.peerId;const result = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(ovSessionId)}/messages`, {method: "POST",- body: JSON.stringify({ role: turn.role, content: turn.text }),+ body: JSON.stringify(body),});if (!result) break;appended += 1;diff --git a/examples/codex-memory-plugin/scripts/session-start-commit.mjs b/examples/codex-memory-plugin/scripts/session-start-commit.mjsindex ac2ed50a5..e67de64e2 100644--- a/examples/codex-memory-plugin/scripts/session-start-commit.mjs+++ b/examples/codex-memory-plugin/scripts/session-start-commit.mjs@@ -66,7 +66,6 @@ async function fetchJSON(path, init = {}) {}if (cfg.account) headers["X-OpenViking-Account"] = cfg.account;if (cfg.user) headers["X-OpenViking-User"] = cfg.user;- 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().catch(() => null);if (!body) return null;diff --git a/examples/codex-memory-plugin/setup-helper/wrapper.sh b/examples/codex-memory-plugin/setup-helper/wrapper.shindex 30255965c..5e96d67cd 100644--- a/examples/codex-memory-plugin/setup-helper/wrapper.sh+++ b/examples/codex-memory-plugin/setup-helper/wrapper.sh@@ -111,7 +111,6 @@ codex() {[ -n "$_ov_key" ] && _env_args+=("OPENVIKING_API_KEY=$_ov_key")[ -n "$_ov_account" ] && _env_args+=("OPENVIKING_ACCOUNT=$_ov_account")[ -n "$_ov_user" ] && _env_args+=("OPENVIKING_USER=$_ov_user")- _env_args+=("OPENVIKING_AGENT_ID=${OPENVIKING_AGENT_ID:-codex}")env "${_env_args[@]}" codex "$@"}diff --git a/examples/langchain-langgraph/langgraph/agent/live_app.py b/examples/langchain-langgraph/langgraph/agent/live_app.pyindex d95ffba60..e6728d482 100644--- a/examples/langchain-langgraph/langgraph/agent/live_app.py+++ b/examples/langchain-langgraph/langgraph/agent/live_app.py@@ -36,7 +36,6 @@ def build_context_client():url=os.environ.get("OPENVIKING_URL") or None,api_key=os.environ.get("OPENVIKING_API_KEY"),user_id=os.environ.get("OPENVIKING_USER_ID"),- agent_id=os.environ.get("OPENVIKING_AGENT_ID"),)client.initialize()return clientdiff --git a/examples/multi_tenant/admin_workflow.py b/examples/multi_tenant/admin_workflow.pyindex 1737f7440..66d9e16e7 100644--- a/examples/multi_tenant/admin_workflow.py+++ b/examples/multi_tenant/admin_workflow.py@@ -136,7 +136,7 @@ def admin_api(base_url: str, root_key: str):# ── 9. Use user key to access data ──print("== 9. Access Data with User Key ==")- bob_client = ov.SyncHTTPClient(url=base_url, api_key=bob_key, agent_id="demo-agent")+ bob_client = ov.SyncHTTPClient(url=base_url, api_key=bob_key)bob_client.initialize()try:entries = bob_client.ls("viking://")diff --git a/examples/multi_tenant/shared_session_role_id_http.py b/examples/multi_tenant/shared_session_peer_id_http.pysimilarity index 50%rename from examples/multi_tenant/shared_session_role_id_http.pyrename to examples/multi_tenant/shared_session_peer_id_http.pyindex c262197df..123497aa1 100644--- a/examples/multi_tenant/shared_session_role_id_http.py+++ b/examples/multi_tenant/shared_session_peer_id_http.py@@ -1,90 +1,38 @@#!/usr/bin/env python3"""-HTTP demo for shared-session + role_id semantics.+HTTP demo for shared-session + peer_id semantics.-This script creates 4 accounts for the namespace-policy matrix, creates one-regular USER in each account, then runs two scenarios per account:+This script creates one account, creates one regular USER, then runs two scenarios:1. `multi-user`- Uses an ADMIN key to switch effective user/agent context within one account,- and demonstrates that ADMIN may explicitly pass role_id.+ Uses an ADMIN key to switch effective user context within one account, and+ demonstrates that ADMIN may explicitly pass peer_id.2. `normal-user`- Uses a USER key to show that role_id is derived from request context and- explicit role_id is rejected.+ Uses a USER key to show that explicit peer_id is accepted and missing+ peer_id is not autofilled from request context.-Create account examples for the 4 namespace-policy combinations:+Create account:export URL=http://127.0.0.1:1933export ROOT_KEY=<root-key>- # ff: isolate_user_scope_by_agent=false, isolate_agent_scope_by_user=falsecurl -sS -X POST "$URL/api/v1/admin/accounts" \-H "X-API-Key: $ROOT_KEY" \-H "Content-Type: application/json" \-d '{- "account_id": "demo-ff",- "admin_user_id": "alice",- "isolate_user_scope_by_agent": false,- "isolate_agent_scope_by_user": false+ "account_id": "demo-peer",+ "admin_user_id": "alice"}'- # ft: isolate_user_scope_by_agent=false, isolate_agent_scope_by_user=true- curl -sS -X POST "$URL/api/v1/admin/accounts" \- -H "X-API-Key: $ROOT_KEY" \- -H "Content-Type: application/json" \- -d '{- "account_id": "demo-ft",- "admin_user_id": "alice",- "isolate_user_scope_by_agent": false,- "isolate_agent_scope_by_user": true- }'-- # tf: isolate_user_scope_by_agent=true, isolate_agent_scope_by_user=false- curl -sS -X POST "$URL/api/v1/admin/accounts" \- -H "X-API-Key: $ROOT_KEY" \- -H "Content-Type: application/json" \- -d '{- "account_id": "demo-tf",- "admin_user_id": "alice",- "isolate_user_scope_by_agent": true,- "isolate_agent_scope_by_user": false- }'-- # tt: isolate_user_scope_by_agent=true, isolate_agent_scope_by_user=true- curl -sS -X POST "$URL/api/v1/admin/accounts" \- -H "X-API-Key: $ROOT_KEY" \- -H "Content-Type: application/json" \- -d '{- "account_id": "demo-tt",- "admin_user_id": "alice",- "isolate_user_scope_by_agent": true,- "isolate_agent_scope_by_user": true- }'--Create a regular USER for each account (the returned `result.user_key` is the key-to use with the `normal-user` scenario):- curl -sS -X POST "$URL/api/v1/admin/accounts/demo-ff/users" \- -H "X-API-Key: $ROOT_KEY" \- -H "Content-Type: application/json" \- -d '{"user_id": "bob", "role": "user"}'-- curl -sS -X POST "$URL/api/v1/admin/accounts/demo-ft/users" \- -H "X-API-Key: $ROOT_KEY" \- -H "Content-Type: application/json" \- -d '{"user_id": "bob", "role": "user"}'-- curl -sS -X POST "$URL/api/v1/admin/accounts/demo-tf/users" \- -H "X-API-Key: $ROOT_KEY" \- -H "Content-Type: application/json" \- -d '{"user_id": "bob", "role": "user"}'-- curl -sS -X POST "$URL/api/v1/admin/accounts/demo-tt/users" \+Create a regular USER (the returned `result.user_key` is the key to use with+the `normal-user` scenario):+ curl -sS -X POST "$URL/api/v1/admin/accounts/demo-peer/users" \-H "X-API-Key: $ROOT_KEY" \-H "Content-Type: application/json" \-d '{"user_id": "bob", "role": "user"}'Examples:- python examples/multi_tenant/shared_session_role_id_http.py \+ python examples/multi_tenant/shared_session_peer_id_http.py \--url http://127.0.0.1:1933 \--root-key <root-key>"""@@ -102,12 +50,6 @@ import httpxOK = "[OK]"FAIL = "[FAIL]"UNSET = object()-NAMESPACE_COMBINATIONS = [- ("ff", False, False),- ("ft", False, True),- ("tf", True, False),- ("tt", True, True),-]def build_headers(@@ -115,7 +57,6 @@ def build_headers(api_key: str,account: Optional[str] = None,user: Optional[str] = None,- agent: Optional[str] = None,) -> Dict[str, str]:headers = {"X-API-Key": api_key,@@ -125,8 +66,6 @@ def build_headers(headers["X-OpenViking-Account"] = accountif user:headers["X-OpenViking-User"] = user- if agent:- headers["X-OpenViking-Agent"] = agentreturn headers@@ -175,8 +114,6 @@ def create_account(root_key: str,account_id: str,admin_user_id: str,- isolate_user_scope_by_agent: bool,- isolate_agent_scope_by_user: bool,) -> Dict[str, Any]:response = client.post(f"{base_url}/api/v1/admin/accounts",@@ -184,8 +121,6 @@ def create_account(json={"account_id": account_id,"admin_user_id": admin_user_id,- "isolate_user_scope_by_agent": isolate_user_scope_by_agent,- "isolate_agent_scope_by_user": isolate_agent_scope_by_user,},)expect_status(response, 200, f"create account {account_id}")@@ -218,14 +153,14 @@ def add_message(*,role: str,content: str,- role_id: object = UNSET,+ peer_id: object = UNSET,) -> httpx.Response:payload: Dict[str, Any] = {"role": role,"content": content,}- if role_id is not UNSET:- payload["role_id"] = role_id+ if peer_id is not UNSET:+ payload["peer_id"] = peer_idreturn client.post(f"{base_url}/api/v1/sessions/{session_id}/messages",headers=headers,@@ -252,23 +187,19 @@ def run_multi_user_flow(account: str,admin_key: str,effective_user_a: str,- effective_agent_a: str,effective_user_b: str,- effective_agent_b: str,- assistant_role_id: Optional[str],+ assistant_peer_id: Optional[str],session_id: Optional[str],) -> Dict[str, Any]:admin_headers_a = build_headers(api_key=admin_key,account=account,user=effective_user_a,- agent=effective_agent_a,)admin_headers_b = build_headers(api_key=admin_key,account=account,user=effective_user_b,- agent=effective_agent_b,)session_id = create_session(@@ -288,7 +219,7 @@ def run_multi_user_flow(role="user",content=f"implicit actor from effective context: {effective_user_a}",)- expect_status(response, 200, "admin implicit user role_id fill")+ expect_status(response, 200, "admin user message without peer_id")response = add_message(client,@@ -296,22 +227,22 @@ def run_multi_user_flow(session_id,admin_headers_a,role="user",- content=f"explicit actor set by admin: {effective_user_b}",- role_id=effective_user_b,+ content=f"explicit peer set by admin: {effective_user_b}",+ peer_id=effective_user_b,)- expect_status(response, 200, "admin explicit user role_id")+ expect_status(response, 200, "admin explicit user peer_id")- resolved_assistant_role_id = assistant_role_id or effective_agent_b+ resolved_assistant_peer_id = assistant_peer_id or "assistant"response = add_message(client,base_url,session_id,admin_headers_a,role="assistant",- content=f"explicit assistant actor: {resolved_assistant_role_id}",- role_id=resolved_assistant_role_id,+ content=f"explicit assistant peer: {resolved_assistant_peer_id}",+ peer_id=resolved_assistant_peer_id,)- expect_status(response, 200, "admin explicit assistant role_id")+ expect_status(response, 200, "admin explicit assistant peer_id")context_from_other_user = get_context(client,@@ -332,18 +263,15 @@ def run_normal_user_flow(*,base_url: str,user_key: str,- agent: str,account: Optional[str],user: Optional[str],- explicit_role_id: Optional[str],- expected_error_status: int,+ explicit_peer_id: Optional[str],session_id: Optional[str],) -> Dict[str, Any]:user_headers = build_headers(api_key=user_key,account=account,user=user,- agent=agent,)session_id = create_session(@@ -363,7 +291,7 @@ def run_normal_user_flow(role="user",content="implicit actor from user key context",)- expect_status(response, 200, "user implicit role_id fill")+ expect_status(response, 200, "user message without peer_id")response = add_message(client,@@ -371,31 +299,21 @@ def run_normal_user_flow(session_id,user_headers,role="assistant",- content=f"implicit assistant actor from agent context: {agent}",+ content="assistant message without peer_id",)- expect_status(response, 200, "user implicit assistant role_id fill")+ expect_status(response, 200, "user assistant message without peer_id")- resolved_explicit_role_id = explicit_role_id or "explicit-user"+ resolved_explicit_peer_id = explicit_peer_id or "explicit-user"response = add_message(client,base_url,session_id,user_headers,role="user",- content=f"this should fail with explicit role_id: {resolved_explicit_role_id}",- role_id=resolved_explicit_role_id,+ content=f"explicit peer_id from user client: {resolved_explicit_peer_id}",+ peer_id=resolved_explicit_peer_id,)- if response.status_code == expected_error_status:- print_response(- f"{OK} user explicit role_id rejected as expected",- response,- )- else:- print_response(- f"{FAIL} user explicit role_id should have been rejected",- response,- )- raise SystemExit(1)+ expect_status(response, 200, "user explicit peer_id")context_response = get_context(client, base_url, session_id, user_headers)expect_status(context_response, 200, "load session context")@@ -420,77 +338,62 @@ def run_setup_and_run(args: argparse.Namespace) -> Dict[str, Any]:health = client.get(f"{base_url}/health")expect_status(health, 200, "health check")- for (- suffix,- isolate_user_scope_by_agent,- isolate_agent_scope_by_user,- ) in NAMESPACE_COMBINATIONS:- account_id = f"{name_prefix}-{suffix}"- print(f"== Account {account_id} ==")- account_result = create_account(- client,- base_url,- root_key=args.root_key,- account_id=account_id,- admin_user_id=args.admin_user,- isolate_user_scope_by_agent=isolate_user_scope_by_agent,- isolate_agent_scope_by_user=isolate_agent_scope_by_user,- )- user_result = register_user(- client,- base_url,- api_key=args.root_key,- account_id=account_id,- user_id=args.regular_user,- role="user",- )-- multi_session_id = f"{account_id}-multi-{run_id}"- normal_session_id = f"{account_id}-normal-{run_id}"-- print(f"-- multi-user scenario for {account_id} --")- multi_result = run_multi_user_flow(- client,- base_url=base_url,- account=account_id,- admin_key=account_result["user_key"],- effective_user_a=args.admin_user,- effective_agent_a=args.effective_agent_a,- effective_user_b=args.regular_user,- effective_agent_b=args.effective_agent_b,- assistant_role_id=args.assistant_role_id,- session_id=multi_session_id,- )-- print(f"-- normal-user scenario for {account_id} --")- normal_result = run_normal_user_flow(- client,- base_url=base_url,- user_key=user_result["user_key"],- agent=args.normal_user_agent,- account=None,- user=None,- explicit_role_id=args.explicit_role_id,- expected_error_status=args.expected_error_status,- session_id=normal_session_id,- )-- summary["accounts"].append(- {- "account_id": account_id,- "namespace_policy": {- "isolate_user_scope_by_agent": isolate_user_scope_by_agent,- "isolate_agent_scope_by_user": isolate_agent_scope_by_user,- },- "admin_user_id": args.admin_user,- "admin_key": account_result["user_key"],- "regular_user_id": args.regular_user,- "regular_user_key": user_result["user_key"],- "multi_user": multi_result,- "normal_user": normal_result,- }- )- print()+ account_id = name_prefix+ print(f"== Account {account_id} ==")+ account_result = create_account(+ client,+ base_url,+ root_key=args.root_key,+ account_id=account_id,+ admin_user_id=args.admin_user,+ )+ user_result = register_user(+ client,+ base_url,+ api_key=args.root_key,+ account_id=account_id,+ user_id=args.regular_user,+ role="user",+ )++ multi_session_id = f"{account_id}-multi-{run_id}"+ normal_session_id = f"{account_id}-normal-{run_id}"++ print(f"-- multi-user scenario for {account_id} --")+ multi_result = run_multi_user_flow(+ client,+ base_url=base_url,+ account=account_id,+ admin_key=account_result["user_key"],+ effective_user_a=args.admin_user,+ effective_user_b=args.regular_user,+ assistant_peer_id=args.assistant_peer_id,+ session_id=multi_session_id,+ )++ print(f"-- normal-user scenario for {account_id} --")+ normal_result = run_normal_user_flow(+ client,+ base_url=base_url,+ user_key=user_result["user_key"],+ account=None,+ user=None,+ explicit_peer_id=args.explicit_peer_id,+ session_id=normal_session_id,+ )++ summary["accounts"].append(+ {+ "account_id": account_id,+ "admin_user_id": args.admin_user,+ "admin_key": account_result["user_key"],+ "regular_user_id": args.regular_user,+ "regular_user_key": user_result["user_key"],+ "multi_user": multi_result,+ "normal_user": normal_result,+ }+ )+ print()print("== Summary ==")print(json.dumps(summary, indent=2, ensure_ascii=False))@@ -498,7 +401,7 @@ def run_setup_and_run(args: argparse.Namespace) -> Dict[str, Any]:def build_parser() -> argparse.ArgumentParser:- parser = argparse.ArgumentParser(description="Shared session + role_id HTTP demo")+ parser = argparse.ArgumentParser(description="Shared session + peer_id HTTP demo")parser.add_argument("--url",default="http://127.0.0.1:1933",@@ -524,43 +427,22 @@ def build_parser() -> argparse.ArgumentParser:parser.add_argument("--admin-user",default="alice",- help="Admin user created in every account",+ help="Admin user created in the account",)parser.add_argument("--regular-user",default="bob",- help="Regular USER created in every account",- )- parser.add_argument(- "--effective-agent-a",- default="agent-a",- help="Agent used for ADMIN effective context A",+ help="Regular USER created in the account",)parser.add_argument(- "--effective-agent-b",- default="agent-b",- help="Agent used for ADMIN effective context B",- )- parser.add_argument(- "--normal-user-agent",- default="agent-a",- help="Agent used for USER scenario",- )- parser.add_argument(- "--assistant-role-id",+ "--assistant-peer-id",default=None,- help="Optional explicit assistant role_id for the ADMIN scenario",+ help="Optional explicit assistant peer_id for the ADMIN scenario",)parser.add_argument(- "--explicit-role-id",+ "--explicit-peer-id",default=None,- help="Optional explicit role_id used for the USER negative test",- )- parser.add_argument(- "--expected-error-status",- type=int,- default=400,- help="Expected HTTP status when USER explicitly sends role_id",+ help="Optional explicit peer_id used for the USER scenario",)return parserdiff --git a/examples/openclaw-plugin/INSTALL-AGENT.md b/examples/openclaw-plugin/INSTALL-AGENT.mdindex 3e324bfbe..8ac397fcc 100644--- a/examples/openclaw-plugin/INSTALL-AGENT.md+++ b/examples/openclaw-plugin/INSTALL-AGENT.md@@ -96,10 +96,10 @@ openclaw openviking setup \--json```-Custom agent routing prefix (optional; only when the user explicitly requests a prefix):+Assistant peer prefix (optional; only when the user explicitly requests assistant `peer_id`):```bash-openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --agent-prefix <PREFIX> --json+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --peer-role assistant --peer-prefix <PREFIX> --json```Slot replacement retry, only after user approval:@@ -139,7 +139,8 @@ Also inspect:| `health.version` | Records server version || `health.compatibility` | Determines whether to warn || `config.hasApiKey` | Confirms whether an API key was saved |-| `config.agent_prefix` | Confirms configured agent prefix when present |+| `config.peer_role` | Confirms which messages write `peer_id` |+| `config.peer_prefix` | Confirms configured assistant peer prefix when present |## Environment Detection@@ -267,7 +268,8 @@ Core fields:| `mode` | Legacy compatibility field. Expected value: `remote`. || `baseUrl` | OpenViking HTTP endpoint || `apiKey` | OpenViking API key |-| `agent_prefix` | Optional; prefix for OpenClaw agent IDs when set. Interactive setup accepts only letters, digits, `_`, and `-`. If unset, the plugin follows session agent IDs. |+| `peer_role` | Controls session `peer_id` writes and recall/search `peer_id`: `none`, `assistant`, or `person`. New installs default to `none`. |+| `peer_prefix` | Optional prefix for assistant `peer_id` values when `peer_role=assistant`. || `accountId` | Required for root API keys || `userId` | Required for root API keys |@@ -329,7 +331,8 @@ Existing config fields are preserved during migration. The new plugin reads old- `baseUrl`- `apiKey`-- `agent_prefix`: optional; interactive setup accepts only letters, digits, `_`, and `-`+- `peer_role`: optional; default `none`; controls session writes and recall/search `peer_id`+- `peer_prefix`: optional when `peer_role=assistant`## Backup Path: ov-installdiff --git a/examples/openclaw-plugin/INSTALL-ZH.md b/examples/openclaw-plugin/INSTALL-ZH.mdindex c75c88ad2..066fe0e36 100644--- a/examples/openclaw-plugin/INSTALL-ZH.md+++ b/examples/openclaw-plugin/INSTALL-ZH.md@@ -141,10 +141,10 @@ openclaw openviking setup \openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --force-slot --json```-如需自定义 agent 路由前缀(可选;多数用户留空即可):+如需给 assistant message 写入带前缀的 `peer_id`(可选;多数用户保持默认 `none` 即可):```bash-openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --agent-prefix <PREFIX> --json+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --peer-role assistant --peer-prefix <PREFIX> --json```### 3. 重启 OpenClaw Gateway@@ -205,7 +205,8 @@ plugins.entries.openviking.config| `mode` | `remote` | 兼容旧配置的字段。当前只支持 remote。 || `baseUrl` | `http://127.0.0.1:1933` | OpenViking HTTP 地址 || `apiKey` | 空 | OpenViking API key |-| `agent_prefix` | 空 | OpenClaw agent ID 的可选前缀;若没有 agent ID,插件使用 `main`。交互式配置只接受字母、数字、`_` 和 `-`。 |+| `peer_role` | `none` | 控制 session message 和 recall/search 请求是否写 `peer_id`:`none`、`assistant` 或 `person`。 |+| `peer_prefix` | 空 | `peer_role=assistant` 时 assistant `peer_id` 的可选前缀。 || `accountId` | 空 | 使用 root API key 时需要 || `userId` | 空 | 使用 root API key 时需要 |@@ -229,14 +230,16 @@ openclaw config get plugins.entries.openviking.config| --- | --- | --- || `baseUrl` | `http://127.0.0.1:1933` | 远端 OpenViking 服务地址 || `apiKey` | 空 | 远端 OpenViking API Key;服务端未开启认证时可不填 |-| `agent_prefix` | 空 | OpenClaw agent ID 的可选前缀;如果拿不到 agent ID,插件使用 `main`。交互式配置只接受字母、数字、`_` 和 `-` |+| `peer_role` | `none` | 控制 session message 和 recall/search 请求是否写 `peer_id`:`none`、`assistant` 或 `person` |+| `peer_prefix` | 空 | `peer_role=assistant` 时 assistant `peer_id` 的可选前缀 |常见设置:```bashopenclaw config set plugins.entries.openviking.config.baseUrl http://your-server:1933openclaw config set plugins.entries.openviking.config.apiKey your-api-key-openclaw config set plugins.entries.openviking.config.agent_prefix your-prefix+openclaw config set plugins.entries.openviking.config.peer_role assistant+openclaw config set plugins.entries.openviking.config.peer_prefix your-prefix```## 升级@@ -289,7 +292,8 @@ ov-install| `--current-version` | 查看 helper 记录的当前版本 || `--base-url URL` | OpenViking 服务器地址(启用非交互模式) || `--api-key KEY` | OpenViking API key |-| `--agent-prefix PREFIX` | Agent 路由前缀 |+| `--peer-role ROLE` | Peer role:`none`、`assistant` 或 `person` |+| `--peer-prefix PREFIX` | assistant `peer_id` 的前缀 || `--update` | 更新 helper 管理的安装 |面向用户的安装,请先使用 `openclaw plugins install clawhub:@openviking/openclaw-plugin`。只有作为备用路径时才选择 `ov-install`。@@ -315,7 +319,7 @@ openclaw gateway restartopenclaw openviking status --json```-已有的配置字段(`baseUrl`、`apiKey`、`agentId` 等)会保留。新版本在运行时兼容读取旧字段名,无需手动修改配置。+已有的配置字段(`baseUrl`、`apiKey`、`peer_role`、`peer_prefix` 等)会保留。### 旧插件 ID(memory-openviking,版本 < 0.3.x)diff --git a/examples/openclaw-plugin/INSTALL.md b/examples/openclaw-plugin/INSTALL.mdindex 74f2bab58..412608980 100644--- a/examples/openclaw-plugin/INSTALL.md+++ b/examples/openclaw-plugin/INSTALL.md@@ -141,10 +141,10 @@ If another context engine already owns the slot, setup will not replace it by deopenclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --force-slot --json```-If you need a custom agent routing prefix (optional; most users leave this empty):+If you want assistant messages to carry a prefixed `peer_id` (optional; most users keep the default `none`):```bash-openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --agent-prefix <PREFIX> --json+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --peer-role assistant --peer-prefix <PREFIX> --json```### 3. Restart OpenClaw Gateway@@ -205,7 +205,8 @@ Core fields:| `mode` | `remote` | Legacy compatibility field. Only remote mode is supported. || `baseUrl` | `http://127.0.0.1:1933` | OpenViking HTTP endpoint || `apiKey` | empty | OpenViking API key |-| `agent_prefix` | empty | Optional prefix for OpenClaw agent IDs. If no agent ID is available, the plugin uses `main`. Interactive setup accepts only letters, digits, `_`, and `-`. |+| `peer_role` | `none` | Controls session `peer_id` writes and recall/search `peer_id`: `none`, `assistant`, or `person`. |+| `peer_prefix` | empty | Optional prefix for assistant `peer_id` values when `peer_role=assistant`. || `accountId` | empty | Required when using a root API key || `userId` | empty | Required when using a root API key |@@ -271,7 +272,8 @@ Useful backup/source flags:| `--current-version` | Print the version tracked by the helper || `--base-url URL` | OpenViking server URL (enables non-interactive mode) || `--api-key KEY` | OpenViking API key |-| `--agent-prefix PREFIX` | Agent routing prefix |+| `--peer-role ROLE` | Peer role: `none`, `assistant`, or `person` |+| `--peer-prefix PREFIX` | Prefix for assistant `peer_id` values || `--update` | Update an existing helper-managed install |For user-facing installs, use `openclaw plugins install clawhub:@openviking/openclaw-plugin` first. Choose `ov-install` only as the backup path.@@ -297,7 +299,7 @@ openclaw gateway restartopenclaw openviking status --json```-Your existing config fields (`baseUrl`, `apiKey`, `agentId`, etc.) are preserved. The new plugin version reads old field names at runtime — no manual config edits needed.+Your existing config fields such as `baseUrl`, `apiKey`, `peer_role`, and `peer_prefix` are preserved.The plugin configuration lives under `plugins.entries.openviking.config`.@@ -315,14 +317,16 @@ The plugin connects to an existing remote OpenViking server.| --- | --- | --- || `baseUrl` | `http://127.0.0.1:1933` | Remote OpenViking HTTP endpoint || `apiKey` | empty | Optional OpenViking API key |-| `agent_prefix` | empty | Optional prefix for OpenClaw agent IDs. If no agent ID is available, the plugin uses `main`. Interactive setup accepts only letters, digits, `_`, and `-` |+| `peer_role` | `none` | Controls session `peer_id` writes and recall/search `peer_id`: `none`, `assistant`, or `person` |+| `peer_prefix` | empty | Optional prefix for assistant `peer_id` values when `peer_role=assistant` |Common settings:```bashopenclaw config set plugins.entries.openviking.config.baseUrl http://your-server:1933openclaw config set plugins.entries.openviking.config.apiKey your-api-key-openclaw config set plugins.entries.openviking.config.agent_prefix your-prefix+openclaw config set plugins.entries.openviking.config.peer_role assistant+openclaw config set plugins.entries.openviking.config.peer_prefix your-prefix```## Startdiff --git a/examples/openclaw-plugin/README.md b/examples/openclaw-plugin/README.mdindex 0546ee597..758b0d2b2 100644--- a/examples/openclaw-plugin/README.md+++ b/examples/openclaw-plugin/README.md@@ -50,9 +50,9 @@ Once installed, the plugin provides these agent tools:- **What is sent**: User/assistant message text from each turn (after stripping injected memory blocks and metadata noise).- **Where it goes**: Your configured OpenViking server (`baseUrl`). The plugin only sends data to that server; downstream model/provider data handling (embedding, VLM) depends on the server's configuration.-- **Storage**: All data lives on your OpenViking server under `viking://user/*`, `viking://agent/*`, and `viking://session/*`.+- **Storage**: All data lives on your OpenViking server under `viking://user/*`, `viking://resources/*`, and `viking://session/*`.- **API Key**: Sent as `X-OpenViking-Key` header over your configured connection. Never logged or forwarded.-- **Multi-tenant isolation**: Supports `accountId`, `userId`, and `agent_prefix` for per-tenant scoping.+- **Multi-tenant isolation**: Supports `accountId` and `userId`. Optional `peer_role` / `peer_prefix` controls whether OpenClaw speakers are written as OpenViking `peer_id`.## Verify@@ -99,53 +99,45 @@ The diagram above reflects the current implementation boundary:- OpenClaw remains the primary runtime on the left. The plugin does not take over agent execution.- The middle layer combines hooks, the context engine, tools, and runtime management in one plugin registration.-- All HTTP traffic goes through `OpenVikingClient`, which centralizes `X-OpenViking-*` headers and routing logs.-- The OpenViking service owns sessions, memories, archives, and Phase 2 extraction, with storage under `viking://user/*`, `viking://agent/*`, and `viking://session/*`.+- All HTTP traffic goes through `OpenVikingClient`, which centralizes tenant headers and routing logs.+- The OpenViking service owns sessions, memories, archives, and Phase 2 extraction, with storage under `viking://user/*`, `viking://resources/*`, and `viking://session/*`.That split lets OpenClaw stay focused on reasoning and orchestration while OpenViking becomes the source of truth for long-lived context.## Identity and Routing-The plugin does not send one fixed agent ID to OpenViking. It tries to keep OpenClaw session identity and OpenViking routing aligned.+The plugin keeps OpenClaw session identity in session and peer metadata. It does not send an OpenViking agent identity or create an agent namespace.The main rules are:- reuse `sessionId` directly when it is already a UUID- prefer `sessionKey` when deriving a stable `ovSessionId`- normalize unsafe path characters, or fall back to a stable SHA-256 when needed-- resolve `X-OpenViking-Agent` per session, not per process-- when `plugins.entries.openviking.config.agent_prefix` is non-empty, prefix the session agent as `<agent_prefix>_<sessionAgent>`-- when OpenClaw does not provide a session agent, use its default agent `main`-- send `X-OpenViking-Agent` on OpenViking requests, including startup health checks+- `peer_role=none` is the default and does not write `peer_id` on session messages+- `peer_role=assistant` writes assistant messages with `peer_id=<sessionAgent>`; if `peer_prefix` is set, the value becomes `<peer_prefix>_<sessionAgent>`+- `peer_role=person` writes user messages with `peer_id` derived from OpenClaw sender identity; assistant messages do not get `peer_id`+- recall/search requests also send the same resolved `peer_id` when `peer_role` is `assistant` or `person`+- when OpenClaw does not provide a session agent, use its default agent `main` for local session and assistant peer metadata- only add `X-OpenViking-Account` / `X-OpenViking-User` when `accountId` / `userId` are explicitly configured-This matters because the plugin is built to support multi-agent and multi-session OpenClaw usage without mixing memories across sessions.+This matters because OpenViking tenant identity is account/user-scoped, while OpenClaw agent identity is runtime metadata.The recommended remote-mode configuration only needs:- `baseUrl`- `apiKey`-- `agent_prefix`+- optionally `peer_role`+- optionally `peer_prefix` when `peer_role=assistant`In this setup:- `apiKey` should usually be a user key+- new installs default to `peer_role=none`- `accountId` / `userId` are advanced options only when the deployment needs explicit identity headers, such as root-key or trusted-server flows-- `isolateUserScopeByAgent` / `isolateAgentScopeByUser` must match the server-side account namespace policy when using the PR #1356 canonical namespace model-- `agentScopeMode` is a deprecated compatibility alias for older hash-based routing and should only be used against older servers-### Canonical namespace policy+### Canonical user namespace-For OpenViking servers that include PR #1356, the plugin no longer treats agent or user scope as a locally computed hash. Instead it expands shorthand aliases into canonical URIs using the configured namespace policy:--- `viking://user/memories`- - `viking://user/<user_id>/memories` when `isolateUserScopeByAgent=false`- - `viking://user/<user_id>/agent/<agent_id>/memories` when `isolateUserScopeByAgent=true`-- `viking://agent/memories`- - `viking://agent/<agent_id>/memories` when `isolateAgentScopeByUser=false`- - `viking://agent/<agent_id>/user/<user_id>/memories` when `isolateAgentScopeByUser=true`--The plugin cannot auto-discover this policy today because `/api/v1/system/status` does not expose it. Configure the two booleans explicitly so they stay aligned with the server-side account policy.+The plugin writes and searches user-scoped memory. `viking://user/memories` is expanded to `viking://user/<user_id>/memories` using the identity resolved from the configured user key. `viking://agent/...` is deprecated by OpenViking and is not used by the plugin.## assemble Recall Flow@@ -161,7 +153,7 @@ During recall, the plugin:1. Extracts query text from the latest user message.2. Resolves the agent routing for the current `sessionId/sessionKey`.3. Runs a quick availability precheck so model requests do not stall when OpenViking is unavailable.-4. Queries both `viking://user/memories` and `viking://agent/memories` in parallel.+4. Queries `viking://user/memories` and optionally `viking://resources`.5. Deduplicates, threshold-filters, reranks, and trims the results under a token budget.6. Prepends the selected memories as a `<relevant-memories>` block to the current user message; it does not append a standalone synthetic user message.@@ -259,7 +251,7 @@ They serve different roles:Resource and skill imports are intentionally separate because they land in different OpenViking namespaces and use different server APIs:- resources go through `/api/v1/resources` and land under `viking://resources/...`-- skills go through `/api/v1/skills` and land under `viking://agent/skills/...`+- skills go through `/api/v1/skills` and land under `viking://user/skills/...`The plugin also registers explicit slash commands for manual imports:@@ -267,7 +259,7 @@ The plugin also registers explicit slash commands for manual imports:/add-resource ./README.md --to viking://resources/openviking-readme --wait/add-skill ./skills/install-openviking-memory --wait/ov-search "OpenViking install" --uri viking://resources/openviking-readme-/ov-search "memory install skill" --uri viking://agent/skills+/ov-search "memory install skill" --uri viking://user/skills```Resource import supports remote URLs, Git URLs, local files, local directories, and uploaded zip files. OpenViking's built-in parsers cover common documents and media such as Markdown, text, PDF, HTML, Word, PowerPoint, Excel, EPUB, images, audio, and video. Directory imports also accept common code, documentation, and config file extensions such as `.py`, `.js`, `.ts`, `.go`, `.rs`, `.java`, `.cpp`, `.json`, `.yaml`, `.toml`, `.csv`, `.rst`, `.proto`, `.tf`, and `.vue`.diff --git a/examples/openclaw-plugin/README_CN.md b/examples/openclaw-plugin/README_CN.mdindex 8a33fd84e..b3075f409 100644--- a/examples/openclaw-plugin/README_CN.md+++ b/examples/openclaw-plugin/README_CN.md@@ -50,9 +50,9 @@ Agent 会自动完成安装 → 配置 → 重启 → 验证。详见 [INSTALL-A- **发送内容**:每轮 user/assistant 消息文本(已剥离注入的记忆块和元数据噪音)。- **发送去向**:仅发往你配置的 OpenViking 服务(`baseUrl`)。插件本身只与该服务通信;服务端对 embedding、VLM 等模型的调用取决于服务端配置。-- **存储位置**:所有数据存储在你的 OpenViking 服务上,路径为 `viking://user/*`、`viking://agent/*`、`viking://session/*`。+- **存储位置**:所有数据存储在你的 OpenViking 服务上,路径为 `viking://user/*`、`viking://resources/*`、`viking://session/*`。- **API Key**:通过 `X-OpenViking-Key` header 发送,不会被日志记录或转发。-- **多租户隔离**:支持 `accountId`、`userId`、`agent_prefix` 三级租户隔离。+- **多租户隔离**:支持 `accountId`、`userId`。可选的 `peer_role` / `peer_prefix` 控制是否把 OpenClaw 说话人写入 OpenViking `peer_id`。## 验证@@ -99,53 +99,45 @@ openclaw config get plugins.slots.contextEngine # 应输出:openviking- OpenClaw 在左侧,仍然是主运行时;插件并不接管 agent 执行本身。- 插件中间层把 Hook、Context Engine、Tools、Runtime Manager 四部分合并在一个注册单元里。-- 所有 HTTP 调用最终都走 `OpenVikingClient`,由 client 层统一补 `X-OpenViking-*` 头和路由日志。-- OpenViking 服务端承接 session、memory、archive 和 Phase 2 抽取,底层存储落在 `viking://user/*`、`viking://agent/*`、`viking://session/*`。+- 所有 HTTP 调用最终都走 `OpenVikingClient`,由 client 层统一补租户 header 和路由日志。+- OpenViking 服务端承接 session、memory、archive 和 Phase 2 抽取,底层存储落在 `viking://user/*`、`viking://resources/*`、`viking://session/*`。这套拆分的意义,是让 OpenClaw 继续专注推理与编排,让 OpenViking 成为长期上下文的事实源。## 身份与路由-这套插件不是把所有请求都打到一个固定 agent ID 上,而是尽量保持 OpenClaw 会话身份和 OpenViking 路由一致。+插件会把 OpenClaw 会话身份保留在 session 和 peer metadata 里,但不会向 OpenViking 发送 agent 身份,也不会创建 agent namespace。核心规则如下:- `sessionId` 是 UUID 时直接复用。- `sessionKey` 存在时优先用它生成稳定的 `ovSessionId`。- 非安全路径字符会被规整或退化成稳定的 SHA-256。-- `X-OpenViking-Agent` 按 session 解析,不按进程写死。-- 若 `plugins.entries.openviking.config.agent_prefix` 非空,会形成 `<agent_prefix>_<sessionAgent>` 的前缀形式。-- OpenClaw 没有提供 session agent 时,使用其默认 agent `main`。-- OpenViking 请求都会发送 `X-OpenViking-Agent`,包括启动阶段的 health check。+- `peer_role=none` 是默认值,session message 不写 `peer_id`。+- `peer_role=assistant` 时,assistant message 写入 `peer_id=<sessionAgent>`;如果配置了 `peer_prefix`,则写入 `<peer_prefix>_<sessionAgent>`。+- `peer_role=person` 时,user message 使用 OpenClaw sender 身份派生 `peer_id`;assistant message 不写 `peer_id`。+- recall/search 请求也会在 `peer_role=assistant` 或 `peer_role=person` 时发送同一个解析后的 `peer_id`。+- OpenClaw 没有提供 session agent 时,使用其默认 agent `main` 作为本地 session 和 assistant peer metadata。- 只有显式配置了 `accountId` / `userId` 时才发送 `X-OpenViking-Account` / `X-OpenViking-User`。-这样做是为了支持多 agent、多 session 并发时的记忆隔离,避免不同 OpenClaw 会话串用同一套长期上下文。+这样做是因为 OpenViking 的租户身份是 account/user 级,OpenClaw agent 身份只作为运行时 metadata 使用。默认推荐的远程模式配置只有:- `baseUrl`- `apiKey`-- `agent_prefix`+- 可选 `peer_role`+- `peer_role=assistant` 时可选 `peer_prefix`其中:- `apiKey` 推荐使用某个 user 的 user key+- 新安装默认 `peer_role=none`- `accountId` / `userId` 仅在部署需要显式身份 header 时作为高级选项使用,例如 root key 或 trusted server 流程-- 使用 PR #1356 canonical namespace 模型时,`isolateUserScopeByAgent` / `isolateAgentScopeByUser` 必须与服务端 account namespace policy 保持一致-- `agentScopeMode` 已退化为兼容旧 hash 路由的 deprecated alias,仅应在旧服务端上使用-### Canonical namespace policy+### Canonical user namespace-对于包含 PR #1356 的 OpenViking 服务端,插件不再在本地计算 user 或 agent scope hash,而是根据配置的 namespace policy 将别名 URI 展开为 canonical URI:--- `viking://user/memories`- - `isolateUserScopeByAgent=false` 时展开为 `viking://user/<user_id>/memories`- - `isolateUserScopeByAgent=true` 时展开为 `viking://user/<user_id>/agent/<agent_id>/memories`-- `viking://agent/memories`- - `isolateAgentScopeByUser=false` 时展开为 `viking://agent/<agent_id>/memories`- - `isolateAgentScopeByUser=true` 时展开为 `viking://agent/<agent_id>/user/<user_id>/memories`--插件当前无法从 `/api/v1/system/status` 自动发现这两个 policy,因此需要显式配置,使其与服务端 account policy 保持一致。+插件写入和检索 user-scoped memory。`viking://user/memories` 会根据 user key 解析出的身份展开为 `viking://user/<user_id>/memories`。`viking://agent/...` 已由 OpenViking 废弃,插件不再使用。## assemble 召回链路@@ -161,7 +153,7 @@ openclaw config get plugins.slots.contextEngine # 应输出:openviking1. 从最后一条 user message 提取查询文本。2. 基于当前 `sessionId/sessionKey` 解析本轮的 agent 路由。3. 先做一次快速可用性检查,避免在 OpenViking 不可用时拖慢模型请求。-4. 并行检索 `viking://user/memories` 和 `viking://agent/memories`。+4. 检索 `viking://user/memories`,并按配置可选检索 `viking://resources`。5. 在插件侧做去重、阈值筛选、重排和 token budget 裁剪。6. 把最终记忆块以 `<relevant-memories>` 形式 prepend 到当前 user message;不会追加独立 synthetic user message。@@ -259,7 +251,7 @@ preflight 阶段的 `assemble()` 并不是简单地把旧聊天记录塞回来Resource 和 skill 保持两个入口,因为它们落在不同 OpenViking 命名空间,并使用不同服务端 API:- resource 走 `/api/v1/resources`,落到 `viking://resources/...`-- skill 走 `/api/v1/skills`,落到 `viking://agent/skills/...`+- skill 走 `/api/v1/skills`,落到 `viking://user/skills/...`插件也提供显式 slash command,方便手动导入:@@ -267,7 +259,7 @@ Resource 和 skill 保持两个入口,因为它们落在不同 OpenViking 命/add-resource ./README.md --to viking://resources/openviking-readme --wait/add-skill ./skills/install-openviking-memory --wait/ov-search "OpenViking install" --uri viking://resources/openviking-readme-/ov-search "memory install skill" --uri viking://agent/skills+/ov-search "memory install skill" --uri viking://user/skills```Resource 导入支持远程 URL、Git URL、本地文件、本地目录和 zip。OpenViking 内置 parser 覆盖常见文档和媒体类型,例如 Markdown、纯文本、PDF、HTML、Word、PowerPoint、Excel、EPUB、图片、音频和视频。目录导入还支持常见代码、文档和配置扩展名,例如 `.py`、`.js`、`.ts`、`.go`、`.rs`、`.java`、`.cpp`、`.json`、`.yaml`、`.toml`、`.csv`、`.rst`、`.proto`、`.tf`、`.vue`。diff --git a/examples/openclaw-plugin/auto-recall.ts b/examples/openclaw-plugin/auto-recall.tsindex 83489f1b1..a7dba76e3 100644--- a/examples/openclaw-plugin/auto-recall.ts+++ b/examples/openclaw-plugin/auto-recall.ts@@ -189,11 +189,12 @@ export async function buildAutoRecallContext(params: {cfg: Required<MemoryOpenVikingConfig>;client: OpenVikingClient;agentId: string;+ peerId?: string;queryText: string;logger: Logger;verbose?: (message: string) => void;}): Promise<{ block?: string; memoryCount: number; estimatedTokens: number }> {- const { cfg, client, agentId, queryText, logger, verbose } = params;+ const { cfg, client, agentId, peerId, queryText, logger, verbose } = params;if (!cfg.autoRecall || queryText.length < 5) {return { memoryCount: 0, estimatedTokens: 0 };@@ -213,11 +214,13 @@ export async function buildAutoRecallContext(params: {targetUri: "viking://user/memories",limit: candidateLimit,scoreThreshold: 0,+ peerId,}, agentId),client.find(queryText, {- targetUri: "viking://agent/memories",+ targetUri: "viking://user/memories",limit: candidateLimit,scoreThreshold: 0,+ peerId,}, agentId),];if (cfg.recallResources) {@@ -226,6 +229,7 @@ export async function buildAutoRecallContext(params: {targetUri: "viking://resources",limit: candidateLimit,scoreThreshold: 0,+ peerId,}, agentId),);}diff --git a/examples/openclaw-plugin/client.ts b/examples/openclaw-plugin/client.tsindex 4e607d4fc..98961e4ba 100644--- a/examples/openclaw-plugin/client.ts+++ b/examples/openclaw-plugin/client.ts@@ -25,8 +25,6 @@ export type FindResult = {};export type CaptureMode = "semantic" | "keyword";-export type ScopeName = "user" | "agent";-export type AgentScopeMode = "user_agent" | "agent";export type RuntimeIdentity = {userId: string;agentId: string;@@ -44,6 +42,15 @@ export type CommitSessionResult = {trace_id?: string;};+export type OVMemoryPolicySwitch = {+ enabled?: boolean;+};++export type OVMemoryPolicy = {+ self?: OVMemoryPolicySwitch;+ peer?: OVMemoryPolicySwitch;+};+export type TaskResult = {task_id: string;task_type: string;@@ -195,18 +202,9 @@ function sleep(ms: number): Promise<void> {}const MEMORY_URI_PATTERNS = [- /^viking:\/\/user\/(?:[^/]+(?:\/agent\/[^/]+)?\/)?memories(?:\/|$)/,- /^viking:\/\/agent\/(?:[^/]+(?:\/user\/[^/]+)?\/)?memories(?:\/|$)/,+ /^viking:\/\/user\/(?:[^/]+\/)?memories(?:\/|$)/,];-const USER_STRUCTURE_DIRS = new Set(["memories", "profile.md", ".abstract.md", ".overview.md"]);-const AGENT_STRUCTURE_DIRS = new Set([- "memories",- "skills",- "instructions",- "workspaces",- ".abstract.md",- ".overview.md",-]);+const USER_STRUCTURE_DIRS = new Set(["memories", "skills", "profile.md", ".abstract.md", ".overview.md"]);const REMOTE_RESOURCE_PREFIXES = ["http://", "https://", "git@", "ssh://", "git://"];export function isMemoryUri(uri: string): boolean {@@ -250,8 +248,6 @@ export class OpenVikingClient {private readonly userId: string = "",/** When set, logs routing for find + session writes (tenant headers + paths; never apiKey). */private readonly routingDebugLog?: (message: string) => void,- private readonly isolateUserScopeByAgent = false,- private readonly isolateAgentScopeByUser = true,) {}getDefaultAgentId(): string {@@ -299,7 +295,7 @@ export class OpenVikingClient {`openviking: ${label} ` +JSON.stringify({...detail,- X_OpenViking_Agent: effectiveAgentId,+ runtime_agent_id: effectiveAgentId,X_OpenViking_Account: tenantHeaders.accountId ?? null,X_OpenViking_User: tenantHeaders.userId ?? null,resolved_user_id: identity.userId,@@ -316,7 +312,7 @@ export class OpenVikingClient {agentId?: string,requestTimeoutMs?: number,): Promise<T> {- const effectiveAgentId = this.resolveEffectiveAgentId(agentId);+ void agentId;const controller = new AbortController();const timer = setTimeout(() => controller.abort(), requestTimeoutMs ?? this.timeoutMs);try {@@ -331,9 +327,6 @@ export class OpenVikingClient {if (tenantHeaders.userId) {headers.set("X-OpenViking-User", tenantHeaders.userId);}- if (effectiveAgentId) {- headers.set("X-OpenViking-Agent", effectiveAgentId);- }if (init.body && !(init.body instanceof FormData) && !headers.has("Content-Type")) {headers.set("Content-Type", "application/json");}@@ -366,6 +359,39 @@ export class OpenVikingClient {await this.request<{ status: string }>("/health", {}, agentId, requestTimeoutMs);}+ async createSession(+ sessionId: string,+ options?: { memoryPolicy?: OVMemoryPolicy },+ agentId?: string,+ ): Promise<{ session_id: string; user?: unknown }> {+ const body: Record<string, unknown> = { session_id: sessionId };+ if (options?.memoryPolicy) {+ body.memory_policy = options.memoryPolicy;+ }+ return this.request<{ session_id: string; user?: unknown }>(+ "/api/v1/sessions",+ { method: "POST", body: JSON.stringify(body) },+ agentId,+ );+ }++ async ensureSession(+ sessionId: string,+ options?: { memoryPolicy?: OVMemoryPolicy },+ agentId?: string,+ ): Promise<boolean> {+ try {+ await this.createSession(sessionId, options, agentId);+ return true;+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ if (message.includes("[ALREADY_EXISTS]")) {+ return false;+ }+ throw err;+ }+ }+private async getRuntimeIdentity(agentId?: string): Promise<RuntimeIdentity> {const effectiveAgentId = this.resolveEffectiveAgentId(agentId);const cached = this.identityCache.get(effectiveAgentId);@@ -386,28 +412,18 @@ export class OpenVikingClient {}}- private async buildCanonicalRoot(scope: ScopeName, agentId?: string): Promise<string> {+ private async buildCanonicalRoot(agentId?: string): Promise<string> {const identity = await this.getRuntimeIdentity(agentId);- if (scope === "user") {- const root = this.isolateUserScopeByAgent- ? `viking://user/${identity.userId}/agent/${identity.agentId}`- : `viking://user/${identity.userId}`;- return root;- }- const root = this.isolateAgentScopeByUser- ? `viking://agent/${identity.agentId}/user/${identity.userId}`- : `viking://agent/${identity.agentId}`;- return root;+ return `viking://user/${identity.userId}`;}private async normalizeTargetUri(targetUri: string, agentId?: string): Promise<string> {const trimmed = targetUri.trim().replace(/\/+$/, "");- const match = trimmed.match(/^viking:\/\/(user|agent)(?:\/(.*))?$/);+ const match = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);if (!match) {return trimmed;}- const scope = match[1] as ScopeName;- const rawRest = (match[2] ?? "").trim();+ const rawRest = (match[1] ?? "").trim();if (!rawRest) {return trimmed;}@@ -416,43 +432,54 @@ export class OpenVikingClient {return trimmed;}- const reservedDirs = scope === "user" ? USER_STRUCTURE_DIRS : AGENT_STRUCTURE_DIRS;- if (!reservedDirs.has(parts[0]!)) {+ let suffix = parts;+ if (!USER_STRUCTURE_DIRS.has(suffix[0]!)) {return trimmed;}- const root = await this.buildCanonicalRoot(scope, agentId);- return `${root}/${parts.join("/")}`;+ const root = await this.buildCanonicalRoot(agentId);+ return `${root}/${suffix.join("/")}`;}async find(query: string,options: {targetUri: string;- limit: number;+ limit?: number;scoreThreshold?: number;+ peerId?: string;},agentId?: string,): Promise<FindResult> {const normalizedTargetUri = await this.normalizeTargetUri(options.targetUri, agentId);- const body = {+ const body: {+ query: string;+ target_uri: string;+ limit?: number;+ score_threshold?: number;+ peer_id?: string;+ } = {query,target_uri: normalizedTargetUri,limit: options.limit,score_threshold: options.scoreThreshold,};+ if (options.peerId) {+ body.peer_id = options.peerId;+ }const effectiveAgentId = this.resolveEffectiveAgentId(agentId);const identity = await this.getRuntimeIdentity(agentId);const tenantHeaders = this.resolveTenantHeaders();this.routingDebugLog?.(`openviking: find POST ${this.baseUrl}/api/v1/search/find ` +JSON.stringify({- X_OpenViking_Agent: effectiveAgentId,+ runtime_agent_id: effectiveAgentId,X_OpenViking_Account: tenantHeaders.accountId ?? null,X_OpenViking_User: tenantHeaders.userId ?? null,resolved_user_id: identity.userId,target_uri: normalizedTargetUri,target_uri_input: options.targetUri,+ peer_id: options.peerId ?? null,query:query.length > 4000? `${query.slice(0, 4000)}…(+${query.length - 4000} more chars)`@@ -731,19 +758,19 @@ export class OpenVikingClient {}>,agentId?: string,createdAt?: string,- roleId?: string,+ peerId?: string,): Promise<void> {const body: {role: string;- role_id?: string;+ peer_id?: string;parts: typeof parts;created_at?: string;} = { role, parts };if (createdAt) {body.created_at = createdAt;}- if (roleId) {- body.role_id = roleId;+ if (peerId) {+ body.peer_id = peerId;}await this.emitRoutingDebug("session message POST (with parts)",@@ -751,7 +778,7 @@ export class OpenVikingClient {path: `/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`,sessionId,role,- role_id: roleId ?? null,+ peer_id: peerId ?? null,partCount: parts.length,created_at: createdAt ?? null,},@@ -807,6 +834,7 @@ export class OpenVikingClient {* preserves the pre-v2 "archive everything" behavior.*/keepRecentCount?: number;+ memoryPolicy?: OVMemoryPolicy;},): Promise<CommitSessionResult> {const keepRecentCount =@@ -827,6 +855,9 @@ export class OpenVikingClient {if (keepRecentCount > 0) {body.keep_recent_count = keepRecentCount;}+ if (options?.memoryPolicy) {+ body.memory_policy = options.memoryPolicy;+ }const result = await this.request<CommitSessionResult>(`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`,{ method: "POST", body: JSON.stringify(body) },diff --git a/examples/openclaw-plugin/commands/setup.ts b/examples/openclaw-plugin/commands/setup.tsindex d4e6fff04..69cafe16f 100644--- a/examples/openclaw-plugin/commands/setup.ts+++ b/examples/openclaw-plugin/commands/setup.ts@@ -56,6 +56,28 @@ function readCompatRangeFromManifest(): { min: string; max: string } {const PLUGIN_VERSION = readPluginVersion();const { min: COMPATIBLE_SERVER_MIN, max: COMPATIBLE_SERVER_MAX } = readCompatRangeFromManifest();+const CONFIG_KEYS_TO_PRESERVE = [+ "targetUri",+ "timeoutMs",+ "autoCapture",+ "captureMode",+ "captureMaxLength",+ "autoRecall",+ "recallResources",+ "recallLimit",+ "recallScoreThreshold",+ "recallMaxInjectedChars",+ "recallMaxContentChars",+ "recallPreferAbstract",+ "recallTokenBudget",+ "commitTokenThreshold",+ "commitKeepRecentCount",+ "bypassSessionPatterns",+ "emitStandardDiagnostics",+ "logFindRequests",+] as const;++type PeerRole = "none" | "assistant" | "person";type CommandProgram = {command: (name: string) => CommandBuilder;@@ -81,29 +103,91 @@ function maskKey(key: string): string {return `${key.slice(0, 4)}...${key.slice(-4)}`;}-function isValidAgentPrefixInput(value: string): boolean {+function isValidPeerPrefixInput(value: string): boolean {const trimmed = value.trim();return !trimmed || /^[a-zA-Z0-9_-]+$/.test(trimmed);}-async function askAgentPrefix(+function normalizePeerRole(value: unknown): PeerRole | undefined {+ if (typeof value !== "string") return undefined;+ const role = value.trim().toLowerCase();+ if (role === "none" || role === "assistant" || role === "person") return role;+ return undefined;+}++function resolveExistingPeerRole(existing: Record<string, unknown> | null | undefined): PeerRole {+ const explicit = normalizePeerRole(existing?.peer_role);+ if (explicit) return explicit;+ return "none";+}++function resolveExistingPeerPrefix(existing: Record<string, unknown> | null | undefined): string {+ const value = existing?.peer_prefix;+ if (typeof value !== "string" || !value.trim()) return "";+ const trimmed = value.trim();+ return trimmed === "default" ? "" : trimmed;+}++function resolveSetupPeerRole(value: unknown): PeerRole {+ if (value === undefined) return "none";+ const role = normalizePeerRole(value);+ if (role) return role;+ throw new Error('peer_role must be "none", "assistant", or "person"');+}++function preserveCurrentConfig(existing: Record<string, unknown> | null | undefined) {+ const config: Record<string, unknown> = {};+ if (!existing) {+ return config;+ }+ for (const key of CONFIG_KEYS_TO_PRESERVE) {+ if (key in existing) {+ config[key] = existing[key];+ }+ }+ return config;+}++async function askPeerRole(+ zh: boolean,+ q: (prompt: string, def?: string) => Promise<string>,+ defaultValue: PeerRole,+): Promise<PeerRole> {+ while (true) {+ const value = await q(+ tr(zh, "Peer Role (none/assistant/person)", "Peer Role(none/assistant/person)"),+ defaultValue,+ );+ const role = normalizePeerRole(value);+ if (role) return role;+ console.log(+ ` ✗ ${tr(+ zh,+ 'Peer Role must be "none", "assistant", or "person".',+ 'Peer Role 必须是 "none"、"assistant" 或 "person"。',+ )}`,+ );+ }+}++async function askPeerPrefix(zh: boolean,q: (prompt: string, def?: string) => Promise<string>,defaultValue: string,): Promise<string> {while (true) {const value = (await q(- tr(zh, "Agent Prefix (optional)", "Agent Prefix(可选)"),+ tr(zh, "Peer Prefix (optional)", "Peer Prefix(可选)"),defaultValue,)).trim();- if (isValidAgentPrefixInput(value)) {+ if (isValidPeerPrefixInput(value)) {return value;}console.log(` ✗ ${tr(zh,- "Agent Prefix may only contain letters, digits, underscores, and hyphens, or be empty.",- "Agent Prefix 只能包含字母、数字、下划线和连字符,或留空。",+ "Peer Prefix may only contain letters, digits, underscores, and hyphens, or be empty.",+ "Peer Prefix 只能包含字母、数字、下划线和连字符,或留空。",)}`,);}@@ -366,7 +450,8 @@ type SetupResult = {mode: string;baseUrl: string;apiKey?: string;- agent_prefix?: string;+ peer_role?: PeerRole;+ peer_prefix?: string;accountId?: string;userId?: string;};@@ -388,7 +473,8 @@ type StatusResult = {mode: string;baseUrl: string;hasApiKey: boolean;- agent_prefix?: string;+ peer_role: PeerRole;+ peer_prefix?: string;hasAccountId: boolean;hasUserId: boolean;};@@ -449,7 +535,8 @@ export function registerSetupCli(api: any): void {.option("--zh", "Chinese prompts").option("--base-url <url>", "OpenViking server URL (enables non-interactive mode)").option("--api-key <key>", "API key for authentication")- .option("--agent-prefix <prefix>", "Agent routing prefix for namespace isolation")+ .option("--peer-role <role>", "Peer ID role: none, assistant, or person")+ .option("--peer-prefix <prefix>", "Prefix for assistant peer_id values").option("--account-id <id>", "Account ID (required for root API keys)").option("--user-id <id>", "User ID (required for root API keys)").option("--allow-offline", "Allow config write even if server is unreachable")@@ -458,11 +545,11 @@ export function registerSetupCli(api: any): void {.action(async (...args: unknown[]) => {const options = (args[0] ?? {}) as Record<string, unknown>;const {- reconfigure, zh: zhOpt, baseUrl, apiKey, agentPrefix,+ reconfigure, zh: zhOpt, baseUrl, apiKey, peerRole, peerPrefix,accountId, userId, allowOffline, forceSlot, json: jsonOpt,} = options as {reconfigure?: boolean; zh?: boolean; baseUrl?: string;- apiKey?: string; agentPrefix?: string; accountId?: string;+ apiKey?: string; peerRole?: string; peerPrefix?: string; accountId?: string;userId?: string; allowOffline?: boolean; forceSlot?: boolean;json?: boolean;};@@ -475,7 +562,8 @@ export function registerSetupCli(api: any): void {const result = await setupNonInteractive(configPath, {baseUrl: baseUrl!,apiKey,- agentPrefix,+ peerRole,+ peerPrefix,accountId,userId,allowOffline: !!allowOffline,@@ -533,7 +621,9 @@ export function registerSetupCli(api: any): void {console.log(` mode: ${existing.mode}`);console.log(` baseUrl: ${existing.baseUrl ?? DEFAULT_REMOTE_URL}`);if (existing.apiKey) console.log(` apiKey: ${maskKey(String(existing.apiKey))}`);- if (existing.agent_prefix) console.log(` agent_prefix: ${existing.agent_prefix}`);+ console.log(` peer_role: ${resolveExistingPeerRole(existing)}`);+ const existingPeerPrefix = resolveExistingPeerPrefix(existing);+ if (existingPeerPrefix) console.log(` peer_prefix: ${existingPeerPrefix}`);console.log("");console.log(tr(zh,@@ -651,10 +741,15 @@ async function runRemoteCheck(async function setupNonInteractive(configPath: string,- params: { baseUrl: string; apiKey?: string; agentPrefix?: string; accountId?: string; userId?: string; allowOffline?: boolean; forceSlot?: boolean },+ params: { baseUrl: string; apiKey?: string; peerRole?: string; peerPrefix?: string; accountId?: string; userId?: string; allowOffline?: boolean; forceSlot?: boolean },): Promise<SetupResult> {try {- const { baseUrl, apiKey, agentPrefix, accountId, userId, allowOffline, forceSlot } = params;+ const { baseUrl, apiKey, peerPrefix, accountId, userId, allowOffline, forceSlot } = params;+ const resolvedPeerRole = resolveSetupPeerRole(params.peerRole);+ const resolvedPeerPrefix = (peerPrefix ?? "").trim();+ if (!isValidPeerPrefixInput(resolvedPeerPrefix)) {+ throw new Error("peer_prefix may only contain letters, digits, underscores, and hyphens, or be empty");+ }// Phase 1: validate connectivity and key type BEFORE writing configconst health = await checkServiceHealth(baseUrl, apiKey);@@ -694,7 +789,8 @@ async function setupNonInteractive(// Phase 2: all checks passed (or --allow-offline), write config and activate slotconst pluginCfg: Record<string, unknown> = { mode: "remote", baseUrl };if (apiKey) pluginCfg.apiKey = apiKey;- if (agentPrefix) pluginCfg.agent_prefix = agentPrefix;+ pluginCfg.peer_role = resolvedPeerRole;+ if (resolvedPeerPrefix) pluginCfg.peer_prefix = resolvedPeerPrefix;if (accountId) pluginCfg.accountId = accountId;if (userId) pluginCfg.userId = userId;@@ -709,7 +805,8 @@ async function setupNonInteractive(mode: "remote",baseUrl,...(apiKey ? { apiKey: maskKey(apiKey) } : {}),- ...(agentPrefix ? { agent_prefix: agentPrefix } : {}),+ peer_role: resolvedPeerRole,+ ...(resolvedPeerPrefix ? { peer_prefix: resolvedPeerPrefix } : {}),...(accountId ? { accountId } : {}),...(userId ? { userId } : {}),},@@ -727,7 +824,8 @@ async function setupNonInteractive(mode: "remote",baseUrl,...(apiKey ? { apiKey: maskKey(apiKey) } : {}),- ...(agentPrefix ? { agent_prefix: agentPrefix } : {}),+ peer_role: resolvedPeerRole,+ ...(resolvedPeerPrefix ? { peer_prefix: resolvedPeerPrefix } : {}),...(accountId ? { accountId } : {}),...(userId ? { userId } : {}),},@@ -754,7 +852,8 @@ function printSetupResult(zh: boolean, result: SetupResult): void {console.log(` mode: ${result.config.mode}`);console.log(` baseUrl: ${result.config.baseUrl}`);if (result.config.apiKey) console.log(` apiKey: ${result.config.apiKey}`);- if (result.config.agent_prefix) console.log(` agent_prefix: ${result.config.agent_prefix}`);+ console.log(` peer_role: ${result.config.peer_role ?? "none"}`);+ if (result.config.peer_prefix) console.log(` peer_prefix: ${result.config.peer_prefix}`);if (result.config.accountId) console.log(` accountId: ${result.config.accountId}`);if (result.config.userId) console.log(` userId: ${result.config.userId}`);}@@ -798,14 +897,15 @@ async function getStatus(configPath: string): Promise<StatusResult> {const health = await checkServiceHealth(baseUrl, apiKey);const keyProbe = health.ok ? await probeApiKeyType(baseUrl, apiKey) : undefined;- const agentPrefix = existing.agent_prefix ?? existing.agentId;+ const peerPrefix = resolveExistingPeerPrefix(existing);return {configured: true,config: {mode: String(existing.mode ?? "remote"),baseUrl,hasApiKey: !!existing.apiKey,- ...(agentPrefix ? { agent_prefix: String(agentPrefix) } : {}),+ peer_role: resolveExistingPeerRole(existing),+ ...(peerPrefix ? { peer_prefix: peerPrefix } : {}),hasAccountId: !!existing.accountId,hasUserId: !!existing.userId,},@@ -869,7 +969,8 @@ function printStatus(zh: boolean, result: StatusResult): void {console.log(` mode: ${result.config.mode}`);console.log(` baseUrl: ${result.config.baseUrl}`);console.log(` apiKey: ${result.config.hasApiKey ? "set" : "not set"}`);- if (result.config.agent_prefix) console.log(` agent_prefix: ${result.config.agent_prefix}`);+ console.log(` peer_role: ${result.config.peer_role}`);+ if (result.config.peer_prefix) console.log(` peer_prefix: ${result.config.peer_prefix}`);console.log(` accountId: ${result.config.hasAccountId ? "set" : "not set"}`);console.log(` userId: ${result.config.hasUserId ? "set" : "not set"}`);}@@ -904,7 +1005,8 @@ async function setupRemote(? String(existing.baseUrl): DEFAULT_REMOTE_URL;const defaultApiKey = existing?.apiKey ? String(existing.apiKey) : "";- const defaultAgentPrefix = existing?.agent_prefix ? String(existing.agent_prefix) : "";+ const defaultPeerRole = resolveExistingPeerRole(existing);+ const defaultPeerPrefix = resolveExistingPeerPrefix(existing);const baseUrl = await q(tr(zh, "OpenViking server URL", "OpenViking 服务器地址"), defaultUrl);const apiKey = await q(tr(zh, "API Key (optional)", "API Key(可选)"), defaultApiKey);@@ -927,7 +1029,10 @@ async function setupRemote(}}- const agentPrefix = await askAgentPrefix(zh, q, defaultAgentPrefix);+ const peerRole = await askPeerRole(zh, q, defaultPeerRole);+ const peerPrefix = peerRole === "assistant"+ ? await askPeerPrefix(zh, q, defaultPeerPrefix)+ : "";console.log("");@@ -948,20 +1053,19 @@ async function setupRemote(console.log("");const pluginCfg: Record<string, unknown> = {- ...(existing ?? {}),+ ...preserveCurrentConfig(existing),mode: "remote",baseUrl,};if (apiKey) pluginCfg.apiKey = apiKey;else delete pluginCfg.apiKey;- if (agentPrefix) pluginCfg.agent_prefix = agentPrefix;- else delete pluginCfg.agent_prefix;+ pluginCfg.peer_role = peerRole;+ if (peerPrefix) pluginCfg.peer_prefix = peerPrefix;+ else delete pluginCfg.peer_prefix;if (accountId) pluginCfg.accountId = accountId;else delete pluginCfg.accountId;if (userId) pluginCfg.userId = userId;else delete pluginCfg.userId;- delete pluginCfg.configPath;- delete pluginCfg.port;writeConfig(configPath, pluginCfg);@@ -971,7 +1075,8 @@ async function setupRemote(console.log(` ${tr(zh, "mode:", "模式:")} remote`);console.log(` baseUrl: ${baseUrl}`);if (apiKey) console.log(` apiKey: ${maskKey(apiKey)}`);- if (agentPrefix) console.log(` agent_prefix: ${agentPrefix}`);+ console.log(` peer_role: ${peerRole}`);+ if (peerPrefix) console.log(` peer_prefix: ${peerPrefix}`);if (accountId) console.log(` accountId: ${accountId}`);if (userId) console.log(` userId: ${userId}`);printSlotResult(zh, slotResult);@@ -985,7 +1090,7 @@ async function setupRemote(export const __test__ = {isLegacyLocalMode,- isValidAgentPrefixInput,+ isValidPeerPrefixInput,activateContextEngineSlot,isContextEngineSlotActive,getStatus,diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.tsindex 08f50c336..591daa516 100644--- a/examples/openclaw-plugin/config.ts+++ b/examples/openclaw-plugin/config.ts@@ -3,23 +3,13 @@ import { getEnv } from "./runtime-utils.js";export type MemoryOpenVikingConfig = {mode?: "remote";baseUrl?: string;- agent_prefix?: string;+ peer_role?: "none" | "assistant" | "person";+ peer_prefix?: string;apiKey?: string;/** Advanced option. Only needed when explicitly sending tenant identity headers. With a user key the server derives identity from the key. */accountId?: string;/** Advanced option. Only needed when explicitly sending tenant identity headers. */userId?: string;- /**- * Canonical namespace policy. Must match the server-side account namespace- * policy because current /system/status does not expose it.- */- isolateUserScopeByAgent?: boolean;- isolateAgentScopeByUser?: boolean;- /**- * Deprecated compatibility alias for older hash-based agent space behavior.- * Prefer isolateUserScopeByAgent / isolateAgentScopeByUser.- */- agentScopeMode?: "user_agent" | "agent";targetUri?: string;timeoutMs?: number;autoCapture?: boolean;@@ -69,14 +59,29 @@ const DEFAULT_COMMIT_TOKEN_THRESHOLD = 20000;const DEFAULT_COMMIT_KEEP_RECENT_COUNT = 10;const DEFAULT_BYPASS_SESSION_PATTERNS: string[] = [];const DEFAULT_EMIT_STANDARD_DIAGNOSTICS = false;-const DEFAULT_AGENT_PREFIX = "";+const DEFAULT_PEER_ROLE = "none" as const;+const DEFAULT_PEER_PREFIX = "";-function resolveAgentPrefix(configured: unknown): string {+function resolvePeerPrefix(configured: unknown): string {if (typeof configured === "string" && configured.trim()) {const trimmed = configured.trim();- return trimmed === "default" ? DEFAULT_AGENT_PREFIX : trimmed;+ return trimmed === "default" ? DEFAULT_PEER_PREFIX : trimmed;+ }+ return DEFAULT_PEER_PREFIX;+}++function resolvePeerRole(configured: unknown) {+ if (typeof configured === "string") {+ const role = configured.trim().toLowerCase();+ if (role === "none" || role === "assistant" || role === "person") {+ return role;+ }+ throw new Error(`openviking peer_role must be "none", "assistant", or "person"`);+ }+ if (configured !== undefined) {+ throw new Error(`openviking peer_role must be "none", "assistant", or "person"`);}- return DEFAULT_AGENT_PREFIX;+ return DEFAULT_PEER_ROLE;}function resolveEnvVars(value: string): string {@@ -150,26 +155,17 @@ export const memoryOpenVikingConfigSchema = {value = {};}const cfg = value as Record<string, unknown>;- if ("agentId" in cfg) {- if (!("agent_prefix" in cfg)) {- cfg.agent_prefix = cfg.agentId;- }- delete cfg.agentId;- }assertAllowedKeys(cfg,["mode","baseUrl",- "agent_prefix",- "agentId",+ "peer_role",+ "peer_prefix","serverAuthMode","apiKey","accountId","userId",- "isolateUserScopeByAgent",- "isolateAgentScopeByUser",- "agentScopeMode","targetUri","timeoutMs","autoCapture",@@ -197,6 +193,8 @@ export const memoryOpenVikingConfigSchema = {);const mode = "remote" as const;+ const peerRole = resolvePeerRole(cfg.peer_role);+ const peerPrefix = resolvePeerPrefix(cfg.peer_prefix);const rawBaseUrl = typeof cfg.baseUrl === "string" ? cfg.baseUrl : resolveDefaultBaseUrl();const resolvedBaseUrl = resolveEnvVars(rawBaseUrl).replace(/\/+$/, "");const rawApiKey = typeof cfg.apiKey === "string" ? cfg.apiKey : getEnv("OPENVIKING_API_KEY");@@ -218,37 +216,6 @@ export const memoryOpenVikingConfigSchema = {? cfg.userId.trim(): (getEnv("OPENVIKING_USER_ID")?.trim() || "");- const hasExplicitAgentScopeMode =- typeof cfg.agentScopeMode === "string" || getEnv("OPENVIKING_AGENT_SCOPE_MODE") !== undefined;- const rawAgentScope = cfg.agentScopeMode ?? getEnv("OPENVIKING_AGENT_SCOPE_MODE");- const agentScopeMode =- rawAgentScope === "user_agent" ? "user_agent" as const : "agent" as const;- const explicitIsolateUserScopeByAgent =- typeof cfg.isolateUserScopeByAgent === "boolean"- ? cfg.isolateUserScopeByAgent- : undefined;- const explicitIsolateAgentScopeByUser =- typeof cfg.isolateAgentScopeByUser === "boolean"- ? cfg.isolateAgentScopeByUser- : undefined;- const envIsolateUserScopeByAgent =- explicitIsolateUserScopeByAgent === undefined &&- getEnv("OPENVIKING_ISOLATE_USER_SCOPE_BY_AGENT") !== undefined- ? envFlag("OPENVIKING_ISOLATE_USER_SCOPE_BY_AGENT")- : undefined;- const envIsolateAgentScopeByUser =- explicitIsolateAgentScopeByUser === undefined &&- getEnv("OPENVIKING_ISOLATE_AGENT_SCOPE_BY_USER") !== undefined- ? envFlag("OPENVIKING_ISOLATE_AGENT_SCOPE_BY_USER")- : undefined;- const isolateUserScopeByAgent =- explicitIsolateUserScopeByAgent ??- envIsolateUserScopeByAgent ??- false;- const isolateAgentScopeByUser =- explicitIsolateAgentScopeByUser ??- envIsolateAgentScopeByUser ??- (hasExplicitAgentScopeMode && agentScopeMode === "user_agent" ? true : false);const recallMaxInjectedChars = Math.max(100,Math.min(@@ -265,13 +232,11 @@ export const memoryOpenVikingConfigSchema = {return {mode,baseUrl: resolvedBaseUrl,- agent_prefix: resolveAgentPrefix(cfg.agent_prefix),+ peer_role: peerRole,+ peer_prefix: peerPrefix,apiKey: rawApiKey ? resolveEnvVars(rawApiKey) : "",accountId,userId,- isolateUserScopeByAgent,- isolateAgentScopeByUser,- agentScopeMode,targetUri: typeof cfg.targetUri === "string" ? cfg.targetUri : DEFAULT_TARGET_URI,timeoutMs: Math.max(1000, Math.floor(toNumber(cfg.timeoutMs, DEFAULT_TIMEOUT_MS))),autoCapture: cfg.autoCapture !== false,@@ -331,10 +296,15 @@ export const memoryOpenVikingConfigSchema = {placeholder: DEFAULT_BASE_URL,help: "HTTP URL when mode is remote (or use ${OPENVIKING_BASE_URL})",},- agent_prefix: {- label: "Agent Prefix",+ peer_role: {+ label: "Peer Role",+ placeholder: DEFAULT_PEER_ROLE,+ help: 'Controls which session messages get peer_id: "none", "assistant", or "person".',+ },+ peer_prefix: {+ label: "Peer Prefix",placeholder: "optional-prefix",- help: 'Optional prefix for OpenViking X-OpenViking-Agent. Empty means use OpenClaw ctx.agentId directly. Non-empty values are prepended as "<prefix>_<ctx.agentId>" (sanitized to [a-zA-Z0-9_-]). If ctx.agentId is unavailable, OpenClaw default agent "main" is used.',+ help: "Optional prefix applied to assistant peer_id values derived from OpenClaw runtime agent IDs.",},apiKey: {label: "OpenViking API Key",@@ -354,24 +324,6 @@ export const memoryOpenVikingConfigSchema = {help: "Advanced option. Tenant user ID. Only needed when explicitly sending identity headers.",advanced: true,},- isolateUserScopeByAgent: {- label: "Isolate User Scope By Agent",- placeholder: "false",- help: "Canonical namespace policy. false (default): user alias expands to viking://user/<user_id>/... . true: expands to viking://user/<user_id>/agent/<agent_id>/... . Must match the server-side account namespace policy.",- advanced: true,- },- isolateAgentScopeByUser: {- label: "Isolate Agent Scope By User",- placeholder: "false",- help: "Canonical namespace policy. false (default): agent alias expands to viking://agent/<agent_id>/... . true: expands to viking://agent/<agent_id>/user/<user_id>/... . Must match the server-side account namespace policy.",- advanced: true,- },- agentScopeMode: {- label: "Deprecated Agent Scope Mode",- placeholder: "agent",- help: 'Deprecated compatibility alias for older routing behavior. Prefer isolateUserScopeByAgent / isolateAgentScopeByUser. Mapping: explicit "user_agent" => false/true, explicit "agent" => false/false. When fully unset, the plugin defaults to false/false to match the current server-side default policy.',- advanced: true,- },targetUri: {label: "Search Target URI",placeholder: DEFAULT_TARGET_URI,diff --git a/examples/openclaw-plugin/context-engine.ts b/examples/openclaw-plugin/context-engine.tsindex 9ebea3516..f1bef7e51 100644--- a/examples/openclaw-plugin/context-engine.ts+++ b/examples/openclaw-plugin/context-engine.ts@@ -1,6 +1,6 @@import { createHash } from "node:crypto";import { DEFAULT_PHASE2_POLL_TIMEOUT_MS } from "./client.js";-import type { OpenVikingClient, OVMessage } from "./client.js";+import type { OpenVikingClient, OVMemoryPolicy, OVMessage } from "./client.js";import type { MemoryOpenVikingConfig } from "./config.js";import {AUTO_RECALL_SOURCE_MARKER,@@ -49,7 +49,7 @@ type IngestResult = {ingested: boolean;};-export function toRoleId(senderId: string | undefined): string | undefined {+export function toPeerId(senderId: string | undefined): string | undefined {if (!senderId) {return undefined;}@@ -61,6 +61,49 @@ export function toRoleId(senderId: string | undefined): string | undefined {return normalized || undefined;}+export function resolveMessagePeerId(params: {+ peerRole: Required<MemoryOpenVikingConfig>["peer_role"];+ role?: string;+ personPeerId?: string;+ assistantPeerId?: string;+}): string | undefined {+ if (params.peerRole === "person" && params.role === "user") {+ return params.personPeerId;+ }+ if (params.peerRole === "assistant" && params.role === "assistant") {+ return params.assistantPeerId;+ }+ return undefined;+}++export function resolveSearchPeerId(params: {+ peerRole: Required<MemoryOpenVikingConfig>["peer_role"];+ personPeerId?: string;+ assistantPeerId?: string;+}): string | undefined {+ const role = params.peerRole === "person"+ ? "user"+ : params.peerRole === "assistant"+ ? "assistant"+ : undefined;+ return resolveMessagePeerId({+ ...params,+ role,+ });+}++export function defaultMemoryPolicyForPeerRole(+ peerRole: Required<MemoryOpenVikingConfig>["peer_role"],+): OVMemoryPolicy | undefined {+ if (peerRole === "none") {+ return undefined;+ }+ return {+ self: { enabled: true },+ peer: { enabled: true },+ };+}+type IngestBatchResult = {ingestedCount: number;};@@ -138,6 +181,25 @@ type ExtractedSender = {senderId?: string;};+type ResolvedSender = ExtractedSender & {+ source: "runtimeContext" | "promptMetadata" | "none";+ senderName?: string;+};++type PromptMetadata = {+ senderId?: string;+ senderName?: string;+};++type RecallQueryInput = {+ text: string;+ source: "latestUserMessage" | "prompt" | "none";+};++type AssembleRecall = Awaited<ReturnType<typeof buildAutoRecallContext>> & {+ queryChars: number;+};+interface ContextBudgets {archiveMemory: number;sessionContext: number;@@ -279,17 +341,39 @@ function prependTextToMessageContent(content: unknown, text: string): unknown {return text;}+function prependRecallAtIndex(messages: AgentMessage[], index: number, recallBlock: string): AgentMessage[] {+ return messages.map((msg, msgIndex) =>+ msgIndex === index+ ? { ...msg, content: prependTextToMessageContent(msg.content, recallBlock) }+ : msg+ );+}+function prependRecallToLatestUserMessage(messages: AgentMessage[], recallBlock: string): AgentMessage[] {const latest = messages.at(-1);if (!latest || latest.role !== "user" || hasAutoRecallBlock(latest)) {return messages;}+ return prependRecallAtIndex(messages, messages.length - 1, recallBlock);+}++function injectRecallIntoContext(messages: AgentMessage[], recallBlock: string): AgentMessage[] {+ const latest = messages.at(-1);+ if (latest?.role === "user" && !hasAutoRecallBlock(latest)) {+ return prependRecallToLatestUserMessage(messages, recallBlock);+ }++ const firstUserIndex = messages.findIndex((msg) => msg.role === "user" && !hasAutoRecallBlock(msg));+ if (firstUserIndex >= 0) {+ return prependRecallAtIndex(messages, firstUserIndex, recallBlock);+ }+return [- ...messages.slice(0, -1),{- ...latest,- content: prependTextToMessageContent(latest.content, recallBlock),+ role: "user",+ content: recallBlock,},+ ...messages,];}@@ -330,6 +414,139 @@ function extractRuntimeSenderId(return { found: false };}+function readStringField(record: Record<string, unknown>, ...keys: string[]): string | undefined {+ for (const key of keys) {+ const value = record[key];+ if (typeof value === "string" && value.trim()) {+ return value.trim();+ }+ }+ return undefined;+}++function safeJsonRecord(text: string): Record<string, unknown> | undefined {+ try {+ const parsed = JSON.parse(text);+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)+ ? parsed as Record<string, unknown>+ : undefined;+ } catch {+ return undefined;+ }+}++function extractJsonFenceAfterLabel(text: string, label: string): Record<string, unknown> | undefined {+ const labelIndex = text.indexOf(label);+ if (labelIndex < 0) {+ return undefined;+ }+ const rest = text.slice(labelIndex + label.length);+ const match = rest.match(/```json\s*([\s\S]*?)\s*```/i);+ if (!match?.[1]) {+ return undefined;+ }+ return safeJsonRecord(match[1]);+}++function uniqueString(values: Array<string | undefined>): string | undefined {+ const unique = new Set(values.map((value) => value?.trim()).filter(Boolean) as string[]);+ return unique.size === 1 ? [...unique][0] : undefined;+}++function extractPromptMetadata(prompt: unknown): PromptMetadata {+ if (typeof prompt !== "string" || !prompt.trim()) {+ return {};+ }++ // Only inspect the OpenClaw-generated metadata preamble before the actual+ // message body. This avoids treating user-authored text as identity data.+ const bodyMarker = prompt.search(/\n?\[message_id:/i);+ const preamble = bodyMarker >= 0 ? prompt.slice(0, bodyMarker) : prompt.slice(0, 3000);+ const conversation = extractJsonFenceAfterLabel(preamble, "Conversation info");+ const sender = extractJsonFenceAfterLabel(preamble, "Sender");++ const senderId = uniqueString([+ conversation ? readStringField(conversation, "sender_id", "senderId") : undefined,+ sender ? readStringField(sender, "id", "sender_id", "senderId") : undefined,+ ]);+ const senderName = uniqueString([+ conversation ? readStringField(conversation, "sender", "sender_name", "senderName") : undefined,+ sender ? readStringField(sender, "name", "label", "username") : undefined,+ ]);++ return { senderId, senderName };+}++function resolveSender(params: {+ runtimeContext?: Record<string, unknown>;+ prompt?: unknown;+}): ResolvedSender {+ const metadata = extractPromptMetadata(params.prompt);+ const runtime = extractRuntimeSenderId(params.runtimeContext);+ if (runtime.found) {+ return { ...runtime, senderName: metadata.senderName, source: "runtimeContext" };+ }++ if (metadata.senderId) {+ return {+ found: true,+ senderId: metadata.senderId,+ senderName: metadata.senderName,+ source: "promptMetadata",+ };+ }++ return {+ found: false,+ senderName: metadata.senderName,+ source: "none",+ };+}++function stripSpeakerPrefix(text: string): string {+ return text.replace(/^[^\n::]{1,80}[::]\s*/, "").trim();+}++function expandShortRecallQuery(text: string, senderName?: string): string {+ return text.length < 5 && senderName+ ? `${senderName} ${text}`+ : text;+}++function extractPromptMessageText(prompt: unknown): string {+ if (typeof prompt !== "string" || !prompt.trim()) {+ return "";+ }+ const matches = [...prompt.matchAll(/\[message_id:[^\]]+\]\s*([\s\S]*?)(?=\n\s*\[System:|\s+\[System:|$)/gi)];+ const raw = matches.at(-1)?.[1]?.trim();+ return raw ? stripSpeakerPrefix(raw) : prompt.trim();+}++function resolveRecallQueryInput(params: {+ latestMessage?: AgentMessage;+ prompt?: unknown;+ senderName?: string;+ preferPrompt?: boolean;+}): RecallQueryInput {+ const promptText = extractPromptMessageText(params.prompt);+ if (params.preferPrompt && promptText) {+ return { text: expandShortRecallQuery(promptText, params.senderName), source: "prompt" };+ }++ if (params.latestMessage?.role === "user") {+ const text = extractAgentMessageText(params.latestMessage);+ if (text.trim()) {+ return { text, source: "latestUserMessage" };+ }+ }++ if (promptText) {+ return { text: expandShortRecallQuery(promptText, params.senderName), source: "prompt" };+ }++ return { text: "", source: "none" };+}+/** OpenClaw session UUID (path-safe on Windows). */const OPENVIKING_OV_SESSION_UUID =/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;@@ -902,6 +1119,7 @@ export function createMemoryOpenVikingContextEngine(params: {const diagEnabled = cfg.emitStandardDiagnostics;const bypassSessionPatterns = compileSessionPatterns(cfg.bypassSessionPatterns);+ const defaultMemoryPolicy = defaultMemoryPolicyForPeerRole(cfg.peer_role);const diag = (stage: string, sessionId: string, data: Record<string, unknown>) =>emitDiag(logger, stage, sessionId, data, diagEnabled);@@ -933,6 +1151,7 @@ export function createMemoryOpenVikingContextEngine(params: {wait: true,agentId,keepRecentCount: 0,+ memoryPolicy: defaultMemoryPolicy,});const memCount = totalExtractedMemories(commitResult.memories_extracted);if (commitResult.status === "failed") {@@ -1070,6 +1289,109 @@ export function createMemoryOpenVikingContextEngine(params: {return { sanitized, archive, session, budgets, instruction };}+ async function buildRecallForAssemble(params: {+ ovSessionId: string;+ agentId: string;+ peerId?: string;+ queryInput: RecallQueryInput;+ client?: OpenVikingClient;+ }): Promise<AssembleRecall> {+ const query = prepareRecallQuery(params.queryInput.text);+ if (!query.query || query.query.length < 5) {+ diag("assemble_recall_skip", params.ovSessionId, {+ reason: "empty_or_short_query",+ querySource: params.queryInput.source,+ queryChars: query.finalChars,+ peerId: params.peerId ?? null,+ });+ return { memoryCount: 0, estimatedTokens: 0, queryChars: query.finalChars };+ }++ if (query.truncated) {+ logger.info(+ `openviking: recall query truncated (` ++ `chars=${query.originalChars}->${query.finalChars})`,+ );+ }++ const recall = await buildAutoRecallContext({+ cfg,+ client: params.client ?? await getClient(),+ agentId: params.agentId,+ peerId: params.peerId,+ queryText: query.query,+ logger,+ verbose: (message) => logger.info(message),+ });+ return { ...recall, queryChars: query.finalChars };+ }++ function recallDiagFields(params: {+ recall: AssembleRecall;+ queryInput: RecallQueryInput;+ peerId?: string;+ sender?: ResolvedSender;+ }): Record<string, unknown> {+ return {+ autoRecallMemoryCount: params.recall.memoryCount,+ autoRecallTokens: params.recall.estimatedTokens,+ querySource: params.queryInput.source,+ queryChars: params.recall.queryChars,+ peerId: params.peerId ?? null,+ ...(params.sender+ ? {+ senderIdFound: params.sender.found,+ senderId: params.sender.senderId ?? null,+ senderSource: params.sender.source,+ }+ : {}),+ };+ }++ function resolveAssembleRecallPeerId(agentId: string, sender: ResolvedSender): string | undefined {+ return resolveSearchPeerId({+ peerRole: cfg.peer_role,+ personPeerId: toPeerId(sender.senderId),+ assistantPeerId: agentId,+ });+ }++ function emptyAssembleRecall(): AssembleRecall {+ return { memoryCount: 0, estimatedTokens: 0, queryChars: 0 };+ }++ function assembleRecallOnlyResult(params: {+ ovSessionId: string;+ reason: string;+ baseMessages: AgentMessage[];+ originalTokens: number;+ recall: AssembleRecall;+ recallBlock: string;+ queryInput: RecallQueryInput;+ peerId?: string;+ sender: ResolvedSender;+ extra?: Record<string, unknown>;+ }): AssembleResult {+ const withRecall = injectRecallIntoContext(params.baseMessages, params.recallBlock);+ const estimatedTokens = roughEstimate(withRecall);+ diag("assemble_result", params.ovSessionId, {+ passthrough: false,+ reason: params.reason,+ ...(params.extra ?? {}),+ outputMessagesCount: withRecall.length,+ inputTokenEstimate: params.originalTokens,+ estimatedTokens,+ ...recallDiagFields({+ recall: params.recall,+ queryInput: params.queryInput,+ peerId: params.peerId,+ sender: params.sender,+ }),+ messages: messageDigest(withRecall),+ });+ return { messages: withRecall, estimatedTokens };+ }+return {info: {id,@@ -1094,7 +1416,10 @@ export function createMemoryOpenVikingContextEngine(params: {const { messages } = assembleParams;const tokenBudget = validTokenBudget(assembleParams.tokenBudget) ?? 128_000;const { sessionKey, ovSessionId: OVSessionId } = resolveSessionIdentity(assembleParams);- const sender = extractRuntimeSenderId(assembleParams.runtimeContext);+ const sender = resolveSender({+ runtimeContext: assembleParams.runtimeContext,+ prompt: assembleParams.prompt,+ });const latestMessage = messages.at(-1);const isMainAssemble =Object.prototype.hasOwnProperty.call(assembleParams, "availableTools") ||@@ -1117,6 +1442,7 @@ export function createMemoryOpenVikingContextEngine(params: {sessionKey: sessionKey ?? null,senderIdFound: sender.found,senderId: sender.senderId ?? null,+ senderSource: sender.source,messages: messageDigest(messages),});@@ -1137,33 +1463,28 @@ export function createMemoryOpenVikingContextEngine(params: {return assemblePassthrough(OVSessionId, "transform_context_recall_already_injected", messages, originalTokens);}- const recallQuery = prepareRecallQuery(extractAgentMessageText(latestMessage));- if (!recallQuery.query || recallQuery.query.length < 5) {+ const recallQueryInput = resolveRecallQueryInput({+ latestMessage,+ senderName: sender.senderName,+ });+ if (recallQueryInput.source === "none") {return assemblePassthrough(OVSessionId, "transform_context_empty_recall_query", messages, originalTokens);}- if (recallQuery.truncated) {- logger.info(- `openviking: recall query truncated (` +- `chars=${recallQuery.originalChars}->${recallQuery.finalChars})`,- );- }try {- const client = await getClient();const routingRef = assembleParams.sessionId ?? sessionKey ?? OVSessionId;const agentId = resolveAgentId(routingRef, sessionKey, OVSessionId);- const recall = await buildAutoRecallContext({- cfg,- client,+ const peerId = resolveAssembleRecallPeerId(agentId, sender);+ const recall = await buildRecallForAssemble({+ ovSessionId: OVSessionId,agentId,- queryText: recallQuery.query,- logger,- verbose: (message) => logger.info(message),+ peerId,+ queryInput: recallQueryInput,});if (!recall.block) {return assemblePassthrough(OVSessionId, "transform_context_no_recall_hits", messages, originalTokens, {- memoryCount: recall.memoryCount,+ ...recallDiagFields({ recall, queryInput: recallQueryInput, peerId }),});}@@ -1175,8 +1496,7 @@ export function createMemoryOpenVikingContextEngine(params: {outputMessagesCount: withRecall.length,inputTokenEstimate: originalTokens,estimatedTokens,- autoRecallMemoryCount: recall.memoryCount,- autoRecallTokens: recall.estimatedTokens,+ ...recallDiagFields({ recall, queryInput: recallQueryInput, peerId, sender }),messages: messageDigest(withRecall),});return { messages: withRecall, estimatedTokens };@@ -1192,13 +1512,74 @@ export function createMemoryOpenVikingContextEngine(params: {const client = await getClient();const routingRef = assembleParams.sessionId ?? sessionKey ?? OVSessionId;const agentId = resolveAgentId(routingRef, sessionKey, OVSessionId);- const ctx = await client.getSessionContext(OVSessionId, tokenBudget, agentId);+ const peerId = resolveAssembleRecallPeerId(agentId, sender);+ const recallQueryInput = resolveRecallQueryInput({+ latestMessage,+ prompt: assembleParams.prompt,+ senderName: sender.senderName,+ preferPrompt: true,+ });+ const hasInjectedRecall = messages.some((message) => hasAutoRecallBlock(message));+ let recall = emptyAssembleRecall();+ if (cfg.autoRecall && !hasInjectedRecall) {+ try {+ recall = await buildRecallForAssemble({+ ovSessionId: OVSessionId,+ agentId,+ peerId,+ queryInput: recallQueryInput,+ client,+ });+ } catch (recallErr) {+ logger.warn?.(`openviking: auto-recall failed: ${String(recallErr)}`);+ diag("assemble_recall_failed", OVSessionId, {+ error: String(recallErr),+ querySource: recallQueryInput.source,+ peerId: peerId ?? null,+ senderSource: sender.source,+ });+ }+ }+ let ctx;+ try {+ ctx = await client.getSessionContext(OVSessionId, tokenBudget, agentId);+ } catch (ctxErr) {+ if (recall.block) {+ return assembleRecallOnlyResult({+ ovSessionId: OVSessionId,+ reason: "recall_only_context_unavailable",+ baseMessages: messages,+ originalTokens,+ recall,+ recallBlock: recall.block,+ queryInput: recallQueryInput,+ peerId,+ sender,+ extra: { contextError: String(ctxErr) },+ });+ }+ throw ctxErr;+ }const preAbstracts = ctx?.pre_archive_abstracts ?? [];const hasArchives = !!ctx?.latest_archive_overview || preAbstracts.length > 0;const activeCount = ctx?.messages?.length ?? 0;if (!ctx || (!hasArchives && activeCount === 0)) {+ if (recall.block) {+ return assembleRecallOnlyResult({+ ovSessionId: OVSessionId,+ reason: "recall_only_no_ov_data",+ baseMessages: messages,+ originalTokens,+ recall,+ recallBlock: recall.block,+ queryInput: recallQueryInput,+ peerId,+ sender,+ extra: { archiveCount: 0, activeCount: 0 },+ });+ }return assemblePassthrough(OVSessionId, "no_ov_data", messages, originalTokens, {archiveCount: 0, activeCount: 0,});@@ -1223,7 +1604,10 @@ export function createMemoryOpenVikingContextEngine(params: {});}- const assembledTokens = roughEstimate(sanitized) + instruction.tokens;+ const outputMessages = recall.block+ ? injectRecallIntoContext(sanitized, recall.block)+ : sanitized;+ const assembledTokens = roughEstimate(outputMessages) + instruction.tokens;const tokensSaved = originalTokens - assembledTokens;const savingPct = originalTokens > 0 ? Math.round((tokensSaved / originalTokens) * 100) : 0;@@ -1231,7 +1615,7 @@ export function createMemoryOpenVikingContextEngine(params: {passthrough: false,archiveCount: preAbstracts.length,activeCount,- outputMessagesCount: sanitized.length,+ outputMessagesCount: outputMessages.length,inputTokenEstimate: originalTokens,estimatedTokens: assembledTokens,tokensSaved,@@ -1241,13 +1625,12 @@ export function createMemoryOpenVikingContextEngine(params: {sessionTokens: session.tokens,sessionBudget: budgets.sessionContext,reservedBudget: budgets.reserved,- senderIdFound: sender.found,- senderId: sender.senderId ?? null,- messages: messageDigest(sanitized),+ ...recallDiagFields({ recall, queryInput: recallQueryInput, peerId, sender }),+ messages: messageDigest(outputMessages),});return {- messages: sanitized,+ messages: outputMessages,estimatedTokens: assembledTokens,...(instruction.text ? { systemPromptAddition: instruction.text } : {}),};@@ -1262,6 +1645,7 @@ export function createMemoryOpenVikingContextEngine(params: {agentId: resolveAgentId(OVSessionId),senderIdFound: sender.found,senderId: sender.senderId ?? null,+ senderSource: sender.source,});return { messages, estimatedTokens: roughEstimate(messages) };}@@ -1353,7 +1737,14 @@ export function createMemoryOpenVikingContextEngine(params: {const client = await getClient();const createdAt = pickLatestCreatedAt(turnMessages);- const senderRoleId = toRoleId(sender.senderId);+ const senderPeerId = toPeerId(sender.senderId);+ if (defaultMemoryPolicy) {+ await client.ensureSession(+ OVSessionId,+ { memoryPolicy: defaultMemoryPolicy },+ agentId,+ );+ }// 发送结构化消息:统一 role 为 user,通过 parts 区分类型for (const msg of extractedMessages) {const ovParts = msg.parts.map((part) => {@@ -1377,13 +1768,19 @@ export function createMemoryOpenVikingContextEngine(params: {});if (ovParts.length > 0) {+ const peerId = resolveMessagePeerId({+ peerRole: cfg.peer_role,+ role: msg.role,+ personPeerId: senderPeerId,+ assistantPeerId: agentId,+ });await client.addSessionMessage(OVSessionId,- msg.role, // 统一是 "user"+ msg.role,ovParts,agentId,createdAt,- msg.role === "user" ? senderRoleId : undefined,+ peerId,);}}@@ -1406,6 +1803,7 @@ export function createMemoryOpenVikingContextEngine(params: {wait: false,agentId,keepRecentCount: cfg.commitKeepRecentCount,+ memoryPolicy: defaultMemoryPolicy,});logger.info(`openviking: committed session=${OVSessionId}, ` +@@ -1503,6 +1901,7 @@ export function createMemoryOpenVikingContextEngine(params: {wait: true,agentId,keepRecentCount: 0,+ memoryPolicy: defaultMemoryPolicy,});const memCount = totalExtractedMemories(commitResult.memories_extracted);diff --git a/examples/openclaw-plugin/docs/oc-resource-skill-import-design.md b/examples/openclaw-plugin/docs/oc-resource-skill-import-design.mdindex e469e7e89..05b4f61a8 100644--- a/examples/openclaw-plugin/docs/oc-resource-skill-import-design.md+++ b/examples/openclaw-plugin/docs/oc-resource-skill-import-design.md@@ -9,7 +9,7 @@随着 OpenViking 的 resource 和 skill 能力完善,OpenClaw 侧也需要一个自然入口,让用户可以在 OpenClaw 对话或显式命令中把外部资料导入到 OpenViking:- Resource:项目文档、代码仓库、网页、PDF、Markdown、本地目录等,落到 `viking://resources/...`-- Skill:`SKILL.md`、skill 目录、raw skill 内容或 MCP tool dict,落到 `viking://agent/skills/...`+- Skill:`SKILL.md`、skill 目录、raw skill 内容或 MCP tool dict,落到 `viking://user/skills/...`本 RFC 讨论 OpenClaw plugin 侧的导入入口、HTTP 对接方式、安全边界和测试方案。@@ -60,7 +60,7 @@ OpenViking 当前已经有独立的 skill 导入链路:- HTTP API:`POST /api/v1/skills`- Service 层:`ResourceService.add_skill(...)`- Processor:`SkillProcessor.process_skill(...)`-- 存储位置:`viking://agent/skills/{skill_name}`+- 存储位置:`viking://user/skills/{skill_name}`支持的输入形态包括:@@ -306,9 +306,9 @@ Try: /ov-search "OpenViking install" --uri viking://resources/openviking-readme`add_skill` 导入 skill 后也应返回 skill URI,并给出 skill 检索建议:```text-Imported OpenViking skill: viking://agent/skills/install-openviking-memory+Imported OpenViking skill: viking://user/skills/install-openviking-memoryProcessing: completed-Try: /ov-search "<query>" --uri viking://agent/skills+Try: /ov-search "<query>" --uri viking://user/skills```#### ov_search 参数设计@@ -328,7 +328,7 @@ v1 建议保持简洁:```text/ov-search "OpenViking install" --uri viking://resources/openviking-readme/ov-search "API usage" --uri viking://resources-/ov-search "<query>" --uri viking://agent/skills+/ov-search "<query>" --uri viking://user/skills```对应 LLM tool 示例:@@ -398,7 +398,7 @@ Resourcesscore: 0.76Skills-1. viking://agent/skills/install-openviking-memory+1. viking://user/skills/install-openviking-memoryInstall and operate OpenViking memory integration...score: 0.69```@@ -435,7 +435,7 @@ Skillsskills: [{context_type: "skill",- uri: "viking://agent/skills/install-openviking-memory",+ uri: "viking://user/skills/install-openviking-memory",level: 0,score: 0.69,category: "",@@ -482,7 +482,7 @@ v1 建议只返回检索结果摘要和 URI,不直接返回完整文件内容`memory_recall` 当前偏向长期记忆,不适合作为 resource/skill 导入后的默认消费入口。`ov_search` v1 应检索:```ts-uris = ["viking://resources", "viking://agent/skills"]+uris = ["viking://resources", "viking://user/skills"]```后续如果希望统一上下文检索 memory/resource/skill,可扩展:@@ -535,7 +535,7 @@ v1 暂不加入,避免把导入 RFC 扩展成完整 OpenViking CLI replica。- 注册单个 tool:`ov_search`- 注册单个 command:`/ov-search`-- 未指定 `uri` 时默认检索 `viking://resources` 和 `viking://agent/skills`+- 未指定 `uri` 时默认检索 `viking://resources` 和 `viking://user/skills`- 指定 `--uri` 时只检索该范围- OpenViking error response 透传为可读错误- 查询为空时返回 usage error@@ -546,7 +546,7 @@ v1 暂不加入,避免把导入 RFC 扩展成完整 OpenViking CLI replica。/add-resource ./README.md --to viking://resources/openviking-readme --wait/ov-search "OpenViking install" --uri viking://resources/openviking-readme/add-skill ./skills/install-openviking-memory --wait-/ov-search "install OpenViking memory" --uri viking://agent/skills+/ov-search "install OpenViking memory" --uri viking://user/skills```以及自然语言触发:@@ -570,7 +570,7 @@ v1 暂不加入,避免把导入 RFC 扩展成完整 OpenViking CLI replica。- 当前建议先使用显式 `/add-skill`,避免在 `/add-resource` 中自动猜测并改变用户意图。4. 导入本地大目录前是否需要确认机制?- 当前方案先不加确认;后续可基于文件数量/zip 大小增加保护。-5. `ov_search` v1 是否默认检索 `viking://resources` 和 `viking://agent/skills`?+5. `ov_search` v1 是否默认检索 `viking://resources` 和 `viking://user/skills`?- 当前建议是。memory 仍交给既有 `memory_recall`,避免职责重叠。6. 是否需要在 v1 同时提供 `/ov-read` 或 `/ov-tree`?- 当前建议不加,先用 `ov_search` 完成导入后的最小消费闭环。diff --git a/examples/openclaw-plugin/health_check_tools/HEALTHCHECK-ZH.md b/examples/openclaw-plugin/health_check_tools/HEALTHCHECK-ZH.mdindex 35f814445..c46a35920 100644--- a/examples/openclaw-plugin/health_check_tools/HEALTHCHECK-ZH.md+++ b/examples/openclaw-plugin/health_check_tools/HEALTHCHECK-ZH.md@@ -136,7 +136,6 @@ Phase 3 会等待异步 commit 完成(默认最多 300 秒)。这是正常| `--openviking <url>` | 自动 | OpenViking 地址 || `--token <token>` | 自动 | Gateway bearer token || `--openviking-api-key <key>` | 自动 | OpenViking API key |-| `--agent-id <id>` | `default` | OpenViking agent id || `--user-id <id>` | 随机 | 测试会话的 user id || `--openclaw-config <path>` | 自动 | `openclaw.json` 路径 || `--chat-timeout <秒>` | `120` | 每次 Gateway 聊天请求的超时 |diff --git a/examples/openclaw-plugin/health_check_tools/HEALTHCHECK.md b/examples/openclaw-plugin/health_check_tools/HEALTHCHECK.mdindex 493afb493..824a142a1 100644--- a/examples/openclaw-plugin/health_check_tools/HEALTHCHECK.md+++ b/examples/openclaw-plugin/health_check_tools/HEALTHCHECK.md@@ -136,7 +136,6 @@ This confirms the full async pipeline: conversation archiving, overview generati| `--openviking <url>` | auto | OpenViking base URL || `--token <token>` | auto | Gateway bearer token || `--openviking-api-key <key>` | auto | OpenViking API key |-| `--agent-id <id>` | `default` | OpenViking agent id || `--user-id <id>` | random | User id for the test session || `--openclaw-config <path>` | auto | Path to `openclaw.json` || `--chat-timeout <seconds>` | `120` | Timeout per Gateway chat request |diff --git a/examples/openclaw-plugin/health_check_tools/ov-healthcheck.py b/examples/openclaw-plugin/health_check_tools/ov-healthcheck.pyindex c686af1b8..06307ea02 100644--- a/examples/openclaw-plugin/health_check_tools/ov-healthcheck.py+++ b/examples/openclaw-plugin/health_check_tools/ov-healthcheck.py@@ -17,7 +17,6 @@ from typing import AnyDEFAULT_GATEWAY_URL = "http://127.0.0.1:19789"DEFAULT_OPENVIKING_URL = "http://127.0.0.1:1933"-DEFAULT_AGENT_ID = "default"DEFAULT_SESSION_SCAN_LIMIT = 0META_FILE_SUFFIXES = (".abstract.md", ".overview.md")@@ -196,9 +195,6 @@ def parse_args() -> argparse.Namespace:default="",help="OpenViking API key. Auto-discovered from plugin config when possible.",)- parser.add_argument(- "--agent-id", default="", help=f"OpenViking agent id (default: {DEFAULT_AGENT_ID})"- )parser.add_argument("--user-id", default="", help="User id for the real conversation session.")parser.add_argument("--openclaw-config",@@ -661,20 +657,15 @@ def wait_for_commit_visibility(class OpenVikingInspector:- def __init__(- self, base_url: str, api_key: str, agent_id: str, *, insecure: bool = False- ) -> None:+ def __init__(self, base_url: str, api_key: str, *, insecure: bool = False) -> None:self.base_url = base_url.rstrip("/")self.api_key = api_key- self.agent_id = agent_id or DEFAULT_AGENT_IDself.insecure = insecuredef headers(self) -> dict[str, str]:headers: dict[str, str] = {}if self.api_key:headers["X-API-Key"] = self.api_key- if self.agent_id:- headers["X-OpenViking-Agent"] = self.agent_idreturn headersdef health(self) -> bool:@@ -1136,7 +1127,6 @@ def main() -> int:)or str(os.environ.get("OPENVIKING_API_KEY", "")).strip())- agent_id = args.agent_id or str(plugin_config.get("agent_prefix", "")).strip() or DEFAULT_AGENT_IDuser_id = args.user_id or f"ov-healthcheck-{uuid.uuid4().hex[:8]}"probe = f"probe-{uuid.uuid4().hex[:8]}"run_facts = build_run_facts(probe)@@ -1205,9 +1195,7 @@ def main() -> int:else:recorder.add("WARN", "Gateway token not found", "continuing without Authorization header")- inspector = OpenVikingInspector(- openviking_url, openviking_api_key, agent_id, insecure=args.insecure- )+ inspector = OpenVikingInspector(openviking_url, openviking_api_key, insecure=args.insecure)try:sessions_before_probe = collect_session_ids(inspector.list_sessions())except Exception:diff --git a/examples/openclaw-plugin/index.ts b/examples/openclaw-plugin/index.tsindex 4b88e80a6..dc09dd4ba 100644--- a/examples/openclaw-plugin/index.ts+++ b/examples/openclaw-plugin/index.ts@@ -13,7 +13,13 @@ import type {CommitSessionResult,OVMessage,} from "./client.js";-import { formatMessageFaithful, toRoleId } from "./context-engine.js";+import {+ defaultMemoryPolicyForPeerRole,+ formatMessageFaithful,+ resolveMessagePeerId,+ resolveSearchPeerId,+ toPeerId,+} from "./context-engine.js";import {compileSessionPatterns,shouldBypassSession,@@ -225,11 +231,10 @@ type OpenClawPluginApi = {const DEFAULT_OPENCLAW_AGENT_ID = "main";/**- * OpenViking `UserIdentifier` allows only [a-zA-Z0-9_-] for agent_id- * (see openviking_cli/session/user_id.py). OpenClaw ids may contain ":"- * (e.g. session keys); never send raw colons in X-OpenViking-Agent.+ * OpenClaw ids may contain ":" (e.g. session keys), while OpenViking+ * peer/session metadata is path-friendly.*/-export function sanitizeOpenVikingAgentIdHeader(raw: string): string {+export function sanitizeRuntimeAgentId(raw: string): string {const trimmed = raw.trim();if (!trimmed) {return "default";@@ -491,7 +496,7 @@ export function createSessionAgentResolver(configAgentId: string) {const prefix = configAgentPrefix;const resolvedBeforeSanitize = prefix ? `${prefix}_${rawAgentId}` : rawAgentId;- const resolved = sanitizeOpenVikingAgentIdHeader(resolvedBeforeSanitize);+ const resolved = sanitizeRuntimeAgentId(resolvedBeforeSanitize);for (const alias of collectSessionAgentAliases(ctx.sessionId, ctx.sessionKey, ctx.ovSessionId)) {sessionAgentIds.set(alias, resolved);}@@ -520,7 +525,7 @@ export function createSessionAgentResolver(configAgentId: string) {branch = "session_resolved";} else if (sessionScopedAgentId) {resolvedBeforeSanitize = prefix ? `${prefix}_${sessionScopedAgentId}` : sessionScopedAgentId;- resolved = sanitizeOpenVikingAgentIdHeader(resolvedBeforeSanitize);+ resolved = sanitizeRuntimeAgentId(resolvedBeforeSanitize);branch = "session_resolved";} else if (!prefix) {resolvedBeforeSanitize = DEFAULT_OPENCLAW_AGENT_ID;@@ -528,7 +533,7 @@ export function createSessionAgentResolver(configAgentId: string) {branch = "default_no_session";} else {resolvedBeforeSanitize = `${prefix}_${DEFAULT_OPENCLAW_AGENT_ID}`;- resolved = sanitizeOpenVikingAgentIdHeader(resolvedBeforeSanitize);+ resolved = sanitizeRuntimeAgentId(resolvedBeforeSanitize);branch = "config_only_fallback";}@@ -592,7 +597,7 @@ const contextEnginePlugin = {}const bypassSessionPatterns = compileSessionPatterns(cfg.bypassSessionPatterns);- const rawAgentId = rawCfg.agent_prefix;+ const rawPeerPrefix = rawCfg.peer_prefix;if (cfg.logFindRequests) {api.logger.info("openviking: routing debug logging enabled (config logFindRequests, or env OPENVIKING_LOG_ROUTING=1 / OPENVIKING_DEBUG=1)",@@ -604,27 +609,20 @@ const contextEnginePlugin = {}};verboseRoutingInfo(- `openviking: loaded plugin config agent_prefix="${cfg.agent_prefix}" ` +- `(raw plugins.entries.openviking.config.agent_prefix=${JSON.stringify(rawAgentId ?? "(missing)")}; ` ++ `openviking: loaded plugin config peer_role="${cfg.peer_role}" peer_prefix="${cfg.peer_prefix}" ` ++ `(raw peer_prefix=${JSON.stringify(rawPeerPrefix ?? "(missing)")}; ` +`${- cfg.agent_prefix- ? 'non-empty → X-OpenViking-Agent is <agent_prefix>_<ctx.agentId> when hooks expose session agent, or <agent_prefix>_main when ctx.agentId is unknown'- : 'empty → X-OpenViking-Agent follows OpenClaw ctx.agentId per session, or "main" when ctx.agentId is unknown'+ cfg.peer_prefix+ ? 'non-empty → assistant peer_id is <peer_prefix>_<ctx.agentId> when peer_role="assistant", or <peer_prefix>_main when ctx.agentId is unknown'+ : 'empty → assistant peer_id follows OpenClaw ctx.agentId when peer_role="assistant", or "main" when ctx.agentId is unknown'})`,);- verboseRoutingInfo(- `openviking: auth/namespace config ` +- JSON.stringify({- isolateUserScopeByAgent: cfg.isolateUserScopeByAgent,- isolateAgentScopeByUser: cfg.isolateAgentScopeByUser,- deprecatedAgentScopeMode: cfg.agentScopeMode,- }),- );const routingDebugLog = cfg.logFindRequests? (msg: string) => {api.logger.info(msg);}: undefined;+ const defaultMemoryPolicy = defaultMemoryPolicyForPeerRole(cfg.peer_role);const tenantAccount = cfg.accountId;const tenantUser = cfg.userId;@@ -632,13 +630,11 @@ const contextEnginePlugin = {new OpenVikingClient(cfg.baseUrl,cfg.apiKey,- cfg.agent_prefix,+ cfg.peer_prefix,cfg.timeoutMs,tenantAccount,tenantUser,routingDebugLog,- cfg.isolateUserScopeByAgent,- cfg.isolateAgentScopeByUser,),);@@ -691,6 +687,16 @@ const contextEnginePlugin = {};};+ const resolveToolSearchPeerId = (+ ctx: unknown,+ session: PluginSessionRouting,+ ): string | undefined =>+ resolveSearchPeerId({+ peerRole: cfg.peer_role,+ personPeerId: toPeerId(extractToolSenderId(ctx)),+ assistantPeerId: session.agentId,+ });+const formatResourceImportText = (result: AddResourceResult): string => {const root = result.root_uri ? ` ${result.root_uri}` : "";const warnings = result.warnings?.length ? ` Warnings: ${result.warnings.join("; ")}` : "";@@ -822,7 +828,11 @@ const contextEnginePlugin = {return lines.join("\n");};- const searchOpenViking = async (input: OVSearchInput, agentId?: string) => {+ const searchOpenViking = async (+ input: OVSearchInput,+ agentId?: string,+ peerId?: string,+ ) => {const query = input.query.trim();if (!query) {throw new Error("query is required");@@ -831,11 +841,11 @@ const contextEnginePlugin = {const client = await getClient();let result: FindResult;if (input.uri) {- result = await client.find(query, { targetUri: input.uri, limit }, agentId);+ result = await client.find(query, { targetUri: input.uri, limit, peerId }, agentId);} else {const [resourcesSettled, skillsSettled] = await Promise.allSettled([- client.find(query, { targetUri: "viking://resources", limit }, agentId),- client.find(query, { targetUri: "viking://agent/skills", limit }, agentId),+ client.find(query, { targetUri: "viking://resources", limit, peerId }, agentId),+ client.find(query, { targetUri: "viking://user/skills", limit, peerId }, agentId),]);const successful: FindResult[] = [];if (resourcesSettled.status === "fulfilled") {@@ -867,6 +877,7 @@ const contextEnginePlugin = {action: "searched",query,uri: input.uri,+ peer_id: peerId ?? null,memories: result.memories ?? [],resources: result.resources ?? [],skills: result.skills ?? [],@@ -947,7 +958,7 @@ const contextEnginePlugin = {"Search OpenViking resources and skills. Use after importing, or when the user asks to search OpenViking resources or skills.",parameters: Type.Object({query: Type.String({ description: "Search query" }),- uri: Type.Optional(Type.String({ description: "Optional search URI. Defaults to resources plus agent skills." })),+ uri: Type.Optional(Type.String({ description: "Optional search URI. Defaults to resources plus user skills." })),limit: Type.Optional(Type.Number({ description: "Max results per search scope. Default: 10" })),}),async execute(_toolCallId: string, params: Record<string, unknown>) {@@ -955,11 +966,12 @@ const contextEnginePlugin = {return makeBypassedToolResult("ov_search");}const session = resolvePluginSessionRouting(ctx);+ const peerId = resolveToolSearchPeerId(ctx, session);return searchOpenViking({query: String((params as { query?: unknown }).query ?? ""),uri: typeof params.uri === "string" ? params.uri : undefined,limit: typeof params.limit === "number" ? params.limit : undefined,- }, session.agentId);+ }, session.agentId, peerId);},}),{ name: "ov_search" },@@ -1017,7 +1029,8 @@ const contextEnginePlugin = {}const session = resolvePluginSessionRouting(ctx);const input = parseOVSearchCommandArgs(ctx.args ?? "");- const result = await searchOpenViking(input, session.agentId);+ const peerId = resolveToolSearchPeerId(ctx, session);+ const result = await searchOpenViking(input, session.agentId, peerId);return { text: result.content[0]!.text, details: result.details };} catch (err) {return { text: `OpenViking search failed: ${err instanceof Error ? err.message : String(err)}` };@@ -1048,6 +1061,7 @@ const contextEnginePlugin = {return makeBypassedToolResult("memory_recall");}const session = resolvePluginSessionRouting(ctx);+ const peerId = resolveToolSearchPeerId(ctx, session);const { query } = params as { query: string };const limit =typeof (params as { limit?: number }).limit === "number"@@ -1066,7 +1080,8 @@ const contextEnginePlugin = {const recallClient = await getClient();if (cfg.logFindRequests) {api.logger.info(- `openviking: memory_recall X-OpenViking-Agent="${session.agentId}" ` ++ `openviking: memory_recall runtime_agent_id="${session.agentId}" ` ++ `peer_id="${peerId ?? ""}" ` +`(plugin defaultAgentId="${recallClient.getDefaultAgentId()}" is unused when session context is present)`,);}@@ -1080,6 +1095,7 @@ const contextEnginePlugin = {targetUri,limit: requestLimit,scoreThreshold: 0,+ peerId,},session.agentId,);@@ -1091,15 +1107,17 @@ const contextEnginePlugin = {targetUri: "viking://user/memories",limit: requestLimit,scoreThreshold: 0,+ peerId,},session.agentId,),recallClient.find(query,{- targetUri: "viking://agent/memories",+ targetUri: "viking://user/memories",limit: requestLimit,scoreThreshold: 0,+ peerId,},session.agentId,),@@ -1112,6 +1130,7 @@ const contextEnginePlugin = {targetUri: "viking://resources",limit: requestLimit,scoreThreshold: 0,+ peerId,},session.agentId,),@@ -1234,19 +1253,32 @@ const contextEnginePlugin = {sessionId = `memory-store-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;usedTempSession = true;}- const roleId = role === "user" ? toRoleId(extractToolSenderId(ctx)) : undefined;+ const peerId = resolveMessagePeerId({+ peerRole: cfg.peer_role,+ role,+ personPeerId: toPeerId(extractToolSenderId(ctx)),+ assistantPeerId: session.agentId,+ });+ if (defaultMemoryPolicy) {+ await c.ensureSession(+ sessionId,+ { memoryPolicy: defaultMemoryPolicy },+ session.agentId,+ );+ }await c.addSessionMessage(sessionId,role,[{ type: "text" as const, text }],session.agentId,undefined,- roleId,+ peerId,);const commitResult = await c.commitSession(sessionId, {wait: true,agentId: session.agentId,keepRecentCount: 0,+ memoryPolicy: defaultMemoryPolicy,});const memoriesCount = totalCommitMemories(commitResult);if (commitResult.status === "failed") {@@ -1353,6 +1385,7 @@ const contextEnginePlugin = {return makeBypassedToolResult("memory_forget");}const session = resolvePluginSessionRouting(ctx);+ const peerId = resolveToolSearchPeerId(ctx, session);const client = await getClient();const uri = (params as { uri?: string }).uri;if (uri) {@@ -1397,6 +1430,7 @@ const contextEnginePlugin = {targetUri,limit: requestLimit,scoreThreshold: 0,+ peerId,},session.agentId,);@@ -1903,7 +1937,7 @@ const contextEnginePlugin = {);let contextEngineRef: ContextEngineWithCommit | null = null;- const sessionAgentResolver = createSessionAgentResolver(cfg.agent_prefix);+ const sessionAgentResolver = createSessionAgentResolver(cfg.peer_prefix);const rememberSessionAgentId = (ctx: SessionAgentLookup) => {sessionAgentResolver.remember(ctx);};@@ -1922,7 +1956,8 @@ const contextEnginePlugin = {sessionId: sid || "(empty)",sessionKey: sk || "(empty)",ovSessionId: ovSid || "(empty)",- parsedConfigAgentPrefix: cfg.agent_prefix,+ parsedConfigPeerPrefix: cfg.peer_prefix,+ peerRole: cfg.peer_role,mappedResolvedAgentId: result.mappedResolvedAgentId,resolvedBeforeSanitize: result.resolvedBeforeSanitize,resolved: result.resolved,diff --git a/examples/openclaw-plugin/openclaw-multi-tenant-test-report.md b/examples/openclaw-plugin/openclaw-multi-tenant-test-report.mdindex 8229237de..8c10e5913 100644--- a/examples/openclaw-plugin/openclaw-multi-tenant-test-report.md+++ b/examples/openclaw-plugin/openclaw-multi-tenant-test-report.md@@ -5,10 +5,10 @@本轮测试围绕 `examples/openclaw-plugin` 的多租户与会话身份透传能力展开,重点验证以下目标:1. 验证插件在 `api_key` 与 `trusted` 两种服务认证模式下的请求头行为是否正确。-2. 验证插件是否按照服务侧命名空间策略,将 `viking://user/memories` 与 `viking://agent/memories` 正确展开为 canonical URI。-3. 验证 `senderId` / `requesterSenderId` 是否能够稳定映射为会话消息的 `role_id`。+2. 验证插件是否按照服务侧命名空间策略,将 `viking://user/memories` 与 `viking://user/memories` 正确展开为 canonical URI。+3. 验证 `senderId` / `requesterSenderId` 是否能够稳定映射为会话消息的 `peer_id`。4. 验证 `afterTurn` 与 `memory_store` 两条写会话路径的身份语义是否一致。-5. 验证多租户场景下默认用户空间、按 agent 隔离空间、共享 agent 空间等路径的召回行为是否符合预期。+5. 验证多租户场景下用户空间、共享资源与 peer/session metadata 的召回行为是否符合预期。## 2. 测试方法@@ -19,17 +19,16 @@- 使用 `curl` 调用 `/health`、`/api/v1/system/status`、`/api/v1/search/find`- 直接验证显式 URI,例如:- `viking://user/default/memories`- - `viking://user/default/agent/main/memories`- - `viking://agent/main/memories`- - `viking://agent/main/user/default/memories`+ - `viking://user/default/skills`+ - `viking://resources`- 通过结构化 seed 与分层 `reindex`,确保召回验证基线可用### 2.2 插件端到端验证通过真实 OpenClaw gateway 与 OpenViking 后端联调验证:-- 远端 `19950`:用于 `api_key` 模式与命名空间矩阵验证-- 远端 `19960`:用于 `trusted` 模式与 `role_id` 验证+- 远端 `19950`:用于 `api_key` 模式与用户空间验证+- 远端 `19960`:用于 `trusted` 模式与 `peer_id` 验证- 使用真实 Feishu 机器人入口验证真实 sender 映射- 结合以下日志进行判定:- `before_prompt_build`@@ -39,11 +38,11 @@### 2.3 真实机器人验证-针对 `role_id` 透传行为,使用真实机器人私聊/群聊场景复核:+针对 `peer_id` 透传行为,使用真实机器人私聊/群聊场景复核:-- 私聊验证真实 sender 到 `role_id` 的稳定映射-- 群聊验证不同成员写入不同 `role_id`-- 工具调用验证 `memory_store` 路径是否能通过 `requesterSenderId` 写出 `role_id`+- 私聊验证真实 sender 到 `peer_id` 的稳定映射+- 群聊验证不同成员写入不同 `peer_id`+- 工具调用验证 `memory_store` 路径是否能通过 `requesterSenderId` 写出 `peer_id`## 3. 测试范围@@ -55,18 +54,15 @@### 3.2 命名空间策略-- `ff`:user 不按 agent 隔离,agent 不按 user 隔离-- `tf`:user 按 agent 隔离,agent 不按 user 隔离-- `tt`:user 按 agent 隔离,agent 按 user 隔离-- 兼容路径:- - `agentScopeMode=agent`- - 新 policy 覆盖旧 alias+- user-scoped memory:`viking://user/<user_id>/memories`+- user-scoped skills:`viking://user/<user_id>/skills`+- shared resources:`viking://resources`### 3.3 身份透传-- `afterTurn.runtimeContext.senderId -> role_id`-- `memory_store.requesterSenderId -> role_id`-- assistant message 不传 `role_id`+- `afterTurn.runtimeContext.senderId -> peer_id`+- `memory_store.requesterSenderId -> peer_id`+- assistant message 不传 `peer_id`## 4. 测试结果@@ -76,44 +72,39 @@|---|---|---|---|| `api_key` | `api_key_without_key_dev` | 通过 | 不再合成 `default/default` 租户 header || `api_key` | `personal_token_default` | 通过 | 命中 `DEFAULT_USER_TOKEN_19950` |-| `api_key` | `agentid_prefix_worker` | 通过 | 实际 agent 值为 `worker_main` |-| 兼容 | `deprecated_agent_alias` | 通过 | `agentScopeMode=agent` 兼容正常 |-| 覆盖优先级 | `new_policy_overrides_deprecated` | 通过 | 新 policy 覆盖旧 alias |-| namespace | `ff_user_token` | 通过 | user 共享空间命中正确 |-| namespace | `ff_agent_token` | 通过 | agent 共享空间命中正确 |-| namespace | `tf_user_token` | 通过 | user 按 agent 隔离命中正确 |-| namespace | `tf_agent_token` | 通过 | agent 共享空间命中正确 |-| namespace | `tt_user_token` | 通过 | user/agent 双隔离命中正确 |-| namespace | `tt_agent_token` | 通过 | agent/user 双隔离命中正确 |+| `api_key` | `runtime_peer_worker` | 通过 | runtime agent 只参与 peer/session metadata |+| namespace | `user_memory_token` | 通过 | user memory 空间命中正确 |+| namespace | `user_skill_token` | 通过 | user skill 空间命中正确 |+| namespace | `resource_token` | 通过 | shared resource 空间命中正确 || `trusted` | `trusted_without_key` | 通过 | 无 key trusted 路径正常 || `trusted` | `trusted_with_key` | 通过 | 带 key trusted 路径正常 || `trusted` | `trusted_root_key_required` | 通过 | 不带 key 被服务侧拒绝 || `trusted` | `trusted_root_key_optional_ok` | 通过 | 带 root key 正常 |-| `senderId -> role_id` | `senderid_trusted_user_msg` | 通过 | `telegram:12345 -> telegram_12345` |-| `senderId -> role_id` | `senderid_trusted_blank` | 通过 | `role_id:null` |-| `senderId -> role_id` | `senderid_sanitize_symbols` | 通过 | `wx/user-01@abc -> wx_user-01_abc` |-| 真实机器人 | 私聊 sender 映射 | 通过 | sender 稳定映射到真实 `role_id` |-| 真实机器人 | 群聊多成员 `role_id` | 通过 | 不同成员落不同 `role_id` |-| `memory_store` | `requesterSenderId -> role_id` | 通过 | `memory_store` 已使用 `requesterSenderId` 写出真实 `role_id` |+| `senderId -> peer_id` | `senderid_trusted_user_msg` | 通过 | `telegram:12345 -> telegram_12345` |+| `senderId -> peer_id` | `senderid_trusted_blank` | 通过 | `peer_id:null` |+| `senderId -> peer_id` | `senderid_sanitize_symbols` | 通过 | `wx/user-01@abc -> wx_user-01_abc` |+| 真实机器人 | 私聊 sender 映射 | 通过 | sender 稳定映射到真实 `peer_id` |+| 真实机器人 | 群聊多成员 `peer_id` | 通过 | 不同成员落不同 `peer_id` |+| `memory_store` | `requesterSenderId -> peer_id` | 通过 | `memory_store` 已使用 `requesterSenderId` 写出真实 `peer_id` |### 4.2 已知说明| 项目 | 状态 | 说明 ||---|---|---|-| `agent_token_main_default` | 已打通 | 曾出现一次回答少 `_19950`,属于回答精度问题,不是链路问题 |+| `user_token_main_default` | 已打通 | 曾出现一次回答少 `_19950`,属于回答精度问题,不是链路问题 || 真实机器人最终回复 | 非插件问题 | 群聊/私聊中出现的 `Something went wrong...` 已定位在 OpenClaw 工具结果回填阶段,与 OpenViking 插件链路无关 |## 5. 关键结论-1. 插件侧 canonical namespace policy、显式租户 header 与 `role_id` 透传能力已完成联调验证。-2. `afterTurn` 路径可通过 `runtimeContext.senderId` 正确写出 `role_id`。-3. `memory_store` 路径在工具上下文中无法直接读取 `senderId`,但可稳定通过 `requesterSenderId` 写出 `role_id`。-4. 在真实机器人私聊与群聊场景中,已确认不同用户会被映射为不同的 `role_id`,且 assistant message 保持 `role_id:null`。+1. 插件侧 user namespace、显式租户 header 与 `peer_id` 透传能力已完成联调验证。+2. `afterTurn` 路径可通过 `runtimeContext.senderId` 正确写出 `peer_id`。+3. `memory_store` 路径在工具上下文中无法直接读取 `senderId`,但可稳定通过 `requesterSenderId` 写出 `peer_id`。+4. 在真实机器人私聊与群聊场景中,已确认不同用户会被映射为不同的 `peer_id`,且 assistant message 保持 `peer_id:null`。5. 当前 OpenViking 插件链路已满足多租户、命名空间与 sender 身份透传的测试目标。## 6. 建议-1. 若后续服务端对 `api_key + USER` 的 `role_id` 语义收紧,应补充一条显式兼容说明或服务端协同约束。+1. 若后续服务端对 `api_key + USER` 的 `peer_id` 语义收紧,应补充一条显式兼容说明或服务端协同约束。2. 如需继续扩大矩阵,可追加:- 更多账号/用户组合- 不同群聊成员的稳定性回归diff --git a/examples/openclaw-plugin/openclaw.plugin.json b/examples/openclaw-plugin/openclaw.plugin.jsonindex 3fd35789e..1927e08f7 100644--- a/examples/openclaw-plugin/openclaw.plugin.json+++ b/examples/openclaw-plugin/openclaw.plugin.json@@ -78,10 +78,15 @@"placeholder": "http://127.0.0.1:1933","help": "HTTP URL when mode is remote (or ${OPENVIKING_BASE_URL})"},- "agent_prefix": {- "label": "Agent Prefix",+ "peer_role": {+ "label": "Peer Role",+ "placeholder": "none",+ "help": "Controls which messages include peer_id: none, assistant, or person. New installs default to none."+ },+ "peer_prefix": {+ "label": "Peer Prefix","placeholder": "optional-prefix",- "help": "Optional OpenViking agent prefix. Empty: follow OpenClaw ctx.agentId directly. Non-empty: use `<prefix>_<OpenClaw ctx.agentId>` (sanitized to letters/digits/_/-). If OpenClaw ctx.agentId is unavailable, use OpenClaw default agent `main`."+ "help": "Optional prefix for assistant peer_id values derived from OpenClaw runtime agent IDs."},"apiKey": {"label": "OpenViking API Key",@@ -101,24 +106,6 @@"help": "Advanced option. Tenant user ID. Only needed when explicitly sending identity headers.","advanced": true},- "isolateUserScopeByAgent": {- "label": "Isolate User Scope By Agent",- "placeholder": "false",- "help": "Canonical namespace policy. false (default): user alias expands to viking://user/<user_id>/... . true: expands to viking://user/<user_id>/agent/<agent_id>/... . Must match the server-side account namespace policy.",- "advanced": true- },- "isolateAgentScopeByUser": {- "label": "Isolate Agent Scope By User",- "placeholder": "false",- "help": "Canonical namespace policy. false (default): agent alias expands to viking://agent/<agent_id>/... . true: expands to viking://agent/<agent_id>/user/<user_id>/... . Must match the server-side account namespace policy.",- "advanced": true- },- "agentScopeMode": {- "label": "Deprecated Agent Scope Mode",- "placeholder": "agent",- "help": "Deprecated compatibility alias for older routing. Prefer isolateUserScopeByAgent / isolateAgentScopeByUser. Explicit user_agent => false/true, explicit agent => false/false. When fully unset, the plugin defaults to false/false to match the current server-side policy.",- "advanced": true- },"targetUri": {"label": "Search Target URI","placeholder": "viking://user/memories",@@ -227,12 +214,19 @@"baseUrl": {"type": "string"},- "agent_prefix": {- "type": "string"+ "peer_role": {+ "type": "string",+ "enum": [+ "none",+ "assistant",+ "person"+ ],+ "default": "none",+ "description": "Controls which session messages include peer_id."},- "agentId": {+ "peer_prefix": {"type": "string",- "description": "Deprecated: use agent_prefix instead"+ "description": "Optional prefix for assistant peer_id values."},"serverAuthMode": {"type": "string",@@ -247,15 +241,6 @@"userId": {"type": "string"},- "isolateUserScopeByAgent": {- "type": "boolean"- },- "isolateAgentScopeByUser": {- "type": "boolean"- },- "agentScopeMode": {- "type": "string"- },"targetUri": {"type": "string"},diff --git a/examples/openclaw-plugin/setup-helper/install.js b/examples/openclaw-plugin/setup-helper/install.jsindex b765e3612..af23c48d8 100755--- a/examples/openclaw-plugin/setup-helper/install.js+++ b/examples/openclaw-plugin/setup-helper/install.js@@ -122,7 +122,10 @@ const selectedMode = "remote";const baseUrlFromEnv = !!process.env.OPENVIKING_BASE_URL;let remoteBaseUrl = (process.env.OPENVIKING_BASE_URL || "http://127.0.0.1:1933").trim();let remoteApiKey = (process.env.OPENVIKING_API_KEY || "").trim();-let remoteAgentPrefix = (process.env.OPENVIKING_AGENT_PREFIX || "").trim();+let remotePeerRole = (process.env.OPENVIKING_PEER_ROLE || "").trim().toLowerCase();+let remotePeerPrefix = (process.env.OPENVIKING_PEER_PREFIX || "").trim();+let peerRoleExplicit = !!process.env.OPENVIKING_PEER_ROLE;+if (!remotePeerRole) remotePeerRole = "none";let remoteAccountId = (process.env.OPENVIKING_ACCOUNT_ID || "").trim();let remoteUserId = (process.env.OPENVIKING_USER_ID || "").trim();let baseUrlExplicit = baseUrlFromEnv;@@ -284,15 +287,32 @@ for (let i = 0; i < argv.length; i++) {remoteApiKey = arg.slice("--api-key=".length).trim();continue;}- if (arg === "--agent-prefix") {+ if (arg === "--peer-role") {const val = argv[i + 1]?.trim();- if (!val) { console.error("--agent-prefix requires a value"); process.exit(1); }- remoteAgentPrefix = val;+ if (!val) { console.error("--peer-role requires a value"); process.exit(1); }+ const role = normalizePeerRole(val);+ if (!role) { console.error('--peer-role must be "none", "assistant", or "person"'); process.exit(1); }+ remotePeerRole = role;+ peerRoleExplicit = true;i += 1;continue;}- if (arg.startsWith("--agent-prefix=")) {- remoteAgentPrefix = arg.slice("--agent-prefix=".length).trim();+ if (arg.startsWith("--peer-role=")) {+ const role = normalizePeerRole(arg.slice("--peer-role=".length));+ if (!role) { console.error('--peer-role must be "none", "assistant", or "person"'); process.exit(1); }+ remotePeerRole = role;+ peerRoleExplicit = true;+ continue;+ }+ if (arg === "--peer-prefix") {+ const val = argv[i + 1]?.trim();+ if (!val) { console.error("--peer-prefix requires a value"); process.exit(1); }+ remotePeerPrefix = val;+ i += 1;+ continue;+ }+ if (arg.startsWith("--peer-prefix=")) {+ remotePeerPrefix = arg.slice("--peer-prefix=".length).trim();continue;}if (arg === "--account-id") {@@ -323,6 +343,12 @@ for (let i = 0; i < argv.length; i++) {}}+remotePeerRole = normalizePeerRole(remotePeerRole) || "none";+if (!isValidPeerPrefixInput(remotePeerPrefix)) {+ console.error("--peer-prefix may only contain letters, digits, underscores, and hyphens");+ process.exit(1);+}+nonInteractive = baseUrlExplicit;function setOpenClawDir(dir) {@@ -347,7 +373,8 @@ function printHelp() {console.log(" --uninstall, --remove Uninstall OpenViking plugin from OpenClaw (backup config, remove plugin entries)");console.log(" --base-url=URL OpenViking server URL (default: $OPENVIKING_BASE_URL or http://127.0.0.1:1933)");console.log(" --api-key=KEY OpenViking API key (default: $OPENVIKING_API_KEY)");- console.log(" --agent-prefix=PREFIX Agent routing prefix (default: $OPENVIKING_AGENT_PREFIX)");+ console.log(" --peer-role=ROLE Peer role: none, assistant, or person (default: $OPENVIKING_PEER_ROLE or none)");+ console.log(" --peer-prefix=PREFIX Prefix for assistant peer_id values (default: $OPENVIKING_PEER_PREFIX)");console.log(" --account-id=ID Account ID for root API key (default: $OPENVIKING_ACCOUNT_ID)");console.log(" --user-id=ID User ID for root API key (default: $OPENVIKING_USER_ID)");console.log(" --force-slot Explicitly replace an existing contextEngine slot owner");@@ -487,11 +514,16 @@ function isYes(answer) {return normalized === "y" || normalized === "yes";}-function isValidAgentPrefixInput(value) {+function isValidPeerPrefixInput(value) {const trimmed = String(value || "").trim();return !trimmed || /^[a-zA-Z0-9_-]+$/.test(trimmed);}+function normalizePeerRole(value) {+ const role = String(value || "").trim().toLowerCase();+ return role === "none" || role === "assistant" || role === "person" ? role : null;+}+function parseJsonObjectFromOutput(output) {const text = String(output || "").trim();if (!text) return null;@@ -513,18 +545,33 @@ function parseJsonObjectFromOutput(output) {return null;}-async function questionAgentPrefix(defaultValue = "") {+async function questionPeerRole(defaultValue = "none") {+ while (true) {+ const answer = await question(+ tr("Peer Role (none/assistant/person)", "Peer Role(none/assistant/person)"),+ defaultValue,+ );+ const role = normalizePeerRole(answer);+ if (role) return role;+ warn(tr(+ 'Peer Role must be "none", "assistant", or "person".',+ 'Peer Role 必须是 "none"、"assistant" 或 "person"。',+ ));+ }+}++async function questionPeerPrefix(defaultValue = "") {while (true) {const answer = (await question(- tr("Agent Prefix (optional)", "Agent Prefix(可选)"),+ tr("Peer Prefix (optional)", "Peer Prefix(可选)"),defaultValue,)).trim();- if (isValidAgentPrefixInput(answer)) {+ if (isValidPeerPrefixInput(answer)) {return answer;}warn(tr(- "Agent Prefix may only contain letters, digits, underscores, and hyphens, or be empty.",- "Agent Prefix 只能包含字母、数字、下划线和连字符,或留空。",+ "Peer Prefix may only contain letters, digits, underscores, and hyphens, or be empty.",+ "Peer Prefix 只能包含字母、数字、下划线和连字符,或留空。",));}}@@ -575,7 +622,10 @@ async function collectRemoteConfig() {if (nonInteractive) return;remoteBaseUrl = await question(tr("OpenViking server URL", "OpenViking 服务器地址"), remoteBaseUrl);remoteApiKey = await question(tr("API Key (optional)", "API Key(可选)"), remoteApiKey);- remoteAgentPrefix = await questionAgentPrefix(remoteAgentPrefix);+ remotePeerRole = await questionPeerRole(remotePeerRole);+ remotePeerPrefix = remotePeerRole === "assistant"+ ? await questionPeerPrefix(remotePeerPrefix)+ : "";}async function checkOpenClaw() {@@ -1400,9 +1450,13 @@ function extractRuntimeConfigFromPluginEntry(entryConfig) {if (typeof entryConfig.apiKey === "string" && entryConfig.apiKey.trim()) {runtime.apiKey = entryConfig.apiKey;}- const prefix = entryConfig.agent_prefix || entryConfig.agentId;+ const role = normalizePeerRole(entryConfig.peer_role);+ if (role) {+ runtime.peer_role = role;+ }+ const prefix = entryConfig.peer_prefix;if (typeof prefix === "string" && prefix.trim()) {- runtime.agent_prefix = prefix.trim();+ runtime.peer_prefix = prefix.trim();}if (typeof entryConfig.accountId === "string" && entryConfig.accountId.trim()) {runtime.accountId = entryConfig.accountId.trim();@@ -1703,7 +1757,8 @@ async function prepareStrongPluginUpgrade() {);remoteBaseUrl = upgradeRuntimeConfig.baseUrl || remoteBaseUrl;remoteApiKey = upgradeRuntimeConfig.apiKey || "";- remoteAgentPrefix = upgradeRuntimeConfig.agent_prefix || "";+ remotePeerRole = upgradeRuntimeConfig.peer_role || remotePeerRole || "none";+ remotePeerPrefix = upgradeRuntimeConfig.peer_prefix || "";remoteAccountId = upgradeRuntimeConfig.accountId || "";remoteUserId = upgradeRuntimeConfig.userId || "";info(tr(`Upgrade runtime mode: ${selectedMode} (remote OpenViking server)`, `升级运行模式: ${selectedMode}(远程 OpenViking 服务)`));@@ -2273,7 +2328,8 @@ async function configureOpenClawPlugin({const effectiveRuntimeConfig = runtimeConfig || {baseUrl: remoteBaseUrl,apiKey: remoteApiKey,- agent_prefix: remoteAgentPrefix,+ peer_role: remotePeerRole,+ peer_prefix: remotePeerPrefix,};let allowedPropsLegacy = null;@@ -2288,7 +2344,7 @@ async function configureOpenClawPlugin({}} catch { /* ignore parse errors */ }- const agentVal = effectiveRuntimeConfig.agent_prefix || "";+ const peerVal = effectiveRuntimeConfig.peer_prefix || "";const candidates = {mode: "remote",baseUrl: effectiveRuntimeConfig.baseUrl || remoteBaseUrl,@@ -2296,7 +2352,7 @@ async function configureOpenClawPlugin({autoRecall: true,autoCapture: true,apiKey: effectiveRuntimeConfig.apiKey || undefined,- agentId: agentVal || undefined,+ peer_prefix: peerVal || undefined,};const pluginConfig = {};@@ -2318,7 +2374,8 @@ async function configureOpenClawPlugin({const effectiveRuntimeConfig = runtimeConfig || {baseUrl: remoteBaseUrl,apiKey: remoteApiKey,- agent_prefix: remoteAgentPrefix,+ peer_role: remotePeerRole,+ peer_prefix: remotePeerPrefix,accountId: remoteAccountId,userId: remoteUserId,};@@ -2342,8 +2399,11 @@ async function configureOpenClawPlugin({if (effectiveRuntimeConfig.apiKey) {setupArgs.push("--api-key", effectiveRuntimeConfig.apiKey);}- if (effectiveRuntimeConfig.agent_prefix) {- setupArgs.push("--agent-prefix", effectiveRuntimeConfig.agent_prefix);+ if (effectiveRuntimeConfig.peer_role) {+ setupArgs.push("--peer-role", effectiveRuntimeConfig.peer_role);+ }+ if (effectiveRuntimeConfig.peer_prefix) {+ setupArgs.push("--peer-prefix", effectiveRuntimeConfig.peer_prefix);}if (effectiveRuntimeConfig.accountId) {setupArgs.push("--account-id", effectiveRuntimeConfig.accountId);@@ -2472,8 +2532,9 @@ async function configureOpenClawPlugin({}} catch { /* ignore parse errors, write all fields */ }- const agentVal = effectiveRuntimeConfig.agent_prefix || "";- const useAgentPrefix = !allowedProps || allowedProps.has("agent_prefix");+ const peerRole = normalizePeerRole(effectiveRuntimeConfig.peer_role) || "none";+ const peerVal = effectiveRuntimeConfig.peer_prefix || "";+ const usePeerFields = !allowedProps || allowedProps.has("peer_role") || allowedProps.has("peer_prefix");const candidates = {mode: "remote",baseUrl: effectiveRuntimeConfig.baseUrl || remoteBaseUrl,@@ -2481,10 +2542,9 @@ async function configureOpenClawPlugin({accountId: effectiveRuntimeConfig.accountId || undefined,userId: effectiveRuntimeConfig.userId || undefined,};- if (useAgentPrefix) {- candidates.agent_prefix = agentVal;- } else {- candidates.agentId = agentVal;+ if (usePeerFields) {+ candidates.peer_role = peerRole;+ if (peerVal) candidates.peer_prefix = peerVal;}const pluginConfig = {};diff --git a/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md b/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.mdindex 41fb4e078..ef57a96dc 100644--- a/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md+++ b/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md@@ -109,7 +109,7 @@ Send this message:> 我需要 3 条信息,不知道的可以问你的管理员:> 1. **OpenViking 服务地址** —— 例如 `https://ov.example.com` 或 `http://192.168.1.100:1933`,本机服务可以直接说"本机"> 2. **API Key** —— 用来鉴权;服务没开认证可以说"没有"-> 3. **Agent 标识前缀**(可选) —— 用于区分多个 agent 的记忆命名空间,留空就用默认+> 3. **Agent 标识前缀**(可选) —— 用于生成 OpenClaw 运行时 peer 标识,留空就用默认>> 先告诉我服务地址吧?@@ -118,7 +118,7 @@ Send this message:> I need 3 things (ask your admin if unsure):> 1. **OpenViking server URL** — e.g. `https://ov.example.com` or `http://192.168.1.100:1933`. For a local server, just say "local".> 2. **API Key** — for auth. Say "none" if the server has no auth.-> 3. **Agent prefix** (optional) — used to namespace memories across agents. Leave blank for default.+> 3. **Agent prefix** (optional) — used to build the OpenClaw runtime peer identity. Leave blank for default.>> What's the server URL?@@ -262,14 +262,14 @@ Tell the user:Run the installer with `npx` (no global install needed):```bash-npx -y openclaw-openviking-setup-helper@latest --base-url BASE_URL [--api-key API_KEY] [--agent-prefix AGENT_PREFIX] [--account-id ACCOUNT_ID] [--user-id USER_ID]+npx -y openclaw-openviking-setup-helper@latest --base-url BASE_URL [--api-key API_KEY] [--peer-role PEER_ROLE] [--peer-prefix PEER_PREFIX] [--account-id ACCOUNT_ID] [--user-id USER_ID]```Build the flag list according to what the user gave you:- Always pass `--base-url BASE_URL`.- Pass `--api-key API_KEY` only if `API_KEY` is non-empty.-- Pass `--agent-prefix AGENT_PREFIX` only if the user gave one.+- Pass `--peer-role` / `--peer-prefix` only if the user explicitly wants peer IDs. Default is no peer IDs.- `--account-id` / `--user-id` only if the root-key path requires them.`ov-install` will, in one shot:@@ -290,14 +290,14 @@ If `ov-install` exits non-zero, capture the last 30 lines of its output, show thRun the setup wizard non-interactively. Build flags from collected values:```bash-openclaw openviking setup --base-url BASE_URL --json [--api-key API_KEY] [--agent-prefix AGENT_PREFIX] [--account-id ACCOUNT_ID] [--user-id USER_ID] [--allow-offline] [--force-slot]+openclaw openviking setup --base-url BASE_URL --json [--api-key API_KEY] [--peer-role PEER_ROLE] [--peer-prefix PEER_PREFIX] [--account-id ACCOUNT_ID] [--user-id USER_ID] [--allow-offline] [--force-slot]```Rules:- `--base-url BASE_URL` is **required** under `--json`. Without it, the wizard prints `--json requires --base-url for non-interactive mode`.- `--api-key` only if `API_KEY` is non-empty.-- `--agent-prefix` only if the user gave one. Use **`--agent-prefix`**, not `--agent-id` (deprecated and removed).+- `--peer-role` / `--peer-prefix` only if the user explicitly wants peer IDs. Default is `--peer-role none`.- `--account-id` / `--user-id` only after STEP 7 root-key detection (see below).- `--allow-offline` only if the user explicitly approved it in STEP 5.- `--force-slot` **never** in the first attempt. Add only after the user confirms (see slot_blocked handling below).@@ -310,7 +310,7 @@ The wizard prints a single JSON object:{"success": true | false,"action": "configured" | "existing" | "error" | "slot_blocked",- "config": { "mode": "remote", "baseUrl": "...", "apiKey": "...", "agent_prefix": "...", "accountId": "...", "userId": "..." },+ "config": { "mode": "remote", "baseUrl": "...", "apiKey": "...", "peer_role": "none|assistant|person", "peer_prefix": "...", "accountId": "...", "userId": "..." },"health": { "ok": true, "status": 200 },"keyProbe": { "keyType": "user_key" | "root_key" | "none", "ok": true },"slot": { "ok": true, "owner": "openviking" },@@ -397,7 +397,7 @@ Expected output:"configured": true,"slotActive": true,"health": { "ok": true },- "config": { "baseUrl": "...", "agent_prefix": "..." }+ "config": { "baseUrl": "...", "peer_role": "none", "peer_prefix": "..." }}```@@ -504,7 +504,8 @@ These are the keys under `plugins.entries.openviking.config` in `openclaw.json`.| `mode` | `"remote"` (forced by plugin) | Always remote in this skill. Don't set manually. || `baseUrl` | `http://127.0.0.1:1933` | OpenViking server URL. || `apiKey` | — | API key. Optional if server has no auth. |-| `agent_prefix` | `""` | Prefix for routing memories per agent. Letters / digits / `_` / `-`. |+| `peer_role` | `"none"` | Controls whether session messages include `peer_id`: `none`, `assistant`, or `person`. |+| `peer_prefix` | `""` | Optional prefix for assistant `peer_id` values when `peer_role=assistant`. || `accountId` | — | Required when `apiKey` is a root key. || `userId` | — | Required when `apiKey` is a root key. || `targetUri` | `viking://user/memories` | Default search scope URI. |@@ -518,9 +519,6 @@ These are the keys under `plugins.entries.openviking.config` in `openclaw.json`.| `recallMaxInjectedChars` | (plugin default) | Hard cap on injected character count. || `recallPreferAbstract` | (plugin default) | Prefer abstract memories over raw. || `recallTokenBudget` | (plugin default) | Token budget for injected memories. |-| `isolateUserScopeByAgent` | (plugin default) | Multi-tenant scoping toggle. |-| `isolateAgentScopeByUser` | (plugin default) | Multi-tenant scoping toggle. |-| `agentScopeMode` | (plugin default) | Agent scope strategy. || `bypassSessionPatterns` | — | Glob patterns for sessions skipped by capture. || `ingestReplyAssist` | (plugin default) | Reply-assist ingestion toggle. || `emitStandardDiagnostics` | (plugin default) | Verbose diagnostic logs. |@@ -659,7 +657,7 @@ Match against actual stderr / JSON `error` strings.| `Server unreachable: …. Use --allow-offline to save config anyway.` | Setup couldn't reach server | Offer `--allow-offline`. || `contextEngine slot is owned by "<x>". … Use --force-slot to replace.` | Slot conflict | Ask user, then retry with `--force-slot`. || `Root API key detected. Missing: --account-id, --user-id` | Multi-tenant key | Collect both, retry with `--account-id` `--user-id`. |-| `openviking: config parse failed` (in gateway log) | Bad value in `openclaw.json` | Show user; check `agent_prefix` charset, URL format. |+| `openviking: config parse failed` (in gateway log) | Bad value in `openclaw.json` | Show user; check `peer_role`, `peer_prefix` charset, URL format. || `extracted 0 memories` after a turn | Server VLM/embedding misconfigured | **Out of scope.** Tell user this is a server-side issue — ask their OpenViking admin to check VLM / embedding config. || `401` / `403` on plugin requests, but `/health` works | Server requires auth on API endpoints | Re-run STEP 7 with the correct `--api-key`. || Plugin doesn't appear in `openclaw plugins list` after Path A | Install didn't actually finish | Re-run Path A; use Path B only if the failure is registry/rate-limit related. |@@ -671,7 +669,7 @@ Match against actual stderr / JSON `error` strings.3. **Never silently use `--force-slot`.** Slot replacement disables another plugin — always confirm with the user first.4. **Never invent values.** If the user can't provide a required value, stop and tell them what to ask their admin.5. **Never claim success without STEP 10.** Only after `openclaw openviking status --json` shows `configured: true && slotActive: true && health.ok: true` may you tell the user it's done.-6. **Use `--agent-prefix`, not `--agent-id`.** The latter is deprecated and removed from the schema.+6. **Use `--peer-role` / `--peer-prefix` only for explicit peer routing.**7. **For Windows, use PowerShell equivalents.** Don't rely on `nohup`, `&`, `mkdir -p`, `source`, etc.8. **Switch to Path B (ov-install) only for ClawHub/rate-limit/registry availability failures.** Don't use it to hide version conflicts or package validation errors.9. **Do NOT install or operate the OpenViking server.** This skill assumes the server is already running. If it isn't, tell the user to contact their admin or follow the OpenViking docs.diff --git a/examples/openclaw-plugin/tests/e2e/test-archive-expand.py b/examples/openclaw-plugin/tests/e2e/test-archive-expand.pyindex bba147b49..a638b1231 100644--- a/examples/openclaw-plugin/tests/e2e/test-archive-expand.py+++ b/examples/openclaw-plugin/tests/e2e/test-archive-expand.py@@ -205,8 +205,6 @@ USER_ID = f"xiaojie-{uuid.uuid4().hex[:8]}"DISPLAY_NAME = "小杰"DEFAULT_GATEWAY = "http://127.0.0.1:19789"DEFAULT_OPENVIKING = "http://127.0.0.1:2934"-AGENT_ID = "main"-console = Console(force_terminal=True)# ── 测试结果收集 ──────────────────────────────────────────────────────────@@ -227,19 +225,12 @@ def check(label: str, condition: bool, detail: str = ""):CHAT_BATCH_1 = ["嗨!我叫小杰,刚入职三个月,在做一个用户画像系统。后端用 Go,框架是 Gin,数据库用 ClickHouse。我想跟你聊聊项目的技术细节,你帮我记一下。",-"我们的 API 认证用的是自己写的 JWT 中间件,token 过期时间设的 7200 秒,刷新 token 有效期 30 天,密钥存在环境变量 AUTH_JWT_SECRET 里。",-"数据采集这块,我写了个 Kafka consumer,group id 是 user-profile-sync-v2,消费的 topic 是 user_behavior_events,每批最多拉 500 条消息。",-"画像数据的 ClickHouse 表叫 user_profiles_v3,主键是 (user_id, event_date),用了 MergeTree 引擎,TTL 设的 180 天。",-"部署脚本在 deploy/scripts/rollout.sh,里面有个关键的金丝雀发布逻辑,先把 10% 流量切到新版本,观察 5 分钟没报警再全量。",-"我们的 Prometheus 告警规则在 monitoring/alerts/backend.yml,有一条关键的:当 P99 延迟超过 500ms 持续 3 分钟就会触发 page 告警。",-"代码规范方面,Go 项目用 golangci-lint,配置文件在 .golangci.yml,禁用了 gocyclo,开启了 govet、errcheck、staticcheck。",-"上周修了个严重 bug:当 ClickHouse 连接超时时,consumer 没有正确回退 offset,导致消息丢失。我写了个 RetryableConsumer wrapper 来修复,重试间隔是指数退避,基础间隔 200ms,最大重试 5 次。",]@@ -248,19 +239,12 @@ CHAT_BATCH_1 = [CHAT_BATCH_2 = ["紧急情况!线上推荐接口大面积超时,错误日志里出现了一条:failed to connect to reco-model-svc:8091: dial tcp 10.0.3.17:8091: i/o timeout。我先帮你记录下排障过程。",-"我先跑了 kubectl get pods -n reco-prod,发现 reco-model-svc-7b9f4d6c8-x2k9p 这个 pod 的 RESTARTS 是 47 次,状态是 CrashLoopBackOff。kubectl logs 看到 OOM Killed,内存限制是 512Mi 但模型加载需要 800Mi。",-"临时解决方案:kubectl edit deployment reco-model-svc -n reco-prod,把 resources.limits.memory 从 512Mi 改成 1Gi,然后 kubectl rollout restart deployment reco-model-svc -n reco-prod。等了 3 分钟 pod 恢复正常。",-"但还有个隐患:我用 tcpdump -i eth0 port 8091 -w /tmp/reco-debug-20260315.pcap 抓了 5 分钟的包,发现有个上游服务 gateway-proxy (IP 10.0.2.33) 的连接没有正确关闭,导致连接泄漏。",-"连接泄漏的根因:gateway-proxy 用了一个自定义的 HTTP client,pool_maxsize 设成了 200,但 idle_timeout 是 0(永不超时)。我在 gateway-proxy 的 config/http-pool.yaml 里改成了 idle_timeout: 30s,pool_maxsize: 50。",-"修完之后跑了个回归测试:curl -w '@curl-format.txt' -o /dev/null -s 'http://10.0.3.17:8091/predict?user_id=test_user_42&features=age,gender,region' 返回 time_total: 0.023s,比之前的 2.1s 快了 100 倍。",-"事后我写了个 incident report,编号是 INC-2026-0315-RECO-OOM,根因分类是 Resource Misconfiguration,影响时长 47 分钟,影响用户数约 12000。",-"老王看完报告说,以后所有服务的 memory limit 至少设置为实际用量的 1.5 倍,并且要在 Grafana 上加一个 container_memory_working_set_bytes / container_spec_memory_limit_bytes > 0.8 的告警。",]@@ -269,19 +253,12 @@ CHAT_BATCH_2 = [CHAT_BATCH_3 = ["今天代码评审了我的推荐接口 PR,PR 编号是 #1847。老王给了 3 个重要 comment,我一个个跟你说。",-"第一个 comment 在 internal/handler/recommend.go 的第 73 行:老王说我的错误处理不对,原来写的是 if err != nil { return nil, err },但应该包装一下上下文:return nil, fmt.Errorf('recommend handler: fetch features for user %s: %w', userID, err)。",-"第二个 comment 在 internal/cache/feature_cache.go 第 142 行:我用了 sync.Map 来缓存用户特征,但老王建议改用分段锁 map,因为 sync.Map 在写多读少的场景下性能不好。他推荐用 github.com/orcaman/concurrent-map/v2 这个库。",-"第三个 comment 是关于测试覆盖率的:当前 recommend 包的覆盖率只有 38%,老王要求至少到 70%。他特别指出 internal/handler/recommend_test.go 缺少对 context.Canceled 和 context.DeadlineExceeded 的边界测试。",-"我按老王的建议改了代码。feature_cache.go 的改动最大,从 sync.Map 迁移到 cmap.ConcurrentMap[string, *UserFeatures]。benchmark 跑下来:BenchmarkFeatureCacheGet-8 从 834 ns/op 降到了 412 ns/op,快了差不多一倍。",-"测试也补了,加了 TestRecommendHandler_ContextCanceled 和 TestRecommendHandler_DeadlineExceeded 两个用例。覆盖率从 38% 提升到了 74%。go test -cover ./internal/handler/ 输出:coverage: 74.2% of statements。",-"PR 最终在周三下午 3:42 合并,commit hash 是 a3f7b2d。合并前跑了 CI,全部 green:lint 42s, test 1m18s, build 2m03s。",-"对了,合并后我发现有个小问题:feature_cache.go 里有一行 import 多余了,_ 'net/http/pprof' 是调试时加的忘了删。我又开了个 hotfix PR #1852 修掉了。",]@@ -289,19 +266,12 @@ CHAT_BATCH_3 = [CHAT_BATCH_4 = ["最近团队在讨论要不要把推荐服务拆成微服务。我画了一个架构图,核心是 3 个服务:feature-store (负责用户特征存储), model-server (负责模型推理), ranking-api (负责排序和过滤)。",-"feature-store 的设计:用 Redis Cluster 做热数据缓存,冷数据存 ClickHouse。Redis 集群是 3 主 3 从,每个节点 maxmemory 8GB,eviction 策略用 allkeys-lru。",-"model-server 计划用 gRPC 通信,proto 文件在 api/proto/model_service.proto。核心 RPC 是 Predict(PredictRequest) returns (PredictResponse),PredictRequest 里有 user_id (string), features (map<string, float>), model_version (string, 默认 'v3.2.1')。",-"ranking-api 是面向外部的 REST 接口。我设计了一个两层缓存:L1 是本地 LRU cache (github.com/hashicorp/golang-lru/v2, 容量 10000), L2 是 Redis。缓存 key 的格式是 reco:{user_id}:{model_version}:{timestamp_bucket},timestamp_bucket 每 5 分钟一个。",-"团队讨论的争议点:老王认为 feature-store 和 model-server 可以合并,因为两者耦合度高。但我觉得拆开更好,因为 feature-store 的扩展需求(加新特征)和 model-server 的扩展需求(换模型)是独立的。",-"最终架构评审的结论:先按 3 服务拆分,但 feature-store 和 model-server 共享一个 K8s namespace (reco-services)。服务间通信走 Istio service mesh,mTLS 加密。",-"部署策略:feature-store 3 副本(HPA min=3, max=10, CPU 阈值 70%),model-server 2 副本(HPA min=2, max=6, CPU 阈值 60%),ranking-api 4 副本(HPA min=4, max=20, CPU 阈值 65%)。",-"对了,架构评审文档存在 Confluence 上,页面 ID 是 ARCH-2026-RECO-MS,最后更新时间是 3 月 20 号。评审参与人:我、老王、测试小李、运维老赵。",]@@ -406,20 +376,19 @@ def extract_reply_text(data: dict) -> str:class OVInspector:- def __init__(self, base_url: str, agent_id: str = AGENT_ID):+ def __init__(self, base_url: str):self.base_url = base_url.rstrip("/")- self.agent_id = agent_iddef _headers(self) -> dict:h: dict[str, str] = {"Content-Type": "application/json"}- if self.agent_id:- h["X-OpenViking-Agent"] = self.agent_idreturn hdef _get(self, path: str, timeout: int = 10):try:resp = requests.get(- f"{self.base_url}{path}", headers=self._headers(), timeout=timeout,+ f"{self.base_url}{path}",+ headers=self._headers(),+ timeout=timeout,)if resp.status_code == 200:data = resp.json()@@ -486,9 +455,9 @@ class OVInspector:def find_latest_session(self) -> str | None:sessions = self.list_sessions()real = [- s for s in sessions- if isinstance(s, dict)- and not s.get("session_id", "").startswith("memory-store-")+ s+ for s in sessions+ if isinstance(s, dict) and not s.get("session_id", "").startswith("memory-store-")]if not real:return None@@ -527,8 +496,12 @@ def render_json(data: Any, title: str = "JSON"):def run_phase_chat(- gateway_url: str, user_id: str, messages: list[str],- batch_label: str, delay: float, verbose: bool,+ gateway_url: str,+ user_id: str,+ messages: list[str],+ batch_label: str,+ delay: float,+ verbose: bool,) -> tuple[int, int]:console.print()console.rule(@@ -544,7 +517,11 @@ def run_phase_chat(console.rule(f"[dim]Turn {i}/{total}[/dim]", style="dim")preview = msg[:150] + ("..." if len(msg) > 150 else "")console.print(- Panel(preview, title=f"[bold cyan]{DISPLAY_NAME} [{i}/{total}][/bold cyan]", border_style="cyan"),+ Panel(+ preview,+ title=f"[bold cyan]{DISPLAY_NAME} [{i}/{total}][/bold cyan]",+ border_style="cyan",+ ),)try:data = send_message(gateway_url, msg, user_id)@@ -635,7 +612,10 @@ def run_phase_verify_index(openviking_url: str, verbose: bool) -> str:def run_phase_expand(- gateway_url: str, user_id: str, delay: float, verbose: bool,+ gateway_url: str,+ user_id: str,+ delay: float,+ verbose: bool,) -> list:console.print()console.rule(@@ -683,18 +663,30 @@ def run_phase_expand()if verbose:- console.print(f" [dim]完整输出: {json.dumps(data.get('output', []), ensure_ascii=False)[:500]}[/dim]")-- results.append({- "question": q, "hits": hits, "hit_rate": hit_rate,- "success": success, "description": desc,- })+ console.print(+ f" [dim]完整输出: {json.dumps(data.get('output', []), ensure_ascii=False)[:500]}[/dim]"+ )++ results.append(+ {+ "question": q,+ "hits": hits,+ "hit_rate": hit_rate,+ "success": success,+ "description": desc,+ }+ )except Exception as e:check(f"Expand Q{i}: 发送成功", False, str(e))- results.append({- "question": q, "hits": [], "hit_rate": 0,- "success": False, "description": desc,- })+ results.append(+ {+ "question": q,+ "hits": [],+ "hit_rate": 0,+ "success": False,+ "description": desc,+ }+ )if i < total:time.sleep(delay)@@ -706,7 +698,10 @@ def run_phase_expand(def run_phase_no_expand(- gateway_url: str, user_id: str, delay: float, verbose: bool,+ gateway_url: str,+ user_id: str,+ delay: float,+ verbose: bool,) -> list:console.print()console.rule(@@ -745,7 +740,9 @@ def run_phase_no_expand(hit_rate >= 0.5,f"命中={hits}, rate={hit_rate:.0%}",)- results.append({"question": q, "hits": hits, "hit_rate": hit_rate, "success": hit_rate >= 0.5})+ results.append(+ {"question": q, "hits": hits, "hit_rate": hit_rate, "success": hit_rate >= 0.5}+ )except Exception as e:check(f"NoExpand Q{i}: 发送成功", False, str(e))results.append({"question": q, "hits": [], "hit_rate": 0, "success": False})@@ -760,7 +757,11 @@ def run_phase_no_expand(def run_full_test(- gateway_url: str, openviking_url: str, user_id: str, delay: float, verbose: bool,+ gateway_url: str,+ openviking_url: str,+ user_id: str,+ delay: float,+ verbose: bool,gateway_restart_cmd: str = "",):console.print()@@ -777,34 +778,50 @@ def run_full_test(# Phase 1: 第一批对话 — 项目技术细节ok1, fail1 = run_phase_chat(- gateway_url, user_id, CHAT_BATCH_1,- "Phase 1: 第一段对话 — 项目技术细节", delay, verbose,+ gateway_url,+ user_id,+ CHAT_BATCH_1,+ "Phase 1: 第一段对话 — 项目技术细节",+ delay,+ verbose,)check(f"Phase 1: {ok1}/{len(CHAT_BATCH_1)} 轮成功", fail1 == 0, f"ok={ok1}, fail={fail1}")# Phase 2a: 第二批对话 — 排障过程ok2, fail2 = run_phase_chat(- gateway_url, user_id, CHAT_BATCH_2,- "Phase 2a: 第二段对话 — 线上排障过程", delay, verbose,+ gateway_url,+ user_id,+ CHAT_BATCH_2,+ "Phase 2a: 第二段对话 — 线上排障过程",+ delay,+ verbose,)check(f"Phase 2a: {ok2}/{len(CHAT_BATCH_2)} 轮成功", fail2 == 0, f"ok={ok2}, fail={fail2}")# Phase 2b: 第三批对话 — 代码评审讨论ok3, fail3 = run_phase_chat(- gateway_url, user_id, CHAT_BATCH_3,- "Phase 2b: 第三段对话 — 代码评审讨论", delay, verbose,+ gateway_url,+ user_id,+ CHAT_BATCH_3,+ "Phase 2b: 第三段对话 — 代码评审讨论",+ delay,+ verbose,)check(f"Phase 2b: {ok3}/{len(CHAT_BATCH_3)} 轮成功", fail3 == 0, f"ok={ok3}, fail={fail3}")# Phase 2c: 第四批对话 — 架构设计讨论ok4, fail4 = run_phase_chat(- gateway_url, user_id, CHAT_BATCH_4,- "Phase 2c: 第四段对话 — 架构设计讨论", delay, verbose,+ gateway_url,+ user_id,+ CHAT_BATCH_4,+ "Phase 2c: 第四段对话 — 架构设计讨论",+ delay,+ verbose,)check(f"Phase 2c: {ok4}/{len(CHAT_BATCH_4)} 轮成功", fail4 == 0, f"ok={ok4}, fail={fail4}")# Phase 3: 验证 Archive Index- session_id = run_phase_verify_index(openviking_url, verbose)+ run_phase_verify_index(openviking_url, verbose)# Gateway 重启 — 清除工作记忆,迫使 LLM 从归档获取信息if gateway_restart_cmd:@@ -814,15 +831,20 @@ def run_full_test(time.sleep(10)console.print(f"[yellow]执行: {gateway_restart_cmd}[/yellow]")import subprocess+try:result = subprocess.run(- gateway_restart_cmd, shell=True, capture_output=True, text=True, timeout=60,+ gateway_restart_cmd,+ shell=True,+ capture_output=True,+ text=True,+ timeout=60,)console.print(f"[yellow]Gateway 重启完成: {result.stdout.strip()}[/yellow]")except subprocess.TimeoutExpired:console.print("[yellow]Gateway 重启命令超时,检查健康状态...[/yellow]")# 等待 Gateway 恢复- for attempt in range(15):+ for _attempt in range(15):time.sleep(2)try:r = requests.get(f"{gateway_url}/health", timeout=3)@@ -866,7 +888,7 @@ def run_full_test(tree.add(f"Phase 2a: 线上排障 — {ok2}/{len(CHAT_BATCH_2)}")tree.add(f"Phase 2b: 代码评审 — {ok3}/{len(CHAT_BATCH_3)}")tree.add(f"Phase 2c: 架构设计 — {ok4}/{len(CHAT_BATCH_4)}")- tree.add(f"Phase 3: Archive Index 验证")+ tree.add("Phase 3: Archive Index 验证")expand_ok = sum(1 for r in expand_results if r["success"])tree.add(f"Phase 4: 归档展开 — {expand_ok}/{len(expand_results)} 问题回答正确")@@ -935,6 +957,7 @@ def scan_expand_log(log_path: str):log_table.add_column("详情", style="dim")import re+row_idx = 0for line in invoked_lines:row_idx += 1@@ -951,7 +974,9 @@ def scan_expand_log(log_path: str):msgs = m_msg.group(1) if m_msg else "?"chars = m_chars.group(1) if m_chars else "?"log_table.add_row(- str(row_idx), "expanded", archive_id,+ str(row_idx),+ "expanded",+ archive_id,f"恢复 {msgs} 条消息, {chars} 字符",)@@ -965,8 +990,9 @@ def scan_expand_log(log_path: str):archive_counts[aid] = archive_counts.get(aid, 0) + 1console.print()- console.print(f"[green]共 {len(invoked_lines)} 次 invoked, "- f"{len(expanded_lines)} 次 expanded[/green]")+ console.print(+ f"[green]共 {len(invoked_lines)} 次 invoked, {len(expanded_lines)} 次 expanded[/green]"+ )for aid, cnt in sorted(archive_counts.items()):console.print(f" {aid}: {cnt} 次调用")@@ -985,8 +1011,14 @@ def main():description=f"ov_archive_expand 归档展开测试 — {DISPLAY_NAME}",formatter_class=argparse.RawDescriptionHelpFormatter,)- parser.add_argument("--gateway", default=DEFAULT_GATEWAY, help=f"Gateway 地址 (默认: {DEFAULT_GATEWAY})")- parser.add_argument("--openviking", default=DEFAULT_OPENVIKING, help=f"OpenViking 地址 (默认: {DEFAULT_OPENVIKING})")+ parser.add_argument(+ "--gateway", default=DEFAULT_GATEWAY, help=f"Gateway 地址 (默认: {DEFAULT_GATEWAY})"+ )+ parser.add_argument(+ "--openviking",+ default=DEFAULT_OPENVIKING,+ help=f"OpenViking 地址 (默认: {DEFAULT_OPENVIKING})",+ )parser.add_argument("--user-id", default=USER_ID, help="测试用户 ID (默认: 随机)")parser.add_argument("--phase",@@ -996,14 +1028,15 @@ def main():)parser.add_argument("--delay", type=float, default=3.0, help="轮次间等待秒数 (默认: 3)")parser.add_argument("--token", default="", help="Gateway auth token (默认: 自动发现)")- parser.add_argument("--agent-id", default=AGENT_ID, help=f"Agent ID (默认: {AGENT_ID})")parser.add_argument(- "--gateway-restart-cmd", default="",+ "--gateway-restart-cmd",+ default="",help="Gateway 重启命令 (在 Phase 4 前执行,清除工作记忆以迫使 archive expand)",)parser.add_argument("--verbose", "-v", action="store_true", help="详细输出")parser.add_argument(- "--log-path", default="",+ "--log-path",+ default="",help="Gateway 日志路径 (如 config/.openclaw/logs/openclaw.log),测试后自动扫描 ov_archive_expand 调用",)args = parser.parse_args()@@ -1022,7 +1055,11 @@ def main():if args.phase == "all":run_full_test(- gateway_url, openviking_url, user_id, args.delay, args.verbose,+ gateway_url,+ openviking_url,+ user_id,+ args.delay,+ args.verbose,gateway_restart_cmd=args.gateway_restart_cmd,)elif args.phase == "chat1":diff --git a/examples/openclaw-plugin/tests/e2e/test-memory-chain.py b/examples/openclaw-plugin/tests/e2e/test-memory-chain.pyindex 890ab7167..2b431f1da 100644--- a/examples/openclaw-plugin/tests/e2e/test-memory-chain.py+++ b/examples/openclaw-plugin/tests/e2e/test-memory-chain.py@@ -148,7 +148,6 @@ USER_ID = f"test-chain-{uuid.uuid4().hex[:8]}"DISPLAY_NAME = "测试用户"DEFAULT_GATEWAY = "http://127.0.0.1:19789"DEFAULT_OPENVIKING = "http://127.0.0.1:2934"-AGENT_ID = "main"console = Console(force_terminal=True)@@ -321,17 +320,14 @@ def extract_reply_text(data: dict) -> str:class OpenVikingInspector:"""OpenViking 内部状态检查器。"""- def __init__(self, base_url: str, api_key: str = "", agent_id: str = AGENT_ID):+ def __init__(self, base_url: str, api_key: str = ""):self.base_url = base_url.rstrip("/")self.api_key = api_key- self.agent_id = agent_iddef _headers(self) -> dict:h: dict[str, str] = {"Content-Type": "application/json"}if self.api_key:h["X-API-Key"] = self.api_key- if self.agent_id:- h["X-OpenViking-Agent"] = self.agent_idreturn hdef _get(self, path: str, timeout: int = 10) -> dict | None:@@ -1136,7 +1132,6 @@ def run_full_test(gateway_url: str, openviking_url: str, user_id: str, delay: fldef main():- global AGENT_IDparser = argparse.ArgumentParser(description="OpenClaw 记忆链路完整测试",formatter_class=argparse.RawDescriptionHelpFormatter,@@ -1182,11 +1177,6 @@ def main():default="",help="Gateway auth token (默认: 自动从 openclaw.json 发现)",)- parser.add_argument(- "--agent-id",- default=AGENT_ID,- help=f"OpenViking agent ID (默认: {AGENT_ID})",- )parser.add_argument("--verbose","-v",@@ -1202,8 +1192,6 @@ def main():token = args.token or discover_gateway_token()set_gateway_token(token)- AGENT_ID = args.agent_id-console.print("[bold]OpenClaw 记忆链路测试[/bold]")console.print(f"[yellow]Gateway:[/yellow] {gateway_url}")console.print(f"[yellow]OpenViking:[/yellow] {openviking_url}")@@ -1216,17 +1204,17 @@ def main():elif args.phase == "afterTurn":_, _, _ = run_phase_after_turn(openviking_url, user_id, args.verbose)elif args.phase == "commit":- inspector = OpenVikingInspector(openviking_url, agent_id=AGENT_ID)+ inspector = OpenVikingInspector(openviking_url)sid = inspector.find_session_for_user(user_id) or user_idsession_info = inspector.get_session(sid)ac = (session_info.get("commit_count", 0) > 0) if session_info else Falserun_phase_commit(openviking_url, sid, args.verbose, ac)elif args.phase == "assemble":- inspector = OpenVikingInspector(openviking_url, agent_id=AGENT_ID)+ inspector = OpenVikingInspector(openviking_url)sid = inspector.find_session_for_user(user_id) or user_idrun_phase_assemble(gateway_url, openviking_url, user_id, sid, args.delay, args.verbose)elif args.phase == "session-id":- inspector = OpenVikingInspector(openviking_url, agent_id=AGENT_ID)+ inspector = OpenVikingInspector(openviking_url)sid = inspector.find_session_for_user(user_id) or user_idrun_phase_session_id(openviking_url, user_id, sid, args.verbose)elif args.phase == "recall":diff --git a/examples/openclaw-plugin/tests/e2e/test-tool-capture.py b/examples/openclaw-plugin/tests/e2e/test-tool-capture.pyindex 6d417acd2..98e07a449 100644--- a/examples/openclaw-plugin/tests/e2e/test-tool-capture.py+++ b/examples/openclaw-plugin/tests/e2e/test-tool-capture.py@@ -112,8 +112,6 @@ if sys.platform == "win32":GATEWAY_URL = "http://127.0.0.1:19789"OPENVIKING_URL = "http://127.0.0.1:2934"-AGENT_ID = "main"-console = Console(force_terminal=True)assertions: list[dict] = []@@ -192,14 +190,11 @@ def has_tool_use_in_output(data: dict) -> bool:class OVInspector:- def __init__(self, base_url: str, agent_id: str = AGENT_ID):+ def __init__(self, base_url: str):self.base_url = base_url.rstrip("/")- self.agent_id = agent_iddef _headers(self) -> dict:h: dict[str, str] = {"Content-Type": "application/json"}- if self.agent_id:- h["X-OpenViking-Agent"] = self.agent_idreturn hdef _get(self, path: str, timeout: int = 10):@@ -230,7 +225,8 @@ class OVInspector:通过检查每个 session 的 updated_at 来找到最新的。"""sessions = self.list_sessions()real_sessions = [- s for s in sessions+ s+ for s in sessionsif isinstance(s, dict) and not s.get("session_id", "").startswith("memory-store-")]if not real_sessions:@@ -282,11 +278,10 @@ def run_test(delay: float,verbose: bool,token: str = "",- agent_id: str = "",):if not token:token = load_gateway_token()- inspector = OVInspector(openviking_url, agent_id=agent_id or AGENT_ID)+ inspector = OVInspector(openviking_url)console.print(Panel(@@ -305,7 +300,9 @@ def run_test(gateway_responses = []for i, msg_cfg in enumerate(TOOL_TRIGGER_MESSAGES):- console.print(f"\n[cyan]消息 {i + 1}/{len(TOOL_TRIGGER_MESSAGES)}:[/cyan] {msg_cfg['description']}")+ console.print(+ f"\n[cyan]消息 {i + 1}/{len(TOOL_TRIGGER_MESSAGES)}:[/cyan] {msg_cfg['description']}"+ )console.print(f" [dim]> {msg_cfg['input'][:80]}...[/dim]")try:@@ -318,15 +315,19 @@ def run_test(console.print(" [yellow]检测到 tool_use 在响应中[/yellow]")if verbose:- console.print(f" [dim]完整响应: {json.dumps(data, ensure_ascii=False)[:500]}[/dim]")-- gateway_responses.append({- "index": i,- "msg": msg_cfg,- "response": data,- "reply": reply,- "has_tool": has_tool,- })+ console.print(+ f" [dim]完整响应: {json.dumps(data, ensure_ascii=False)[:500]}[/dim]"+ )++ gateway_responses.append(+ {+ "index": i,+ "msg": msg_cfg,+ "response": data,+ "reply": reply,+ "has_tool": has_tool,+ }+ )check(f"消息 {i + 1} 发送成功",@@ -387,7 +388,11 @@ def run_test(returnconsole.print(f" [green]OV session context 消息数: {len(messages)}[/green]")- check("OV session 有内容", len(messages) > 0 or bool(archive_overview), f"messages={len(messages)}")+ check(+ "OV session 有内容",+ len(messages) > 0 or bool(archive_overview),+ f"messages={len(messages)}",+ )# ── Phase 3: 分析存储的内容是否包含 tool 信息 ──────────────────────@@ -403,15 +408,17 @@ def run_test(all_stored_text += (part.get("text", "") or "") + "\n"if verbose:- console.print(Panel(- all_stored_text[:3000] + ("..." if len(all_stored_text) > 3000 else ""),- title="OV 存储的全部文本",- ))+ console.print(+ Panel(+ all_stored_text[:3000] + ("..." if len(all_stored_text) > 3000 else ""),+ title="OV 存储的全部文本",+ )+ )any_tool_in_gateway = any(r.get("has_tool") for r in gateway_responses)# 检查 toolUse 标记(仅在 gateway 响应确实含 tool_use 时才必须)- has_tool_use_marker = bool(re.search(r'\[toolUse:', all_stored_text, re.IGNORECASE))+ has_tool_use_marker = bool(re.search(r"\[toolUse:", all_stored_text, re.IGNORECASE))if any_tool_in_gateway:check("存储文本包含 [toolUse:] 标记",@@ -426,7 +433,7 @@ def run_test()# 检查 toolResult 标记- has_tool_result_marker = bool(re.search(r'result\]:', all_stored_text, re.IGNORECASE))+ has_tool_result_marker = bool(re.search(r"result\]:", all_stored_text, re.IGNORECASE))check("存储文本包含 tool result 标记",has_tool_result_marker or not any_tool_in_gateway,@@ -434,7 +441,7 @@ def run_test()# 检查 assistant 标记- has_assistant = bool(re.search(r'\[assistant\]:', all_stored_text, re.IGNORECASE))+ has_assistant = bool(re.search(r"\[assistant\]:", all_stored_text, re.IGNORECASE))check("存储文本包含 [assistant] 标记",has_assistant,@@ -442,7 +449,7 @@ def run_test()# 检查 user 标记- has_user = bool(re.search(r'\[user\]:', all_stored_text, re.IGNORECASE))+ has_user = bool(re.search(r"\[user\]:", all_stored_text, re.IGNORECASE))check("存储文本包含 [user] 标记",has_user,@@ -451,7 +458,6 @@ def run_test(# 检查关键内容是否保留(检查活跃上下文 + 归档摘要 + gateway 响应)all_gateway_text = "\n".join(r.get("reply", "") for r in gateway_responses)- combined_text = all_stored_text + "\n" + all_gateway_textfor msg_cfg in TOOL_TRIGGER_MESSAGES:for kw in msg_cfg.get("expect_keywords", []):@@ -473,9 +479,9 @@ def run_test(tool_related_lines = []for line in all_stored_text.split("\n"):stripped = line.strip()- if re.search(r'\[toolUse:', stripped, re.IGNORECASE):+ if re.search(r"\[toolUse:", stripped, re.IGNORECASE):tool_related_lines.append(("toolUse", stripped[:150]))- elif re.search(r'result\]:', stripped, re.IGNORECASE):+ elif re.search(r"result\]:", stripped, re.IGNORECASE):tool_related_lines.append(("toolResult", stripped[:150]))if tool_related_lines:@@ -521,7 +527,9 @@ def print_summary():console.print("\n[green bold]全部通过!toolUse/toolResult 捕获验证成功。[/green bold]")else:console.print(f"\n[red bold]有 {failed} 个断言失败。[/red bold]")- console.print("[yellow]注: 如果模型没有调用工具,toolUse/toolResult 标记可能不存在 — 这不代表代码有 bug。[/yellow]")+ console.print(+ "[yellow]注: 如果模型没有调用工具,toolUse/toolResult 标记可能不存在 — 这不代表代码有 bug。[/yellow]"+ )console.print("[yellow]可以在 gateway 日志中确认 afterTurn 的存储内容。[/yellow]")@@ -533,7 +541,6 @@ def main():parser.add_argument("--gateway", default=GATEWAY_URL, help="Gateway 地址")parser.add_argument("--openviking", default=OPENVIKING_URL, help="OpenViking 地址")parser.add_argument("--token", default="", help="Gateway auth token (默认: 自动发现)")- parser.add_argument("--agent-id", default=AGENT_ID, help=f"OpenViking agent ID (默认: {AGENT_ID})")parser.add_argument("--delay", type=float, default=3.0, help="消息间延迟秒数")parser.add_argument("--verbose", "-v", action="store_true", help="详细输出")args = parser.parse_args()@@ -547,7 +554,6 @@ def main():delay=args.delay,verbose=args.verbose,token=args.token,- agent_id=args.agent_id,)diff --git a/examples/openclaw-plugin/tests/test-memory-chain.py b/examples/openclaw-plugin/tests/test-memory-chain.pyindex 877fbf31f..640e9f69c 100644--- a/examples/openclaw-plugin/tests/test-memory-chain.py+++ b/examples/openclaw-plugin/tests/test-memory-chain.py@@ -57,8 +57,6 @@ USER_ID = f"test-chain-{uuid.uuid4().hex[:8]}"DISPLAY_NAME = "测试用户"DEFAULT_GATEWAY = "http://127.0.0.1:18790"DEFAULT_OPENVIKING = "http://127.0.0.1:8000"-AGENT_ID = "openclaw"-console = Console()# ── 测试结果收集 ──────────────────────────────────────────────────────────@@ -151,17 +149,14 @@ def extract_reply_text(data: dict) -> str:class OpenVikingInspector:"""OpenViking 内部状态检查器。"""- def __init__(self, base_url: str, api_key: str = "", agent_id: str = AGENT_ID):+ def __init__(self, base_url: str, api_key: str = ""):self.base_url = base_url.rstrip("/")self.api_key = api_key- self.agent_id = agent_iddef _headers(self) -> dict:h: dict[str, str] = {"Content-Type": "application/json"}if self.api_key:h["X-API-Key"] = self.api_key- if self.agent_id:- h["X-OpenViking-Agent"] = self.agent_idreturn hdef _get(self, path: str, timeout: int = 10) -> dict | None:diff --git a/examples/openclaw-plugin/tests/test-tool-capture.py b/examples/openclaw-plugin/tests/test-tool-capture.pyindex 0d536ef36..47a2dfebd 100644--- a/examples/openclaw-plugin/tests/test-tool-capture.py+++ b/examples/openclaw-plugin/tests/test-tool-capture.py@@ -33,8 +33,6 @@ from rich.table import TableGATEWAY_URL = "http://127.0.0.1:18789"OPENVIKING_URL = "http://127.0.0.1:1933"-AGENT_ID = "openclaw"-console = Console()assertions: list[dict] = []@@ -52,6 +50,7 @@ def load_gateway_token() -> str:"""从 openclaw.json 读取 gateway auth token。"""try:import pathlib+cfg_path = pathlib.Path.home() / ".openclaw" / "openclaw.json"cfg = json.loads(cfg_path.read_text())return cfg.get("gateway", {}).get("auth", {}).get("token", "")@@ -100,14 +99,11 @@ def has_tool_use_in_output(data: dict) -> bool:class OVInspector:- def __init__(self, base_url: str, agent_id: str = AGENT_ID):+ def __init__(self, base_url: str):self.base_url = base_url.rstrip("/")- self.agent_id = agent_iddef _headers(self) -> dict:h: dict[str, str] = {"Content-Type": "application/json"}- if self.agent_id:- h["X-OpenViking-Agent"] = self.agent_idreturn hdef _get(self, path: str, timeout: int = 10):@@ -138,7 +134,8 @@ class OVInspector:通过检查每个 session 的 updated_at 来找到最新的。"""sessions = self.list_sessions()real_sessions = [- s for s in sessions+ s+ for s in sessionsif isinstance(s, dict) and not s.get("session_id", "").startswith("memory-store-")]if not real_sessions:@@ -210,7 +207,9 @@ def run_test(gateway_responses = []for i, msg_cfg in enumerate(TOOL_TRIGGER_MESSAGES):- console.print(f"\n[cyan]消息 {i + 1}/{len(TOOL_TRIGGER_MESSAGES)}:[/cyan] {msg_cfg['description']}")+ console.print(+ f"\n[cyan]消息 {i + 1}/{len(TOOL_TRIGGER_MESSAGES)}:[/cyan] {msg_cfg['description']}"+ )console.print(f" [dim]> {msg_cfg['input'][:80]}...[/dim]")try:@@ -223,15 +222,19 @@ def run_test(console.print(" [yellow]检测到 tool_use 在响应中[/yellow]")if verbose:- console.print(f" [dim]完整响应: {json.dumps(data, ensure_ascii=False)[:500]}[/dim]")-- gateway_responses.append({- "index": i,- "msg": msg_cfg,- "response": data,- "reply": reply,- "has_tool": has_tool,- })+ console.print(+ f" [dim]完整响应: {json.dumps(data, ensure_ascii=False)[:500]}[/dim]"+ )++ gateway_responses.append(+ {+ "index": i,+ "msg": msg_cfg,+ "response": data,+ "reply": reply,+ "has_tool": has_tool,+ }+ )check(f"消息 {i + 1} 发送成功",@@ -298,13 +301,15 @@ def run_test(all_stored_text += (part.get("text", "") or "") + "\n"if verbose:- console.print(Panel(- all_stored_text[:3000] + ("..." if len(all_stored_text) > 3000 else ""),- title="OV 存储的全部文本",- ))+ console.print(+ Panel(+ all_stored_text[:3000] + ("..." if len(all_stored_text) > 3000 else ""),+ title="OV 存储的全部文本",+ )+ )# 检查 toolUse 标记是否存在- has_tool_use_marker = bool(re.search(r'\[toolUse:', all_stored_text, re.IGNORECASE))+ has_tool_use_marker = bool(re.search(r"\[toolUse:", all_stored_text, re.IGNORECASE))check("存储文本包含 [toolUse:] 标记",has_tool_use_marker,@@ -312,7 +317,7 @@ def run_test()# 检查 toolResult 标记是否存在- has_tool_result_marker = bool(re.search(r'result\]:', all_stored_text, re.IGNORECASE))+ has_tool_result_marker = bool(re.search(r"result\]:", all_stored_text, re.IGNORECASE))check("存储文本包含 tool result 标记",has_tool_result_marker,@@ -320,7 +325,7 @@ def run_test()# 检查 assistant 标记- has_assistant = bool(re.search(r'\[assistant\]:', all_stored_text, re.IGNORECASE))+ has_assistant = bool(re.search(r"\[assistant\]:", all_stored_text, re.IGNORECASE))check("存储文本包含 [assistant] 标记",has_assistant,@@ -328,7 +333,7 @@ def run_test()# 检查 user 标记- has_user = bool(re.search(r'\[user\]:', all_stored_text, re.IGNORECASE))+ has_user = bool(re.search(r"\[user\]:", all_stored_text, re.IGNORECASE))check("存储文本包含 [user] 标记",has_user,@@ -354,9 +359,9 @@ def run_test(tool_related_lines = []for line in all_stored_text.split("\n"):stripped = line.strip()- if re.search(r'\[toolUse:', stripped, re.IGNORECASE):+ if re.search(r"\[toolUse:", stripped, re.IGNORECASE):tool_related_lines.append(("toolUse", stripped[:150]))- elif re.search(r'result\]:', stripped, re.IGNORECASE):+ elif re.search(r"result\]:", stripped, re.IGNORECASE):tool_related_lines.append(("toolResult", stripped[:150]))if tool_related_lines:@@ -402,7 +407,9 @@ def print_summary():console.print("\n[green bold]全部通过!toolUse/toolResult 捕获验证成功。[/green bold]")else:console.print(f"\n[red bold]有 {failed} 个断言失败。[/red bold]")- console.print("[yellow]注: 如果模型没有调用工具,toolUse/toolResult 标记可能不存在 — 这不代表代码有 bug。[/yellow]")+ console.print(+ "[yellow]注: 如果模型没有调用工具,toolUse/toolResult 标记可能不存在 — 这不代表代码有 bug。[/yellow]"+ )console.print("[yellow]可以在 gateway 日志中确认 afterTurn 的存储内容。[/yellow]")diff --git a/examples/openclaw-plugin/tests/ut/client.test.ts b/examples/openclaw-plugin/tests/ut/client.test.tsindex b4ab0acb5..32a3cf460 100644--- a/examples/openclaw-plugin/tests/ut/client.test.ts+++ b/examples/openclaw-plugin/tests/ut/client.test.ts@@ -34,20 +34,20 @@ describe("isMemoryUri", () => {expect(isMemoryUri("viking://user/default/memories/item-1")).toBe(true);});- it("returns true for user memory URI isolated by agent", () => {- expect(isMemoryUri("viking://user/alice/agent/work/memories/item-1")).toBe(true);+ it("returns false for deprecated user memory URI with agent segment", () => {+ expect(isMemoryUri("viking://user/alice/agent/work/memories/item-1")).toBe(false);});- it("returns true for valid agent memory URI", () => {- expect(isMemoryUri("viking://agent/memories/xyz")).toBe(true);+ it("returns false for deprecated agent memory alias", () => {+ expect(isMemoryUri("viking://agent/memories/xyz")).toBe(false);});- it("returns true for agent memory URI with space prefix", () => {- expect(isMemoryUri("viking://agent/abc123/memories/item-2")).toBe(true);+ it("returns false for deprecated agent memory URI with space prefix", () => {+ expect(isMemoryUri("viking://agent/abc123/memories/item-2")).toBe(false);});- it("returns true for agent memory URI isolated by user", () => {- expect(isMemoryUri("viking://agent/work/user/alice/memories/item-2")).toBe(true);+ it("returns false for deprecated agent memory URI with user segment", () => {+ expect(isMemoryUri("viking://agent/work/user/alice/memories/item-2")).toBe(false);});it("returns true for user memories root", () => {@@ -62,7 +62,7 @@ describe("isMemoryUri", () => {expect(isMemoryUri("viking://user/skills/abc")).toBe(false);});- it("returns false for agent instructions URI", () => {+ it("returns false for deprecated agent instructions URI", () => {expect(isMemoryUri("viking://agent/instructions/rule-1")).toBe(false);});@@ -163,13 +163,13 @@ describe("OpenVikingClient resource and skill import", () => {const fetchMock = vi.fn().mockResolvedValueOnce(okResponse({ temp_file_id: "upload_skill.md" }))- .mockResolvedValueOnce(okResponse({ uri: "viking://agent/skills/demo", name: "demo" }));+ .mockResolvedValueOnce(okResponse({ uri: "viking://user/skills/demo", name: "demo" }));vi.stubGlobal("fetch", fetchMock);const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);const result = await client.addSkill({ path: filePath, wait: true });- expect(result.uri).toBe("viking://agent/skills/demo");+ expect(result.uri).toBe("viking://user/skills/demo");expect(JSON.parse(String((fetchMock.mock.calls[1]![1] as RequestInit).body))).toMatchObject({temp_file_id: "upload_skill.md",wait: true,@@ -186,7 +186,7 @@ describe("OpenVikingClient resource and skill import", () => {const fetchMock = vi.fn().mockResolvedValueOnce(okResponse({ temp_file_id: "upload_skill.zip" }))- .mockResolvedValueOnce(okResponse({ uri: "viking://agent/skills/demo", name: "demo" }));+ .mockResolvedValueOnce(okResponse({ uri: "viking://user/skills/demo", name: "demo" }));vi.stubGlobal("fetch", fetchMock);const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);@@ -203,7 +203,7 @@ describe("OpenVikingClient resource and skill import", () => {it("addSkill posts raw skill data directly", async () => {const data = "---\nname: inline\ndescription: inline\n---\n\n# Inline\n";const fetchMock = vi.fn().mockResolvedValue(- okResponse({ uri: "viking://agent/skills/inline", name: "inline" }),+ okResponse({ uri: "viking://user/skills/inline", name: "inline" }),);vi.stubGlobal("fetch", fetchMock);@@ -224,7 +224,7 @@ describe("OpenVikingClient resource and skill import", () => {inputSchema: { type: "object", properties: {} },};const fetchMock = vi.fn().mockResolvedValue(- okResponse({ uri: "viking://agent/skills/demo-tool", name: "demo-tool" }),+ okResponse({ uri: "viking://user/skills/demo-tool", name: "demo-tool" }),);vi.stubGlobal("fetch", fetchMock);@@ -331,24 +331,57 @@ describe("OpenVikingClient resource and skill import", () => {memories_extracted: { core: 1 },});});-});-describe("OpenVikingClient tenant headers (advanced accountId / userId overrides)", () => {- it.each([- ["prefix", "prefix_main"],- ["", "main"],- ])("sends OpenClaw default agent for health checks with prefix %j", async (prefix, expected) => {- const fetchMock = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));+ it("sends memory_policy when creating a session", async () => {+ const fetchMock = vi.fn().mockResolvedValue(okResponse({ session_id: "s1" }));vi.stubGlobal("fetch", fetchMock);- const client = new OpenVikingClient("http://127.0.0.1:1933", "sk-test", prefix, 5000);- await client.healthCheck();+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);+ await client.createSession("s1", {+ memoryPolicy: {+ self: { enabled: true },+ peer: { enabled: true },+ },+ });++ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];+ expect(url).toBe("http://127.0.0.1:1933/api/v1/sessions");+ expect(JSON.parse(String(init.body))).toEqual({+ session_id: "s1",+ memory_policy: {+ self: { enabled: true },+ peer: { enabled: true },+ },+ });+ });++ it("sends memory_policy when committing a session", async () => {+ const fetchMock = vi.fn().mockResolvedValue(okResponse({+ session_id: "s1",+ status: "accepted",+ archived: true,+ }));+ vi.stubGlobal("fetch", fetchMock);++ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);+ await client.commitSession("s1", {+ memoryPolicy: {+ self: { enabled: true },+ peer: { enabled: true },+ },+ });const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];- const headers = new Headers(init.headers);- expect(headers.get("X-OpenViking-Agent")).toBe(expected);+ expect(JSON.parse(String(init.body))).toEqual({+ memory_policy: {+ self: { enabled: true },+ peer: { enabled: true },+ },+ });});+});+describe("OpenVikingClient tenant headers (advanced accountId / userId overrides)", () => {it("sends explicitly configured accountId and userId in request headers", async () => {const fetchMock = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));vi.stubGlobal("fetch", fetchMock);@@ -432,7 +465,7 @@ describe("OpenVikingClient tenant headers (advanced accountId / userId overrides});});-describe("OpenVikingClient canonical namespace policy", () => {+describe("OpenVikingClient canonical user namespace", () => {it("expands user memory alias to canonical user root by default", async () => {const fetchMock = vi.fn(async (url: string) => {if (url.endsWith("/api/v1/system/status")) {@@ -448,8 +481,6 @@ describe("OpenVikingClient canonical namespace policy", () => {const client = new OpenVikingClient("http://127.0.0.1:1933", "", "my-agent", 5000,"", "", undefined,- false,- true,);await client.find("test query", { targetUri: "viking://user/memories" }, "my-agent");@@ -460,7 +491,7 @@ describe("OpenVikingClient canonical namespace policy", () => {expect(body.target_uri).toBe("viking://user/alice/memories");});- it("expands user memory alias to user/agent root when isolateUserScopeByAgent=true", async () => {+ it("expands user memory alias to canonical user root", async () => {const fetchMock = vi.fn(async (url: string) => {if (url.endsWith("/api/v1/system/status")) {return okResponse({ user: "alice" });@@ -475,8 +506,6 @@ describe("OpenVikingClient canonical namespace policy", () => {const client = new OpenVikingClient("http://127.0.0.1:1933", "", "my-agent", 5000,"", "", undefined,- true,- true,);await client.find("test query", { targetUri: "viking://user/memories" }, "my-agent");@@ -484,10 +513,10 @@ describe("OpenVikingClient canonical namespace policy", () => {String(c[0]).endsWith("/api/v1/search/find"),)!;const body = JSON.parse(String((findCall[1] as RequestInit).body));- expect(body.target_uri).toBe("viking://user/alice/agent/my-agent/memories");+ expect(body.target_uri).toBe("viking://user/alice/memories");});- it("expands agent memory alias to canonical agent/user root by default", async () => {+ it("expands user memory alias to canonical user root by default", async () => {const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {if (url.endsWith("/api/v1/system/status")) {return okResponse({ user: "alice" });@@ -505,16 +534,16 @@ describe("OpenVikingClient canonical namespace policy", () => {false,true,);- await client.find("test", { targetUri: "viking://agent/memories" }, "shared-agent");+ await client.find("test", { targetUri: "viking://user/memories" }, "shared-agent");const findCall = fetchMock.mock.calls.find((c) =>String(c[0]).endsWith("/api/v1/search/find"),)!;const body = JSON.parse(String((findCall[1] as RequestInit).body));- expect(body.target_uri).toBe("viking://agent/shared-agent/user/alice/memories");+ expect(body.target_uri).toBe("viking://user/alice/memories");});- it("expands agent scope paths without user suffix when isolateAgentScopeByUser=false", async () => {+ it("expands user skill alias to canonical user root", async () => {const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {if (url.endsWith("/api/v1/system/status")) {return okResponse({ user: "alice" });@@ -532,16 +561,41 @@ describe("OpenVikingClient canonical namespace policy", () => {false,false,);- await client.find("test", { targetUri: "viking://agent/skills" }, "shared-agent");+ await client.find("test", { targetUri: "viking://user/skills" }, "shared-agent");++ const findCall = fetchMock.mock.calls.find((c) =>+ String(c[0]).endsWith("/api/v1/search/find"),+ )!;+ const body = JSON.parse(String((findCall[1] as RequestInit).body));+ expect(body.target_uri).toBe("viking://user/alice/skills");+ });++ it("includes peer_id when find receives peerId", async () => {+ const fetchMock = vi.fn(async (url: string) => {+ if (url.endsWith("/api/v1/system/status")) {+ return okResponse({ user: "alice" });+ }+ if (url.endsWith("/api/v1/search/find")) {+ return okResponse({ memories: [], total: 0 });+ }+ return okResponse({});+ });+ vi.stubGlobal("fetch", fetchMock);++ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "shared-agent", 5000);+ await client.find("test", {+ targetUri: "viking://user/memories",+ peerId: "telegram_12345",+ }, "shared-agent");const findCall = fetchMock.mock.calls.find((c) =>String(c[0]).endsWith("/api/v1/search/find"),)!;const body = JSON.parse(String((findCall[1] as RequestInit).body));- expect(body.target_uri).toBe("viking://agent/shared-agent/skills");+ expect(body.peer_id).toBe("telegram_12345");});- it("includes role_id when addSessionMessage receives one", async () => {+ it("includes peer_id when addSessionMessage receives one", async () => {const fetchMock = vi.fn().mockResolvedValue(okResponse({ session_id: "s1" }));vi.stubGlobal("fetch", fetchMock);@@ -557,6 +611,6 @@ describe("OpenVikingClient canonical namespace policy", () => {const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];const body = JSON.parse(String(init.body));- expect(body.role_id).toBe("telegram_12345");+ expect(body.peer_id).toBe("telegram_12345");});});diff --git a/examples/openclaw-plugin/tests/ut/config.test.ts b/examples/openclaw-plugin/tests/ut/config.test.tsindex dfea626bf..109fc59e4 100644--- a/examples/openclaw-plugin/tests/ut/config.test.ts+++ b/examples/openclaw-plugin/tests/ut/config.test.ts@@ -23,9 +23,8 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {expect(cfg.captureMode).toBe("semantic");expect(cfg.captureMaxLength).toBe(24000);expect(cfg.recallMaxContentChars).toBe(5000);- expect(cfg.agent_prefix).toBe("");- expect(cfg.isolateUserScopeByAgent).toBe(false);- expect(cfg.isolateAgentScopeByUser).toBe(false);+ expect(cfg.peer_role).toBe("none");+ expect(cfg.peer_prefix).toBe("");expect(cfg.emitStandardDiagnostics).toBe(false);});@@ -168,29 +167,32 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {expect(cfgHigh.recallMaxContentChars).toBe(10000);});- it("resolves agent_prefix from configured value", () => {- const cfg = memoryOpenVikingConfigSchema.parse({ agent_prefix: " my-agent " });- expect(cfg.agent_prefix).toBe("my-agent");+ it("accepts explicit peer_role values", () => {+ expect(memoryOpenVikingConfigSchema.parse({ peer_role: "none" }).peer_role).toBe("none");+ expect(memoryOpenVikingConfigSchema.parse({ peer_role: "assistant" }).peer_role).toBe("assistant");+ expect(memoryOpenVikingConfigSchema.parse({ peer_role: "person" }).peer_role).toBe("person");});- it("falls back to an empty prefix for empty agent_prefix", () => {- const cfg = memoryOpenVikingConfigSchema.parse({ agent_prefix: " " });- expect(cfg.agent_prefix).toBe("");+ it("throws on invalid peer_role", () => {+ expect(() =>+ memoryOpenVikingConfigSchema.parse({ peer_role: "agent" }),+ ).toThrow('peer_role must be "none", "assistant", or "person"');});- it("normalizes legacy 'default' agent_prefix to an empty prefix", () => {- const cfg = memoryOpenVikingConfigSchema.parse({ agent_prefix: "default" });- expect(cfg.agent_prefix).toBe("");+ it("resolves peer_prefix from configured value", () => {+ const cfg = memoryOpenVikingConfigSchema.parse({ peer_prefix: " my-agent " });+ expect(cfg.peer_role).toBe("none");+ expect(cfg.peer_prefix).toBe("my-agent");});- it("migrates legacy agentId to agent_prefix", () => {- const cfg = memoryOpenVikingConfigSchema.parse({ agentId: "legacy-agent" });- expect(cfg.agent_prefix).toBe("legacy-agent");+ it("falls back to an empty prefix for empty peer_prefix", () => {+ const cfg = memoryOpenVikingConfigSchema.parse({ peer_prefix: " " });+ expect(cfg.peer_prefix).toBe("");});- it("agent_prefix takes precedence over legacy agentId", () => {- const cfg = memoryOpenVikingConfigSchema.parse({ agentId: "old", agent_prefix: "new" });- expect(cfg.agent_prefix).toBe("new");+ it("normalizes legacy 'default' peer_prefix to an empty prefix", () => {+ const cfg = memoryOpenVikingConfigSchema.parse({ peer_prefix: "default" });+ expect(cfg.peer_prefix).toBe("");});it("parses accountId and trims whitespace", () => {@@ -218,56 +220,15 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {expect(cfg.userId).toBe("");});- it("default user-key flow does not require accountId, userId, or agentScopeMode", () => {+ it("default user-key flow does not require accountId or userId", () => {const cfg = memoryOpenVikingConfigSchema.parse({baseUrl: "http://127.0.0.1:1933",apiKey: "sk-user",- agent_prefix: "coding-agent",+ peer_role: "assistant",+ peer_prefix: "coding-agent",});expect(cfg.accountId).toBe("");expect(cfg.userId).toBe("");- expect(cfg.agentScopeMode).toBe("agent");- expect(cfg.isolateUserScopeByAgent).toBe(false);- expect(cfg.isolateAgentScopeByUser).toBe(false);- });-- it("defaults namespace policy to the current server-side false/false policy", () => {- const cfg = memoryOpenVikingConfigSchema.parse({});- expect(cfg.agentScopeMode).toBe("agent");- expect(cfg.isolateUserScopeByAgent).toBe(false);- expect(cfg.isolateAgentScopeByUser).toBe(false);- });-- it("maps deprecated agentScopeMode 'agent' to false/false namespace policy", () => {- const cfg = memoryOpenVikingConfigSchema.parse({ agentScopeMode: "agent" });- expect(cfg.agentScopeMode).toBe("agent");- expect(cfg.isolateUserScopeByAgent).toBe(false);- expect(cfg.isolateAgentScopeByUser).toBe(false);- });-- it("falls back to user_agent for invalid agentScopeMode", () => {- const cfg = memoryOpenVikingConfigSchema.parse({ agentScopeMode: "invalid" });- expect(cfg.agentScopeMode).toBe("agent");- expect(cfg.isolateUserScopeByAgent).toBe(false);- expect(cfg.isolateAgentScopeByUser).toBe(false);- });-- it("maps explicit deprecated agentScopeMode 'user_agent' to false/true namespace policy", () => {- const cfg = memoryOpenVikingConfigSchema.parse({ agentScopeMode: "user_agent" });- expect(cfg.agentScopeMode).toBe("user_agent");- expect(cfg.isolateUserScopeByAgent).toBe(false);- expect(cfg.isolateAgentScopeByUser).toBe(true);- });-- it("explicit namespace policy overrides deprecated agentScopeMode", () => {- const cfg = memoryOpenVikingConfigSchema.parse({- agentScopeMode: "agent",- isolateUserScopeByAgent: true,- isolateAgentScopeByUser: true,- });- expect(cfg.agentScopeMode).toBe("agent");- expect(cfg.isolateUserScopeByAgent).toBe(true);- expect(cfg.isolateAgentScopeByUser).toBe(true);});it("accepts deprecated serverAuthMode without exposing it in parsed config", () => {diff --git a/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.tsindex 3e07edd90..0d5cd029d 100644--- a/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts+++ b/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts@@ -35,6 +35,7 @@ function makeEngine(opts?: {: vi.fn().mockResolvedValue(undefined);const client = {+ ensureSession: vi.fn().mockResolvedValue(true),addSessionMessage,commitSession: vi.fn().mockResolvedValue({status: "accepted",@@ -70,6 +71,7 @@ function makeEngine(opts?: {return {engine,client: client as unknown as {+ ensureSession: ReturnType<typeof vi.fn>;addSessionMessage: ReturnType<typeof vi.fn>;commitSession: ReturnType<typeof vi.fn>;getSession: ReturnType<typeof vi.fn>;@@ -221,7 +223,7 @@ describe("context-engine afterTurn()", () => {);});- it("passes sanitized senderId as role_id", async () => {+ it("does not pass peer_id by default", async () => {const { engine, client } = makeEngine();await engine.afterTurn!({@@ -232,8 +234,58 @@ describe("context-engine afterTurn()", () => {runtimeContext: { senderId: "telegram:12345" },});+ expect(client.addSessionMessage).toHaveBeenCalledTimes(1);+ expect(client.addSessionMessage.mock.calls[0][5]).toBeUndefined();+ });++ it("passes sanitized senderId as peer_id when peer_role is person", async () => {+ const { engine, client } = makeEngine({+ cfgOverrides: { peer_role: "person" },+ });++ await engine.afterTurn!({+ sessionId: "s1",+ sessionFile: "",+ messages: [{ role: "user", content: "hello world" }],+ prePromptMessageCount: 0,+ runtimeContext: { senderId: "telegram:12345" },+ });+expect(client.addSessionMessage).toHaveBeenCalledTimes(1);expect(client.addSessionMessage.mock.calls[0][5]).toBe("telegram_12345");+ expect(client.ensureSession).toHaveBeenCalledWith(+ "s1",+ {+ memoryPolicy: {+ self: { enabled: true },+ peer: { enabled: true },+ },+ },+ "test-agent",+ );+ });++ it("passes runtime agent as peer_id only for assistant messages when peer_role is assistant", async () => {+ const { engine, client } = makeEngine({+ cfgOverrides: { peer_role: "assistant" },+ });++ await engine.afterTurn!({+ sessionId: "s1",+ sessionFile: "",+ messages: [+ { role: "user", content: "hello world" },+ { role: "assistant", content: "hi there" },+ ],+ prePromptMessageCount: 0,+ runtimeContext: { senderId: "telegram:12345" },+ });++ expect(client.addSessionMessage).toHaveBeenCalledTimes(2);+ expect(client.addSessionMessage.mock.calls[0][1]).toBe("user");+ expect(client.addSessionMessage.mock.calls[0][5]).toBeUndefined();+ expect(client.addSessionMessage.mock.calls[1][1]).toBe("assistant");+ expect(client.addSessionMessage.mock.calls[1][5]).toBe("test-agent");});it("sanitizes <relevant-memories> from user content but not from assistant", async () => {@@ -305,6 +357,31 @@ describe("context-engine afterTurn()", () => {expect(commitCall[1]).toMatchObject({ wait: false });});+ it("passes peer memory policy to commit when peer_role is person", async () => {+ const { engine, client } = makeEngine({+ commitTokenThreshold: 100,+ getSession: { pending_tokens: 5000 },+ cfgOverrides: { peer_role: "person" },+ });++ await engine.afterTurn!({+ sessionId: "s1",+ sessionFile: "",+ messages: [{ role: "user", content: "remember my table tennis preference" }],+ prePromptMessageCount: 0,+ runtimeContext: { senderId: "openclaw-tui" },+ });++ expect(client.commitSession).toHaveBeenCalledTimes(1);+ expect(client.commitSession.mock.calls[0][1]).toMatchObject({+ wait: false,+ memoryPolicy: {+ self: { enabled: true },+ peer: { enabled: true },+ },+ });+ });+it("catches errors without throwing", async () => {const { engine, logger } = makeEngine({addSessionMessageError: new Error("network timeout"),diff --git a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.tsindex a4b6fa3b1..1ebedd38a 100644--- a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts+++ b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts@@ -151,6 +151,225 @@ describe("context-engine assemble()", () => {expect(result.systemPromptAddition).toBeUndefined();});+ it("passes sender peer_id to transformContext auto-recall when peer_role is person", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ json: async () => ({ status: "ok" }),+ }),+ );+ try {+ const { engine, client } = makeEngine(+ {+ latest_archive_overview: "",+ pre_archive_abstracts: [],+ messages: [],+ estimatedTokens: 0,+ stats: makeStats(),+ },+ {+ cfgOverrides: {+ autoRecall: true,+ peer_role: "person",+ },+ },+ );++ const sourceMessages = [+ { role: "assistant", content: [{ type: "text", text: "Previous answer." }] },+ { role: "user", content: "what backend language should we use?" },+ ];++ await engine.assemble({+ sessionId: "session-person-peer",+ runtimeContext: { senderId: "wx/user-01@abc" },+ messages: sourceMessages,+ });++ expect(client.find).toHaveBeenCalledTimes(2);+ for (const call of client.find.mock.calls) {+ expect(call[1]).toMatchObject({ peerId: "wx_user-01_abc" });+ }+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it("uses prompt metadata sender_id for main assemble peer auto-recall when runtimeContext is missing", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ json: async () => ({ status: "ok" }),+ }),+ );+ try {+ const { engine, client } = makeEngine(+ new Error("should be replaced"),+ {+ cfgOverrides: {+ autoRecall: true,+ peer_role: "person",+ recallPreferAbstract: true,+ },+ },+ );+ client.getSessionContext.mockRejectedValueOnce(+ new Error("OpenViking request failed [NOT_FOUND]: Session not found"),+ );+ client.find+ .mockResolvedValueOnce({+ memories: [+ {+ uri: "viking://user/acme/peers/ou_bcc/memories/profile.md",+ level: 2,+ category: "profile",+ abstract: "# 秦浩杰\n- 正在维护的项目:openviking",+ score: 0.92,+ },+ ],+ total: 1,+ })+ .mockResolvedValueOnce({ memories: [], total: 0 });++ const prompt = [+ "Conversation info (untrusted metadata):",+ "```json",+ JSON.stringify({+ message_id: "om_1",+ sender_id: "ou_bcc",+ sender: "秦浩杰",+ is_group_chat: true,+ }),+ "```",+ "",+ "Sender (untrusted metadata):",+ "```json",+ JSON.stringify({+ id: "ou_bcc",+ name: "秦浩杰",+ }),+ "```",+ "",+ "[message_id: om_1]",+ "秦浩杰: 我是谁",+ "",+ "[System: mention metadata]",+ ].join("\n");++ const result = await engine.assemble({+ sessionId: "session-main-prompt-peer",+ sessionKey: "agent:main:feishu:group:oc_123",+ messages: [],+ prompt,+ });++ expect(client.find).toHaveBeenCalledTimes(2);+ for (const call of client.find.mock.calls) {+ expect(call[1]).toMatchObject({ peerId: "ou_bcc" });+ }+ expect(result.messages[0]?.role).toBe("user");+ expect(result.messages[0]?.content).toContain("Source: openviking-auto-recall");+ expect(result.messages[0]?.content).toContain("正在维护的项目:openviking");+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it("prefers runtimeContext senderId over prompt metadata for main assemble recall", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ json: async () => ({ status: "ok" }),+ }),+ );+ try {+ const { engine, client } = makeEngine(+ {+ latest_archive_overview: "",+ pre_archive_abstracts: [],+ messages: [],+ estimatedTokens: 0,+ stats: makeStats(),+ },+ {+ cfgOverrides: {+ autoRecall: true,+ peer_role: "person",+ },+ },+ );++ await engine.assemble({+ sessionId: "session-main-runtime-peer",+ runtimeContext: { senderId: "trusted/runtime-user" },+ messages: [],+ prompt: [+ "Conversation info (untrusted metadata):",+ "```json",+ JSON.stringify({ sender_id: "fake-prompt-user", sender: "Prompt User" }),+ "```",+ "",+ "[message_id: om_1]",+ "Prompt User: 我喜欢什么水果?",+ ].join("\n"),+ });++ expect(client.find).toHaveBeenCalledTimes(2);+ for (const call of client.find.mock.calls) {+ expect(call[1]).toMatchObject({ peerId: "trusted_runtime-user" });+ }+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it("passes assistant peer_id to transformContext auto-recall when peer_role is assistant", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ json: async () => ({ status: "ok" }),+ }),+ );+ try {+ const { engine, client } = makeEngine(+ {+ latest_archive_overview: "",+ pre_archive_abstracts: [],+ messages: [],+ estimatedTokens: 0,+ stats: makeStats(),+ },+ {+ cfgOverrides: {+ autoRecall: true,+ peer_role: "assistant",+ },+ },+ );++ const sourceMessages = [+ { role: "assistant", content: [{ type: "text", text: "Previous answer." }] },+ { role: "user", content: "what backend language should we use?" },+ ];++ await engine.assemble({+ sessionId: "session-assistant-peer",+ messages: sourceMessages,+ });++ expect(client.find).toHaveBeenCalledTimes(2);+ for (const call of client.find.mock.calls) {+ expect(call[1]).toMatchObject({ peerId: "agent:session-assistant-peer" });+ }+ } finally {+ vi.unstubAllGlobals();+ }+ });+it("passes through transformContext messages when the latest message is not user", async () => {const { engine, getClient } = makeEngine({diff --git a/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-compact.test.tsindex 096a9ecf4..e6ce44ac5 100644--- a/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts+++ b/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts@@ -15,12 +15,16 @@ function makeLogger() {};}-function makeEngine(commitResult: unknown, opts?: { throwError?: Error }) {+function makeEngine(+ commitResult: unknown,+ opts?: { throwError?: Error; cfgOverrides?: Record<string, unknown> },+) {const cfg = memoryOpenVikingConfigSchema.parse({mode: "remote",baseUrl: "http://127.0.0.1:1933",autoCapture: false,autoRecall: false,+ ...(opts?.cfgOverrides ?? {}),});const logger = makeLogger();@@ -116,6 +120,27 @@ describe("context-engine commitOVSession()", () => {expect(client.commitSession.mock.calls[0][1]).toMatchObject({ wait: true });});+ it("passes peer memory policy when peer_role is person", async () => {+ const { engine, client } = makeEngine(+ {+ status: "completed",+ archived: false,+ memories_extracted: {},+ },+ { cfgOverrides: { peer_role: "person" } },+ );++ await engine.commitOVSession({ sessionId: "s1" });++ expect(client.commitSession.mock.calls[0][1]).toMatchObject({+ wait: true,+ memoryPolicy: {+ self: { enabled: true },+ peer: { enabled: true },+ },+ });+ });+it("uses sessionKey-derived OV session ID for commitOVSession", async () => {const { engine, client, resolveAgentId } = makeEngine({status: "completed",@@ -303,6 +328,27 @@ describe("context-engine compact()", () => {expect(client.commitSession.mock.calls[0][1]).toMatchObject({ wait: true });});+ it("compact passes peer memory policy when peer_role is person", async () => {+ const { engine, client } = makeEngine(+ {+ status: "completed",+ archived: true,+ memories_extracted: {},+ },+ { cfgOverrides: { peer_role: "person" } },+ );++ await engine.compact({ sessionId: "s1", sessionFile: "" });++ expect(client.commitSession.mock.calls[0][1]).toMatchObject({+ wait: true,+ memoryPolicy: {+ self: { enabled: true },+ peer: { enabled: true },+ },+ });+ });+it("logs memory extraction count on success", async () => {const { engine, logger } = makeEngine({status: "completed",diff --git a/examples/openclaw-plugin/tests/ut/index-utils.test.ts b/examples/openclaw-plugin/tests/ut/index-utils.test.tsindex fde800dbf..97cb05eda 100644--- a/examples/openclaw-plugin/tests/ut/index-utils.test.ts+++ b/examples/openclaw-plugin/tests/ut/index-utils.test.ts@@ -2,45 +2,45 @@ import { describe, expect, it } from "vitest";import {prepareRecallQuery,- sanitizeOpenVikingAgentIdHeader,+ sanitizeRuntimeAgentId,createSessionAgentResolver,} from "../../index.js";-describe("sanitizeOpenVikingAgentIdHeader", () => {+describe("sanitizeRuntimeAgentId", () => {it("keeps clean alphanumeric+dash+underscore strings", () => {- expect(sanitizeOpenVikingAgentIdHeader("my-agent_v2")).toBe("my-agent_v2");+ expect(sanitizeRuntimeAgentId("my-agent_v2")).toBe("my-agent_v2");});it("replaces special characters with underscore", () => {- expect(sanitizeOpenVikingAgentIdHeader("agent:role:v1")).toBe("agent_role_v1");+ expect(sanitizeRuntimeAgentId("agent:role:v1")).toBe("agent_role_v1");});it("collapses multiple underscores", () => {- expect(sanitizeOpenVikingAgentIdHeader("a::b:::c")).toBe("a_b_c");+ expect(sanitizeRuntimeAgentId("a::b:::c")).toBe("a_b_c");});it("strips leading/trailing underscores", () => {- expect(sanitizeOpenVikingAgentIdHeader("_agent_")).toBe("agent");+ expect(sanitizeRuntimeAgentId("_agent_")).toBe("agent");});it("returns 'default' for empty string", () => {- expect(sanitizeOpenVikingAgentIdHeader("")).toBe("default");+ expect(sanitizeRuntimeAgentId("")).toBe("default");});it("returns 'default' for whitespace-only", () => {- expect(sanitizeOpenVikingAgentIdHeader(" ")).toBe("default");+ expect(sanitizeRuntimeAgentId(" ")).toBe("default");});it("returns 'ov_agent' for all-symbol input", () => {- expect(sanitizeOpenVikingAgentIdHeader("@#$%")).toBe("ov_agent");+ expect(sanitizeRuntimeAgentId("@#$%")).toBe("ov_agent");});it("handles spaces by replacing with underscore", () => {- expect(sanitizeOpenVikingAgentIdHeader("my agent")).toBe("my_agent");+ expect(sanitizeRuntimeAgentId("my agent")).toBe("my_agent");});it("preserves mixed case", () => {- expect(sanitizeOpenVikingAgentIdHeader("MyAgent")).toBe("MyAgent");+ expect(sanitizeRuntimeAgentId("MyAgent")).toBe("MyAgent");});});diff --git a/examples/openclaw-plugin/tests/ut/plugin-normal-flow-real-server.test.ts b/examples/openclaw-plugin/tests/ut/plugin-normal-flow-real-server.test.tsindex dba0d3347..49ae3f43f 100644--- a/examples/openclaw-plugin/tests/ut/plugin-normal-flow-real-server.test.ts+++ b/examples/openclaw-plugin/tests/ut/plugin-normal-flow-real-server.test.ts@@ -232,10 +232,13 @@ describe("plugin normal flow with healthy backend", () => {messages: [{ role: "user", content: "fallback" }],});- expect(assembled.messages[0]).toEqual({- role: "user",- content: "[Session History Summary]\nEarlier work focused on backend stack choices.",- });+ expect(assembled.messages[0]?.role).toBe("user");+ const firstAssembledMessage = String(assembled.messages[0]?.content);+ expect(firstAssembledMessage).toContain("Source: openviking-auto-recall");+ expect(firstAssembledMessage).toContain("User prefers Rust for backend tasks.");+ expect(firstAssembledMessage).toContain(+ "[Session History Summary]\nEarlier work focused on backend stack choices.",+ );expect(assembled.messages[1]).toEqual({role: "assistant",content: [{ type: "text", text: "Stored answer from OpenViking." }],diff --git a/examples/openclaw-plugin/tests/ut/setup-command.test.ts b/examples/openclaw-plugin/tests/ut/setup-command.test.tsindex 6a633f791..8f39ce138 100644--- a/examples/openclaw-plugin/tests/ut/setup-command.test.ts+++ b/examples/openclaw-plugin/tests/ut/setup-command.test.ts@@ -6,14 +6,14 @@ describe("openviking setup agent prefix validation", () => {it.each(["", " ", "main", "foo_main", "foo-main", "Foo_123"])("accepts valid agent prefix %j",(value) => {- expect(__test__.isValidAgentPrefixInput(value)).toBe(true);+ expect(__test__.isValidPeerPrefixInput(value)).toBe(true);},);it.each(["foo.bar", "foo/bar", "foo bar", "中文", "foo:bar"])("rejects invalid agent prefix %j",(value) => {- expect(__test__.isValidAgentPrefixInput(value)).toBe(false);+ expect(__test__.isValidPeerPrefixInput(value)).toBe(false);},);});diff --git a/examples/openclaw-plugin/tests/ut/tools.test.ts b/examples/openclaw-plugin/tests/ut/tools.test.tsindex 03415797e..f9f03d5f6 100644--- a/examples/openclaw-plugin/tests/ut/tools.test.ts+++ b/examples/openclaw-plugin/tests/ut/tools.test.ts@@ -247,6 +247,41 @@ describe("Tool: memory_recall (registration)", () => {}});+ it("passes sender peer_id to memory_recall when peer_role is person", async () => {+ const fetchMock = vi.fn(async (url: string) => {+ const requestUrl = new URL(url);+ if (requestUrl.pathname === "/api/v1/system/status") {+ return okResponse({ user: "default" });+ }+ if (requestUrl.pathname === "/api/v1/search/find") {+ return okResponse({ memories: [], resources: [], skills: [], total: 0 });+ }+ return okResponse({});+ });+ vi.stubGlobal("fetch", fetchMock);++ const { factoryTools, api } = setupPlugin(undefined, {+ peer_role: "person",+ });+ contextEnginePlugin.register(api as any);+ const tool = factoryTools.get("memory_recall")!({+ sessionId: "test-session",+ requesterSenderId: "wx/user-01@abc",+ });++ await tool.execute("tc-memory-recall-peer", {+ query: "backend preference",+ }) as ToolResult;++ const findBodies = fetchMock.mock.calls+ .filter(([calledUrl]) => String(calledUrl).includes("/api/v1/search/find"))+ .map((call) => JSON.parse(String((call[1] as RequestInit).body)));+ expect(findBodies).toHaveLength(2);+ for (const body of findBodies) {+ expect(body.peer_id).toBe("wx_user-01_abc");+ }+ });+it("applies recallMaxInjectedChars to explicit memory_recall output", async () => {const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {const requestUrl = new URL(url);@@ -319,7 +354,7 @@ describe("Tool: memory_store (behavioral)", () => {expect(store!.description).toContain("threshold/commit dependent");});- it("uses requesterSenderId to populate role_id for user writes", async () => {+ it("uses requesterSenderId to populate peer_id for user writes", async () => {const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {if (url.endsWith("/api/v1/system/status")) {return okResponse({ user: "default" });@@ -338,7 +373,7 @@ describe("Tool: memory_store (behavioral)", () => {});vi.stubGlobal("fetch", fetchMock);- const { factoryTools, api } = setupPlugin();+ const { factoryTools, api } = setupPlugin(undefined, { peer_role: "person" });contextEnginePlugin.register(api as any);const factory = factoryTools.get("memory_store");expect(factory).toBeDefined();@@ -358,10 +393,105 @@ describe("Tool: memory_store (behavioral)", () => {const [, init] = messageCall as [string, RequestInit];const body = JSON.parse(String(init.body));expect(body.role).toBe("user");- expect(body.role_id).toBe("wx_user-01_abc");+ expect(body.peer_id).toBe("wx_user-01_abc");expect(result.content[0]!.text).toContain("committed 1 memories");expect(result.details.action).toBe("stored");expect(result.details.memoriesCount).toBe(1);++ const createCall = fetchMock.mock.calls.find(([url]) =>+ String(url).endsWith("/api/v1/sessions"),+ );+ expect(createCall).toBeDefined();+ expect(JSON.parse(String((createCall![1] as RequestInit).body))).toMatchObject({+ memory_policy: {+ self: { enabled: true },+ peer: { enabled: true },+ },+ });++ const commitCall = fetchMock.mock.calls.find(([url]) =>+ String(url).endsWith("/commit"),+ );+ expect(commitCall).toBeDefined();+ expect(JSON.parse(String((commitCall![1] as RequestInit).body))).toMatchObject({+ memory_policy: {+ self: { enabled: true },+ peer: { enabled: true },+ },+ });+ });++ it("does not populate peer_id for user writes by default", async () => {+ const fetchMock = vi.fn(async (url: string) => {+ if (url.endsWith("/api/v1/system/status")) {+ return okResponse({ user: "default" });+ }+ if (url.includes("/messages")) {+ return okResponse({ session_id: "sess-1" });+ }+ if (url.endsWith("/commit")) {+ return okResponse({ status: "completed", archived: false, memories_extracted: { core: 1 } });+ }+ return okResponse({});+ });+ vi.stubGlobal("fetch", fetchMock);++ const { factoryTools, api } = setupPlugin();+ contextEnginePlugin.register(api as any);+ const tool = factoryTools.get("memory_store")!({+ sessionId: "runtime-session",+ sessionKey: "agent:main:main",+ requesterSenderId: "wx/user-01@abc",+ });++ await tool.execute("tc-memory-store-default-peer", { text: "hello from tool" });++ const messageCall = fetchMock.mock.calls.find(([url]) =>+ String(url).includes("/api/v1/sessions/") && String(url).includes("/messages"),+ );+ expect(messageCall).toBeDefined();+ const [, init] = messageCall as [string, RequestInit];+ const body = JSON.parse(String(init.body));+ expect(body.role).toBe("user");+ expect(body.peer_id).toBeUndefined();+ });++ it("uses runtime agent as peer_id for assistant writes when peer_role is assistant", async () => {+ const fetchMock = vi.fn(async (url: string) => {+ if (url.endsWith("/api/v1/system/status")) {+ return okResponse({ user: "default" });+ }+ if (url.includes("/messages")) {+ return okResponse({ session_id: "sess-1" });+ }+ if (url.endsWith("/commit")) {+ return okResponse({ status: "completed", archived: false, memories_extracted: { core: 1 } });+ }+ return okResponse({});+ });+ vi.stubGlobal("fetch", fetchMock);++ const { factoryTools, api } = setupPlugin(undefined, { peer_role: "assistant" });+ contextEnginePlugin.register(api as any);+ const tool = factoryTools.get("memory_store")!({+ sessionId: "runtime-session",+ sessionKey: "agent:worker:main",+ requesterSenderId: "wx/user-01@abc",+ });++ await tool.execute("tc-memory-store-assistant-peer", {+ text: "assistant note",+ role: "assistant",+ });++ const messageCall = fetchMock.mock.calls.find(([url]) =>+ String(url).includes("/api/v1/sessions/") && String(url).includes("/messages"),+ );+ expect(messageCall).toBeDefined();+ const [, init] = messageCall as [string, RequestInit];+ const body = JSON.parse(String(init.body));+ expect(body.role).toBe("assistant");+ expect(body.peer_id).toBe("worker");});it("uses a temporary session by default instead of the current tool session", async () => {@@ -821,7 +951,7 @@ describe("Tool: ov_search (behavioral)", () => {skills: [{context_type: "skill",- uri: "viking://agent/skills/install-openviking-memory",+ uri: "viking://user/skills/install-openviking-memory",level: 0,score: 0.7,category: "",@@ -854,7 +984,40 @@ describe("Tool: ov_search (behavioral)", () => {.filter((call) => String(call[0]).endsWith("/api/v1/search/find")).map((call) => JSON.parse(String((call[1] as RequestInit).body)));expect(findBodies.some((body) => body.target_uri === "viking://resources")).toBe(true);- expect(findBodies.some((body) => String(body.target_uri).startsWith("viking://agent/") && String(body.target_uri).endsWith("/skills"))).toBe(true);+ expect(findBodies.some((body) => String(body.target_uri).startsWith("viking://user/") && String(body.target_uri).endsWith("/skills"))).toBe(true);+ });++ it("passes assistant peer_id to ov_search when peer_role is assistant", async () => {+ const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {+ if (url.endsWith("/api/v1/system/status")) {+ return okResponse({ user: "default" });+ }+ if (url.includes("/api/v1/fs/ls")) {+ return okResponse([]);+ }+ if (url.endsWith("/api/v1/search/find")) {+ return okResponse({ memories: [], resources: [], skills: [], total: 0 });+ }+ return okResponse({});+ });+ vi.stubGlobal("fetch", fetchMock);++ const { factoryTools, api } = setupPlugin(undefined, { peer_role: "assistant" });+ contextEnginePlugin.register(api as any);+ const search = factoryTools.get("ov_search")!({+ sessionId: "runtime-session",+ agentId: "worker",+ });++ await search.execute("tc-ov-search-peer", { query: "OpenViking install" }) as ToolResult;++ const findBodies = fetchMock.mock.calls+ .filter((call) => String(call[0]).endsWith("/api/v1/search/find"))+ .map((call) => JSON.parse(String((call[1] as RequestInit).body)));+ expect(findBodies).toHaveLength(2);+ for (const body of findBodies) {+ expect(body.peer_id).toBe("worker");+ }});it("returns partial results when one default scope search fails", async () => {@@ -1069,31 +1232,6 @@ describe("Plugin registration", () => {expect(search.text).toContain("Usage: /ov-search");});- it("search command propagates agent identity when command ctx includes it", async () => {- const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {- if (url.endsWith("/api/v1/search/find")) {- return okResponse({ memories: [], resources: [], skills: [], total: 0 });- }- return okResponse({});- });- vi.stubGlobal("fetch", fetchMock);-- const { commands, api } = setupPlugin();- contextEnginePlugin.register(api as any);-- await commands.get("ov-search")!.handler({- args: "test query --uri viking://resources",- commandBody: "/ov-search",- agentId: "worker",- sessionId: "session-1",- sessionKey: "agent:worker:session-1",- });-- const [, init] = fetchMock.mock.calls.find((call) => String(call[0]).endsWith("/api/v1/search/find")) as [string, RequestInit];- const headers = new Headers(init.headers);- expect(headers.get("X-OpenViking-Agent")).toBe("worker");- });-it("search command propagates configured tenant headers", async () => {const fetchMock = vi.fn(async (url: string) => {if (url.endsWith("/api/v1/search/find")) {@@ -1123,7 +1261,6 @@ describe("Plugin registration", () => {const headers = new Headers(init.headers);expect(headers.get("X-OpenViking-Account")).toBe("acct-shared");expect(headers.get("X-OpenViking-User")).toBe("alice");- expect(headers.get("X-OpenViking-Agent")).toBe("worker");});it("add_resource propagates configured tenant headers", async () => {@@ -1189,7 +1326,7 @@ describe("Plugin registration", () => {it("add_skill posts skill imports to the skills API", async () => {const fetchMock = vi.fn(async () =>- okResponse({ uri: "viking://agent/skills/demo", name: "demo" }),+ okResponse({ uri: "viking://user/skills/demo", name: "demo" }),);vi.stubGlobal("fetch", fetchMock);diff --git a/examples/opencode-memory-plugin/INSTALL-ZH.md b/examples/opencode-memory-plugin/INSTALL-ZH.mdindex 216d2916c..6c40783e2 100644--- a/examples/opencode-memory-plugin/INSTALL-ZH.md+++ b/examples/opencode-memory-plugin/INSTALL-ZH.md@@ -94,6 +94,9 @@ cp examples/opencode-memory-plugin/.gitignore ~/.config/opencode/plugins/.gitign{"endpoint": "http://localhost:1933","apiKey": "",+ "account": "",+ "user": "",+ "peerId": "","enabled": true,"timeoutMs": 30000,"autoCommit": {@@ -107,6 +110,8 @@ cp examples/opencode-memory-plugin/.gitignore ~/.config/opencode/plugins/.gitign- `endpoint`: OpenViking 服务地址- `apiKey`: 可留空,推荐用环境变量提供+- `account` / `user`: 多租户身份头+- `peerId`: 可选;作为请求级 `peer_id` 用于 recall/search 和 session message 写入- `enabled`: 是否启用插件- `timeoutMs`: 普通请求超时时间- `autoCommit.intervalMinutes`: 自动提交 session 的周期diff --git a/examples/opencode-memory-plugin/README.md b/examples/opencode-memory-plugin/README.mdindex 6e7e96e82..2017ec3a8 100644--- a/examples/opencode-memory-plugin/README.md+++ b/examples/opencode-memory-plugin/README.md@@ -89,6 +89,7 @@ Example config:"apiKey": "","account": "default","user": "opencode",+ "peerId": "","enabled": true,"timeoutMs": 30000,"autoCommit": {@@ -99,8 +100,9 @@ Example config:````account` and `user` are sent as `X-OpenViking-Account` and `X-OpenViking-User` tenant headers on every plugin API request; leave them empty to omit the headers.+`peerId` is sent as request-level `peer_id` for memory recall/search and captured session messages; leave it empty to preserve existing behavior.-The environment variables `OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, and `OPENVIKING_USER` take precedence over the config file.+The environment variables `OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, and `OPENVIKING_PEER_ID` take precedence over the config file.## Runtime Filesdiff --git a/examples/opencode-memory-plugin/README_CN.md b/examples/opencode-memory-plugin/README_CN.mdindex cbf049f21..61786acd2 100644--- a/examples/opencode-memory-plugin/README_CN.md+++ b/examples/opencode-memory-plugin/README_CN.md@@ -89,6 +89,7 @@ export OPENVIKING_USER="opencode""apiKey": "","account": "default","user": "opencode",+ "peerId": "","enabled": true,"timeoutMs": 30000,"autoCommit": {@@ -99,8 +100,9 @@ export OPENVIKING_USER="opencode"````account` 和 `user` 会作为 `X-OpenViking-Account` 与 `X-OpenViking-User` 租户头随每次插件 API 请求发送;留空则不会附加这些头。+`peerId` 会作为请求级 `peer_id` 用于 memory recall/search 和 session message 写入;留空则保持现有行为。-环境变量 `OPENVIKING_API_KEY`、`OPENVIKING_ACCOUNT` 和 `OPENVIKING_USER` 优先于配置文件。+环境变量 `OPENVIKING_API_KEY`、`OPENVIKING_ACCOUNT`、`OPENVIKING_USER` 和 `OPENVIKING_PEER_ID` 优先于配置文件。## 运行时文件diff --git a/examples/opencode-memory-plugin/openviking-memory.ts b/examples/opencode-memory-plugin/openviking-memory.tsindex f8fe1718e..21770e2fc 100644--- a/examples/opencode-memory-plugin/openviking-memory.ts+++ b/examples/opencode-memory-plugin/openviking-memory.ts@@ -279,6 +279,7 @@ interface OpenVikingConfig {apiKey: stringaccount: stringuser: string+ peerId: stringenabled: booleantimeoutMs: numberautoCommit?: {@@ -362,6 +363,7 @@ const DEFAULT_CONFIG: OpenVikingConfig = {apiKey: "",account: "",user: "",+ peerId: "",enabled: true,timeoutMs: 30000,autoCommit: {@@ -451,6 +453,9 @@ function loadConfig(): OpenVikingConfig {if (process.env.OPENVIKING_USER) {config.user = process.env.OPENVIKING_USER}+ if (process.env.OPENVIKING_PEER_ID) {+ config.peerId = process.env.OPENVIKING_PEER_ID+ }return config}@@ -477,6 +482,9 @@ function loadConfig(): OpenVikingConfig {if (process.env.OPENVIKING_USER) {config.user = process.env.OPENVIKING_USER}+ if (process.env.OPENVIKING_PEER_ID) {+ config.peerId = process.env.OPENVIKING_PEER_ID+ }if (config.autoCommit) {config.autoCommit.intervalMinutes = getAutoCommitIntervalMinutes(config)}@@ -1345,10 +1353,18 @@ async function addMessageToSession(config: OpenVikingConfig,): Promise<boolean> {try {+ const body: { role: "user" | "assistant"; content: string; peer_id?: string } = {+ role,+ content,+ }+ const peerId = config.peerId.trim()+ if (peerId) {+ body.peer_id = peerId+ }const response = await makeRequest<OpenVikingResponse<void>>(config, {method: "POST",endpoint: `/api/v1/sessions/${ovSessionId}/messages`,- body: { role, content },+ body,timeoutMs: 5000,})unwrapResponse(response)@@ -1639,12 +1655,21 @@ function extractMessageText(parts: { type: string; text?: string }[]): string |/** Perform search against OpenViking with a timeout guard. Returns empty on any failure. */async function performRecallSearch(config: OpenVikingConfig, query: string): Promise<RecallSearchItem[]> {try {+ const body: { query: string; limit: number; mode: string; peer_id?: string } = {+ query: query.slice(0, 4000),+ limit: 20,+ mode: "auto",+ }+ const peerId = config.peerId.trim()+ if (peerId) {+ body.peer_id = peerId+ }const response = await makeRequest<OpenVikingResponse<{ memories?: RecallSearchItem[]; results?: RecallSearchItem[] }>>(config,{method: "POST",endpoint: "/api/v1/search/find",- body: { query: query.slice(0, 4000), limit: 20, mode: "auto" },+ body,timeoutMs: AUTO_RECALL_TIMEOUT_MS,},)@@ -2006,7 +2031,7 @@ export const OpenVikingMemoryPlugin = async (input: PluginInput): Promise<Hooks>uri: z.string().describe(- "Complete viking:// URI from search results or list output (e.g., viking://user/memories/profile.md, viking://agent/memories/context.md)",+ "Complete viking:// URI from search results or list output (e.g., viking://user/memories/profile.md, viking://resources/zh/guide.md)",),level: z.enum(["auto", "abstract", "overview", "read"])@@ -2064,7 +2089,7 @@ export const OpenVikingMemoryPlugin = async (input: PluginInput): Promise<Hooks>uri: z.string().describe(- "Complete viking:// URI to inspect (e.g., viking://user/memories/, viking://agent/memories/, viking://resources/zh/)",+ "Complete viking:// URI to inspect (e.g., viking://user/memories/, viking://user/skills/, viking://resources/zh/)",),view: z.enum(["list", "tree", "stat"])@@ -2119,7 +2144,7 @@ export const OpenVikingMemoryPlugin = async (input: PluginInput): Promise<Hooks>memcommit: tool({description:- "Commit the current OpenCode session to OpenViking and extract persistent memories from the accumulated conversation.\n\nBy default this tool commits the OpenViking session mapped to the current OpenCode session. Use `session_id` only when you need to target a specific OpenViking session manually.\n\nUse when:\n- You want a mid-session memory extraction without ending the chat\n- You want recently discussed preferences, entities, or cases persisted immediately\n\nAutomatically extracts and stores:\n- User profile, preferences, entities, events → viking://user/memories/\n- Agent cases and patterns → viking://agent/memories/\n\nReturns background commit progress or completion details, including task_id, memories_extracted, and archived.",+ "Commit the current OpenCode session to OpenViking and extract persistent memories from the accumulated conversation.\n\nBy default this tool commits the OpenViking session mapped to the current OpenCode session. Use `session_id` only when you need to target a specific OpenViking session manually.\n\nUse when:\n- You want a mid-session memory extraction without ending the chat\n- You want recently discussed preferences, entities, or cases persisted immediately\n\nAutomatically extracts and stores memories under viking://user/memories/.\n\nReturns background commit progress or completion details, including task_id, memories_extracted, and archived.",args: {session_id: z.string()@@ -2306,6 +2331,7 @@ export const OpenVikingMemoryPlugin = async (input: PluginInput): Promise<Hooks>target_uri?: stringsession_id?: stringscore_threshold?: number+ peer_id?: string} = {query: args.query,limit: args.limit ?? 10,@@ -2313,6 +2339,8 @@ export const OpenVikingMemoryPlugin = async (input: PluginInput): Promise<Hooks>if (args.target_uri) requestBody.target_uri = args.target_uriif (args.score_threshold !== undefined) requestBody.score_threshold = args.score_thresholdif (mode === "deep" && sessionId) requestBody.session_id = sessionId+ const peerId = config.peerId.trim()+ if (peerId) requestBody.peer_id = peerIdtry {const response = await makeRequest<OpenVikingResponse<SearchResult>>(config, {diff --git a/examples/opencode-plugin/INSTALL-ZH.md b/examples/opencode-plugin/INSTALL-ZH.mdindex 57bdc7a03..b14e486b3 100644--- a/examples/opencode-plugin/INSTALL-ZH.md+++ b/examples/opencode-plugin/INSTALL-ZH.md@@ -97,7 +97,7 @@ export { OpenVikingPlugin, default } from "./openviking/index.mjs""apiKey": "","account": "","user": "",- "agentId": "",+ "peerId": "","enabled": true,"timeoutMs": 30000,"repoContext": { "enabled": true, "cacheTtlMs": 60000 },@@ -118,11 +118,14 @@ export { OpenVikingPlugin, default } from "./openviking/index.mjs"export OPENVIKING_API_KEY="your-api-key-here"```-`apiKey` 会作为 `X-API-Key` 发送。`account`、`user`、`agentId` 会分别作为-`X-OpenViking-Account`、`X-OpenViking-User`、`X-OpenViking-Agent` 发送。-如果 OpenViking 服务启用了多租户认证,租户级 API 通常必须配置 `account` 和 `user`。+`apiKey` 会作为 `X-API-Key` 发送。`account` 和 `user` 是 trusted mode+身份头,会作为 `X-OpenViking-Account`、`X-OpenViking-User` 发送;使用+user/admin API key 的 API_KEY mode 时应留空。+`peerId` 会作为请求级 `peer_id` 用于 memory recall/search 和 session message 写入;+需要 peer 维度路由时请显式配置。-`OPENVIKING_API_KEY`、`OPENVIKING_ACCOUNT`、`OPENVIKING_USER`、`OPENVIKING_AGENT_ID`+`OPENVIKING_API_KEY`、`OPENVIKING_ACCOUNT`、`OPENVIKING_USER`、+`OPENVIKING_PEER_ID`优先级高于 `openviking-config.json` 里的同名配置。高级场景可以用 `OPENVIKING_PLUGIN_CONFIG` 指向其他配置文件路径。diff --git a/examples/opencode-plugin/INSTALL.md b/examples/opencode-plugin/INSTALL.mdindex 54d3c522f..33b5a7f3e 100644--- a/examples/opencode-plugin/INSTALL.md+++ b/examples/opencode-plugin/INSTALL.md@@ -97,7 +97,7 @@ Example configuration:"apiKey": "","account": "","user": "",- "agentId": "",+ "peerId": "","enabled": true,"timeoutMs": 30000,"repoContext": { "enabled": true, "cacheTtlMs": 60000 },@@ -118,9 +118,9 @@ It is recommended to provide the API key through an environment variable insteadexport OPENVIKING_API_KEY="your-api-key-here"```-`apiKey` is sent as `X-API-Key`. `account`, `user`, and `agentId` are sent as `X-OpenViking-Account`, `X-OpenViking-User`, and `X-OpenViking-Agent`, respectively. If multi-tenant authentication is enabled on the OpenViking server, tenant-scoped APIs usually require `account` and `user` to be configured.+`apiKey` is sent as `X-API-Key`. `account` and `user` are trusted-mode identity headers sent as `X-OpenViking-Account` and `X-OpenViking-User`; leave them empty when using API-key mode with user/admin API keys. `peerId` is sent as request-level `peer_id` for memory recall/search and captured session messages; configure it explicitly when peer-scoped memory routing is needed.-`OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, and `OPENVIKING_AGENT_ID` take precedence over the corresponding values in `openviking-config.json`.+`OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, and `OPENVIKING_PEER_ID` take precedence over the corresponding values in `openviking-config.json`.For advanced setups, use `OPENVIKING_PLUGIN_CONFIG` to point to another configuration file path.diff --git a/examples/opencode-plugin/README.md b/examples/opencode-plugin/README.mdindex 0ae7be92c..12bf978e1 100644--- a/examples/opencode-plugin/README.md+++ b/examples/opencode-plugin/README.md@@ -110,7 +110,7 @@ Create `~/.config/opencode/openviking-config.json`:"apiKey": "","account": "","user": "",- "agentId": "",+ "peerId": "","enabled": true,"timeoutMs": 30000,"repoContext": { "enabled": true, "cacheTtlMs": 60000 },@@ -125,12 +125,16 @@ Create `~/.config/opencode/openviking-config.json`:}```-`apiKey` is sent as `X-API-Key`. `account`, `user`, and `agentId` are sent as-`X-OpenViking-Account`, `X-OpenViking-User`, and `X-OpenViking-Agent`.-They are required by multi-tenant OpenViking servers for tenant-scoped APIs.+`apiKey` is sent as `X-API-Key`. `account` and `user` are trusted-mode identity+headers sent as `X-OpenViking-Account` and `X-OpenViking-User`; leave them empty+when using API-key mode with user/admin API keys.+`peerId` is sent as request-level `peer_id` for memory recall/search and+captured session messages. Configure `peerId` explicitly when peer-scoped+memory routing is needed.-`OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, and-`OPENVIKING_AGENT_ID` take precedence over values in this file.+`OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`,+and `OPENVIKING_PEER_ID` take+precedence over values in this file.For advanced setups, `OPENVIKING_PLUGIN_CONFIG` can point to another config file path.diff --git a/examples/opencode-plugin/lib/memory-recall.mjs b/examples/opencode-plugin/lib/memory-recall.mjsindex a0a037220..2d81cd2de 100644--- a/examples/opencode-plugin/lib/memory-recall.mjs+++ b/examples/opencode-plugin/lib/memory-recall.mjs@@ -1,4 +1,4 @@-import { log, makeRequest, unwrapResponse } from "./utils.mjs"+import { effectivePeerId, log, makeRequest, unwrapResponse } from "./utils.mjs"const AUTO_RECALL_TIMEOUT_MS = 5000const RECALL_STOPWORDS = new Set([@@ -42,10 +42,13 @@ export function createMemoryRecall({ config }) {async function performRecallSearch(query) {try {+ const body = { query: query.slice(0, 4000), limit: 20, mode: "auto" }+ const peerId = effectivePeerId(config)+ if (peerId) body.peer_id = peerIdconst response = await makeRequest(config, {method: "POST",endpoint: "/api/v1/search/find",- body: { query: query.slice(0, 4000), limit: 20, mode: "auto" },+ body,timeoutMs: AUTO_RECALL_TIMEOUT_MS,})const result = unwrapResponse(response)diff --git a/examples/opencode-plugin/lib/memory-session.mjs b/examples/opencode-plugin/lib/memory-session.mjsindex 80aaa1feb..967658035 100644--- a/examples/opencode-plugin/lib/memory-session.mjs+++ b/examples/opencode-plugin/lib/memory-session.mjs@@ -2,6 +2,7 @@ import fs from "fs"import path from "path"import {log,+ effectivePeerId,makeRequest,safeStringify,unwrapResponse,@@ -326,10 +327,13 @@ export function createMemorySessionManager({ config, pluginRoot }) {async function addMessageToSession(ovSessionId, role, content) {try {+ const body = { role, content }+ const peerId = effectivePeerId(config)+ if (peerId) body.peer_id = peerIdconst response = await makeRequest(config, {method: "POST",endpoint: `/api/v1/sessions/${encodeURIComponent(ovSessionId)}/messages`,- body: { role, content },+ body,timeoutMs: 5000,})unwrapResponse(response)diff --git a/examples/opencode-plugin/lib/memory-tools.mjs b/examples/opencode-plugin/lib/memory-tools.mjsindex 00a2330e1..e03b0d8b4 100644--- a/examples/opencode-plugin/lib/memory-tools.mjs+++ b/examples/opencode-plugin/lib/memory-tools.mjs@@ -2,6 +2,7 @@ import { tool } from "@opencode-ai/plugin"import { addMemaddResource } from "./memadd-local.mjs"import {log,+ effectivePeerId,makeRequest,unwrapResponse,validateVikingUri,@@ -37,6 +38,8 @@ export function createMemoryTools({ config, sessionManager, projectDirectory })if (args.target_uri) body.target_uri = args.target_uriif (args.score_threshold !== undefined) body.score_threshold = args.score_thresholdif (mode === "deep" && sessionId) body.session_id = sessionId+ const peerId = effectivePeerId(config)+ if (peerId) body.peer_id = peerIdconst response = await makeRequest(config, {method: "POST",diff --git a/examples/opencode-plugin/lib/utils.mjs b/examples/opencode-plugin/lib/utils.mjsindex 07f207fe1..b975cd921 100644--- a/examples/opencode-plugin/lib/utils.mjs+++ b/examples/opencode-plugin/lib/utils.mjs@@ -7,7 +7,7 @@ export const DEFAULT_CONFIG = {apiKey: "",account: "",user: "",- agentId: "",+ peerId: "",enabled: true,timeoutMs: 30000,runtime: {@@ -35,7 +35,7 @@ function cloneDefaultConfig() {function mergeConfig(fileConfig = {}) {const config = cloneDefaultConfig()- for (const key of ["endpoint", "apiKey", "account", "user", "agentId", "enabled", "timeoutMs"]) {+ for (const key of ["endpoint", "apiKey", "account", "user", "peerId", "enabled", "timeoutMs"]) {if (fileConfig[key] !== undefined) config[key] = fileConfig[key]}config.runtime = {@@ -54,8 +54,8 @@ function mergeConfig(fileConfig = {}) {if (process.env.OPENVIKING_USER) {config.user = process.env.OPENVIKING_USER}- if (process.env.OPENVIKING_AGENT_ID) {- config.agentId = process.env.OPENVIKING_AGENT_ID+ if (process.env.OPENVIKING_PEER_ID) {+ config.peerId = process.env.OPENVIKING_PEER_ID}config.timeoutMs = normalizeNumber(config.timeoutMs, DEFAULT_CONFIG.timeoutMs, 1000, 300000)@@ -179,6 +179,10 @@ export function normalizeEndpoint(endpoint) {return endpoint.replace(/\/+$/, "")}+export function effectivePeerId(config) {+ return String(config.peerId || "").trim() || null+}+export async function makeRequest(config, options) {const url = `${normalizeEndpoint(config.endpoint)}${options.endpoint}`const headers = makeAuthHeaders(config, { "Content-Type": "application/json", ...(options.headers ?? {}) })@@ -286,7 +290,6 @@ function makeAuthHeaders(config, headers = {}) {if (config.apiKey) result["X-API-Key"] = config.apiKeyif (config.account) result["X-OpenViking-Account"] = config.accountif (config.user) result["X-OpenViking-User"] = config.user- if (config.agentId) result["X-OpenViking-Agent"] = config.agentIdreturn result}diff --git a/examples/ov.conf.example b/examples/ov.conf.exampleindex 453af2a1c..48ad9aa15 100644--- a/examples/ov.conf.example+++ b/examples/ov.conf.example@@ -159,7 +159,6 @@"version": "v2","extraction_enabled": true,"session_skill_extraction_enabled": false,- "role_id_memory_isolation_enabled": false,},"log": {"level": "INFO",diff --git a/examples/ovcli.conf.example b/examples/ovcli.conf.exampleindex e76480926..49e3cef05 100644--- a/examples/ovcli.conf.example+++ b/examples/ovcli.conf.example@@ -4,7 +4,6 @@"root_api_key": null,"account": null,"user": null,- "agent_id": null,"timeout": 60.0,"output": "table","echo_command": true,diff --git a/examples/skills/ov-add-data/SKILL.md b/examples/skills/ov-add-data/SKILL.mdindex ea3fabfb2..53b03ac79 100644--- a/examples/skills/ov-add-data/SKILL.md+++ b/examples/skills/ov-add-data/SKILL.md@@ -188,7 +188,7 @@ ov add-memory '[# OpenViking (OV) `add-skill`-The `ov add-skill` command adds agent capabilities to OpenViking — supporting SKILL.md files, MCP tool definitions, and raw skill content. Skills are automatically processed and organized under the `viking://agent/skills/` namespace, making them discoverable and usable by agents.+The `ov add-skill` command adds capabilities to OpenViking — supporting SKILL.md files, MCP tool definitions, and raw skill content. Skills are automatically processed and organized under the `viking://user/skills/` namespace, making them discoverable and usable by agents.## When to Use@@ -234,7 +234,7 @@ ov add-skill ./skills/my-skill/Returns the URI of the added skill, like:```-uri viking://agent/skills/my-skill/+uri viking://user/skills/my-skill/```## SKILL.md Formatdiff --git a/examples/skills/ov_dream/OV_LITE_INSTALL.md b/examples/skills/ov_dream/OV_LITE_INSTALL.mdindex f24befde8..7c3278df3 100644--- a/examples/skills/ov_dream/OV_LITE_INSTALL.md+++ b/examples/skills/ov_dream/OV_LITE_INSTALL.md@@ -7,7 +7,6 @@ This guide installs OV Lite for OpenClaw through the `ov_dream` skill. It syncsSet these values before running sync or recall:- `OPENVIKING_API_KEY`: OpenViking serverless API key-- `OPENVIKING_AGENT_ID`: OpenViking serverless agent IDDo not print API keys in logs, shell history snippets, or replies.@@ -46,13 +45,12 @@ If any check fails, the downloaded `dream.py` is not the expected OV Lite versio## Configure Serverless Auth-Create `~/.openclaw/ov_dream.env` if it does not exist. If it already exists, keep real `OPENVIKING_API_KEY` and `OPENVIKING_AGENT_ID` values and only add missing non-secret defaults.+Create `~/.openclaw/ov_dream.env` if it does not exist. If it already exists, keep the real `OPENVIKING_API_KEY` value and only add missing non-secret defaults.```bashcat > ~/.openclaw/ov_dream.env <<'EOF'OPENVIKING_BASE_URL=https://api.vikingdb.cn-beijing.volces.com/openvikingOPENVIKING_API_KEY=<replace with OpenViking serverless API key>-OPENVIKING_AGENT_ID=<replace with OpenViking agent ID>OPENVIKING_AUTH_MODE=serverlessEOFchmod 600 ~/.openclaw/ov_dream.envdiff --git a/examples/skills/ov_dream/SKILL.md b/examples/skills/ov_dream/SKILL.mdindex efec01bea..cb24439f3 100644--- a/examples/skills/ov_dream/SKILL.md+++ b/examples/skills/ov_dream/SKILL.md@@ -82,4 +82,4 @@ Rules:- It does not auto-inject recall into prompts.- It does not replace the OpenViking context-engine plugin.- Disk-based sync is for recently recorded chat transcripts. It is not a precise "currently running sessions" detector.-- For OpenViking serverless, configure `OPENVIKING_BASE_URL`, `OPENVIKING_API_KEY`, `OPENVIKING_AGENT_ID`, and optionally `OPENVIKING_AUTH_MODE=serverless`. The CLI will use Bearer auth and the serverless session message format automatically.+- For OpenViking serverless, configure `OPENVIKING_BASE_URL`, `OPENVIKING_API_KEY`, and optionally `OPENVIKING_AUTH_MODE=serverless`. The CLI will use Bearer auth and the serverless session message format automatically.diff --git a/examples/skills/ov_dream/scripts/dream.py b/examples/skills/ov_dream/scripts/dream.pyindex ede30c98e..ceab51719 100644--- a/examples/skills/ov_dream/scripts/dream.py+++ b/examples/skills/ov_dream/scripts/dream.py@@ -11,7 +11,6 @@ from typing import Any, Iterablefrom urllib.error import HTTPErrorfrom urllib.request import Request, urlopen-DEFAULT_BASE_URL = "http://127.0.0.1:1933"DEFAULT_TARGET_URI = "viking://user/default"LEGACY_TARGET_URI = "viking://user/memories"@@ -39,13 +38,11 @@ class OpenVikingClient:self,base_url: str,api_key: str | None = None,- agent_id: str | None = None,auth_mode: str = "auto",timeout: int = 30,) -> None:self.base_url = base_url.rstrip("/")self.api_key = api_key or os.environ.get("OPENVIKING_API_KEY", "")- self.agent_id = agent_id or os.environ.get("OPENVIKING_AGENT_ID") or os.environ.get("OPENVIKING_AGENT", "default")self.auth_mode = self._resolve_auth_mode(auth_mode)self.timeout = timeout@@ -61,7 +58,6 @@ class OpenVikingClient:def _headers(self) -> dict[str, str]:headers = {"Content-Type": "application/json"}if self.auth_mode == "serverless":- headers["X-OpenViking-Agent"] = self.agent_idif self.api_key:headers["Authorization"] = "Bearer " + self.api_keyelse:@@ -69,7 +65,6 @@ class OpenVikingClient:{"X-OpenViking-Account": os.environ.get("OPENVIKING_ACCOUNT", "default"),"X-OpenViking-User": os.environ.get("OPENVIKING_USER", "default"),- "X-OpenViking-Agent": self.agent_id,})if self.api_key:@@ -88,7 +83,9 @@ class OpenVikingClient:return f"viking://user/{user_space}/memories/"return target_uri- def _request(self, method: str, path: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:+ def _request(+ self, method: str, path: str, payload: dict[str, Any] | None = None+ ) -> dict[str, Any]:data = None if payload is None else json.dumps(payload).encode("utf-8")request = Request(f"{self.base_url}{path}",@@ -133,7 +130,9 @@ class OpenVikingClient:suffix = "" if self.auth_mode == "serverless" else "?wait=true" if wait else ""return self._request("POST", f"/api/v1/sessions/{session_id}/commit{suffix}", payload)- def recall(self, query: str, limit: int = 5, target_uri: str = DEFAULT_TARGET_URI) -> dict[str, Any]:+ def recall(+ self, query: str, limit: int = 5, target_uri: str = DEFAULT_TARGET_URI+ ) -> dict[str, Any]:return self._request("POST","/api/v1/search/find",@@ -261,7 +260,9 @@ def get_active_session(openclaw_root: Path) -> Session | None:return sessions[0] if sessions else None-def parse_messages(sessions_root: Path, session: Session, after_timestamp: str | None) -> Iterable[Message]:+def parse_messages(+ sessions_root: Path, session: Session, after_timestamp: str | None+) -> Iterable[Message]:path = get_session_file_path(sessions_root, session)if not path.exists():return []@@ -282,9 +283,7 @@ def parse_messages(sessions_root: Path, session: Session, after_timestamp: str |continueblocks = message.get("content", [])text_parts = [- block.get("text", "").strip()- for block in blocks- if block.get("type") == "text"+ block.get("text", "").strip() for block in blocks if block.get("type") == "text"]content = "\n".join(part for part in text_parts if part)if not content:@@ -309,7 +308,8 @@ def sync_session(messages = [messagefor message in parse_messages(sessions_root, session, last_synced_timestamp)- if message.timestamp and (last_synced_timestamp is None or message.timestamp > last_synced_timestamp)+ if message.timestamp+ and (last_synced_timestamp is None or message.timestamp > last_synced_timestamp)]messages.sort(key=lambda message: message.timestamp)@@ -345,7 +345,9 @@ def sync_session(}-def sync_active_session(client: OpenVikingClient, openclaw_root: Path, state_root: Path) -> dict[str, Any]:+def sync_active_session(+ client: OpenVikingClient, openclaw_root: Path, state_root: Path+) -> dict[str, Any]:sessions_root = openclaw_root / "agents" / "main" / "sessions"active_sessions = get_active_sessions(openclaw_root)if not active_sessions:@@ -397,10 +399,15 @@ def _normalize_ov_command(argv: list[str] | None) -> list[str] | None:def _build_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser(prog="ov dream")- parser.add_argument("--base-url", default=os.environ.get("OPENVIKING_BASE_URL", DEFAULT_BASE_URL))+ parser.add_argument(+ "--base-url", default=os.environ.get("OPENVIKING_BASE_URL", DEFAULT_BASE_URL)+ )parser.add_argument("--api-key", default=None)- parser.add_argument("--agent-id", default=None)- parser.add_argument("--auth-mode", choices=["auto", "local", "serverless"], default=os.environ.get("OPENVIKING_AUTH_MODE", "auto"))+ parser.add_argument(+ "--auth-mode",+ choices=["auto", "local", "serverless"],+ default=os.environ.get("OPENVIKING_AUTH_MODE", "auto"),+ )parser.add_argument("--openclaw-root", default=str(Path.home() / ".openclaw"))parser.add_argument("--state-root", default=str(Path.home() / ".openclaw" / "memory"))@@ -467,7 +474,6 @@ def run_dream(args: argparse.Namespace) -> int:client = OpenVikingClient(base_url=args.base_url,api_key=args.api_key,- agent_id=args.agent_id,auth_mode=args.auth_mode,)summary = sync_active_session(@@ -483,7 +489,6 @@ def run_recall(args: argparse.Namespace) -> int:client = OpenVikingClient(base_url=args.base_url,api_key=args.api_key,- agent_id=args.agent_id,auth_mode=args.auth_mode,)result = client.recall(query=args.query, limit=args.limit)diff --git a/examples/skills/ov_dream/tests/test_dream_cli.py b/examples/skills/ov_dream/tests/test_dream_cli.pyindex e2f145d1a..97b8c5c33 100644--- a/examples/skills/ov_dream/tests/test_dream_cli.py+++ b/examples/skills/ov_dream/tests/test_dream_cli.py@@ -2,8 +2,8 @@ from __future__ import annotationsimport importlib.utilimport json-from pathlib import Pathimport sys+from pathlib import Pathdef _load_dream_module():@@ -19,7 +19,9 @@ def _load_dream_module():dream = _load_dream_module()-def _write_session(path: Path, session_id: str, messages: list[tuple[str, str, str]] | None = None) -> None:+def _write_session(+ path: Path, session_id: str, messages: list[tuple[str, str, str]] | None = None+) -> None:rows = [{"id": session_id, "timestamp": "2026-04-20T00:00:00Z", "cwd": "/tmp"},]@@ -34,7 +36,9 @@ def _write_session(path: Path, session_id: str, messages: list[tuple[str, str, s},})- path.write_text("\n".join(json.dumps(row, ensure_ascii=False) for row in rows) + "\n", encoding="utf-8")+ path.write_text(+ "\n".join(json.dumps(row, ensure_ascii=False) for row in rows) + "\n", encoding="utf-8"+ )def test_normalize_raw_ov_recall_phrase() -> None:@@ -48,8 +52,13 @@ def test_recall_expands_default_user_root_to_explicit_user_space(monkeypatch) ->assert client._resolve_target_uri("viking://user/default") == "viking://user/default"assert client._resolve_target_uri("viking://user/default/") == "viking://user/default"assert client._resolve_target_uri("viking://user/memories") == "viking://user/default/memories/"- assert client._resolve_target_uri("viking://user/memories/") == "viking://user/default/memories/"- assert client._resolve_target_uri("viking://user/default/memories/") == "viking://user/default/memories/"+ assert (+ client._resolve_target_uri("viking://user/memories/") == "viking://user/default/memories/"+ )+ assert (+ client._resolve_target_uri("viking://user/default/memories/")+ == "viking://user/default/memories/"+ )def test_recall_default_target_uri_is_user_root() -> None:@@ -60,7 +69,7 @@ def test_recall_default_target_uri_is_user_root() -> None:calls.append((method, path, payload))return {"memories": []}- client = RecordingClient(base_url=dream.SERVERLESS_BASE_URL, api_key="test-key", agent_id="test-agent")+ client = RecordingClient(base_url=dream.SERVERLESS_BASE_URL, api_key="test-key")client.recall("hello")@@ -77,16 +86,14 @@ def test_recall_default_target_uri_is_user_root() -> None:]-def test_serverless_headers_use_bearer_and_agent_id() -> None:+def test_serverless_headers_use_bearer_auth() -> None:client = dream.OpenVikingClient(base_url=dream.SERVERLESS_BASE_URL,api_key="test-key",- agent_id="test-agent",)assert client.auth_mode == "serverless"assert client._headers()["Authorization"] == "Bearer test-key"- assert client._headers()["X-OpenViking-Agent"] == "test-agent"assert "X-API-Key" not in client._headers()assert "X-OpenViking-User" not in client._headers()@@ -102,7 +109,6 @@ def test_serverless_sync_reuses_source_session_id_and_uses_parts_payload() -> Noclient = RecordingClient(base_url=dream.SERVERLESS_BASE_URL,api_key="test-key",- agent_id="test-agent",)client.add_session_message("source-session", "user", "hello")@@ -214,9 +220,15 @@ def test_get_active_sessions_filters_index_entries(tmp_path: Path) -> None:json.dumps({"agent:main:main": {"sessionId": "main", "sessionFile": "main.jsonl"},- "agent:main:telegram:direct:123": {"sessionId": "direct", "sessionFile": str(kept_direct)},+ "agent:main:telegram:direct:123": {+ "sessionId": "direct",+ "sessionFile": str(kept_direct),+ },"agent:main:cron:daily": {"sessionId": "cron", "sessionFile": str(skipped_cron)},- "agent:main:subagent:child": {"sessionId": "subagent", "sessionFile": str(skipped_subagent)},+ "agent:main:subagent:child": {+ "sessionId": "subagent",+ "sessionFile": str(skipped_subagent),+ },}),encoding="utf-8",@@ -259,7 +271,10 @@ def test_sync_active_session_syncs_chat_sessions_with_independent_cursors(tmp_pajson.dumps({"agent:main:main": {"sessionId": "main", "sessionFile": str(main_file)},- "agent:main:telegram:direct:123": {"sessionId": "direct", "sessionFile": str(direct_file)},+ "agent:main:telegram:direct:123": {+ "sessionId": "direct",+ "sessionFile": str(direct_file),+ },"agent:main:cron:daily": {"sessionId": "cron", "sessionFile": str(cron_file)},}),diff --git a/openviking/async_client.py b/openviking/async_client.pyindex debda7841..48a2f00b4 100644--- a/openviking/async_client.py+++ b/openviking/async_client.py@@ -46,14 +46,12 @@ class AsyncOpenViking:def __init__(self,path: Optional[str] = None,- **kwargs,):"""Initialize OpenViking client (embedded mode).Args:path: Local storage path (overrides ov.conf storage path).- **kwargs: Additional configuration parameters."""# Singleton guard for repeated initializationif hasattr(self, "_singleton_initialized") and self._singleton_initialized:@@ -129,7 +127,10 @@ class AsyncOpenViking:return await self._client.session_exists(session_id)async def create_session(- self, session_id: Optional[str] = None, telemetry: TelemetryRequest = False+ self,+ session_id: Optional[str] = None,+ telemetry: TelemetryRequest = False,+ memory_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Create a new session.@@ -138,7 +139,11 @@ class AsyncOpenViking:If None, creates a new session with auto-generated ID."""await self._ensure_initialized()- return await self._client.create_session(session_id, telemetry=telemetry)+ return await self._client.create_session(+ session_id,+ telemetry=telemetry,+ memory_policy=memory_policy,+ )async def list_sessions(self) -> List[Any]:"""List all sessions."""@@ -174,7 +179,7 @@ class AsyncOpenViking:content: str | None = None,parts: list[dict] | None = None,created_at: str | None = None,- role_id: str | None = None,+ peer_id: str | None = None,telemetry: TelemetryRequest = False,) -> Dict[str, Any]:"""Add a message to a session.@@ -185,7 +190,7 @@ class AsyncOpenViking:content: Text content (simple mode)parts: Parts array (full Part support: TextPart, ContextPart, ToolPart)created_at: Message creation time (ISO format string)- role_id: Optional explicit actor identity. Omit to let the client/server derive it.+ peer_id: Optional stable interaction peer identity.If both content and parts are provided, parts takes precedence."""@@ -196,7 +201,7 @@ class AsyncOpenViking:content=content,parts=parts,created_at=created_at,- role_id=role_id,+ peer_id=peer_id,telemetry=telemetry,)@@ -220,6 +225,7 @@ class AsyncOpenViking:telemetry: TelemetryRequest = False,*,keep_recent_count: int = 0,+ memory_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Commit a session (archive and extract memories)."""await self._ensure_initialized()@@ -227,6 +233,7 @@ class AsyncOpenViking:session_id,telemetry=telemetry,keep_recent_count=keep_recent_count,+ memory_policy=memory_policy,)async def get_task(self, task_id: str) -> Optional[Dict[str, Any]]:@@ -365,6 +372,7 @@ class AsyncOpenViking:until: Optional[str] = None,time_field: Optional[str] = None,level: Optional[List[int]] = None,+ peer_id: Optional[str] = None,):"""Complex search with session context.@@ -394,6 +402,7 @@ class AsyncOpenViking:until=until,time_field=time_field,level=level,+ peer_id=peer_id,)async def find(@@ -408,6 +417,7 @@ class AsyncOpenViking:until: Optional[str] = None,time_field: Optional[str] = None,level: Optional[List[int]] = None,+ peer_id: Optional[str] = None,):"""Semantic search"""await self._ensure_initialized()@@ -422,6 +432,7 @@ class AsyncOpenViking:until=until,time_field=time_field,level=level,+ peer_id=peer_id,)# ============= FS methods =============diff --git a/openviking/client/local.py b/openviking/client/local.pyindex 24eda0fd7..2d7744d4f 100644--- a/openviking/client/local.py+++ b/openviking/client/local.py@@ -7,6 +7,7 @@ Implements BaseClient interface using direct service calls (embedded mode).from typing import Any, Dict, List, Optional, Union+from openviking.core.peer_id import normalize_peer_idfrom openviking.server.identity import RequestContext, Rolefrom openviking.service import OpenVikingServicefrom openviking.telemetry import TelemetryRequest@@ -62,7 +63,7 @@ class LocalClient(BaseClient):Args:path: Local storage path (overrides ov.conf storage path)- user: Explicit user/account/agent identity for embedded mode+ user: Explicit account/user identity for embedded mode"""self._service = OpenVikingService(path=path,@@ -299,6 +300,7 @@ class LocalClient(BaseClient):until: Optional[str] = None,time_field: Optional[str] = None,level: Optional[List[int]] = None,+ peer_id: Optional[str] = None,) -> Any:"""Semantic search without session context."""resolved_filter = _resolve_search_filter(filter, since, until, time_field)@@ -309,6 +311,7 @@ class LocalClient(BaseClient):query=query,ctx=self._ctx,target_uri=target_uri,+ peer_id=normalize_peer_id(peer_id),limit=limit,score_threshold=score_threshold,filter=resolved_filter,@@ -333,6 +336,7 @@ class LocalClient(BaseClient):until: Optional[str] = None,time_field: Optional[str] = None,level: Optional[List[int]] = None,+ peer_id: Optional[str] = None,) -> Any:"""Semantic search with optional session context."""resolved_filter = _resolve_search_filter(filter, since, until, time_field)@@ -346,6 +350,7 @@ class LocalClient(BaseClient):query=query,ctx=self._ctx,target_uri=target_uri,+ peer_id=normalize_peer_id(peer_id),session=session,limit=limit,score_threshold=score_threshold,@@ -404,7 +409,10 @@ class LocalClient(BaseClient):# ============= Sessions =============async def create_session(- self, session_id: Optional[str] = None, telemetry: TelemetryRequest = False+ self,+ session_id: Optional[str] = None,+ telemetry: TelemetryRequest = False,+ memory_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Create a new session.@@ -415,17 +423,24 @@ class LocalClient(BaseClient):execution = await run_with_telemetry(operation="session.create",telemetry=telemetry,- fn=lambda: self._create_session_impl(session_id),+ fn=lambda: self._create_session_impl(session_id, memory_policy),)return attach_telemetry_payload(execution.result,execution.telemetry,)- async def _create_session_impl(self, session_id: Optional[str]) -> Dict[str, Any]:+ async def _create_session_impl(+ self,+ session_id: Optional[str],+ memory_policy: Optional[Dict[str, Any]],+ ) -> Dict[str, Any]:await self._service.initialize_user_directories(self._ctx)- await self._service.initialize_agent_directories(self._ctx)- session = await self._service.sessions.create(self._ctx, session_id)+ session = await self._service.sessions.create(+ self._ctx,+ session_id,+ memory_policy=memory_policy,+ )return {"session_id": session.session_id,"user": session.user.to_dict(),@@ -468,6 +483,7 @@ class LocalClient(BaseClient):telemetry: TelemetryRequest = False,*,keep_recent_count: int = 0,+ memory_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Commit a session (archive and extract memories)."""execution = await run_with_telemetry(@@ -477,6 +493,7 @@ class LocalClient(BaseClient):session_id,self._ctx,keep_recent_count=keep_recent_count,+ memory_policy=memory_policy,),)return attach_telemetry_payload(@@ -495,7 +512,7 @@ class LocalClient(BaseClient):content: Optional[str] = None,parts: Optional[List[Dict[str, Any]]] = None,created_at: Optional[str] = None,- role_id: Optional[str] = None,+ peer_id: Optional[str] = None,telemetry: TelemetryRequest = False,) -> Dict[str, Any]:"""Add a message to a session.@@ -506,7 +523,7 @@ class LocalClient(BaseClient):content: Text content (simple mode, backward compatible)parts: Parts array (full Part support mode)created_at: Message creation time (ISO format string)- role_id: Optional explicit actor identity. Omit to derive it from the local context.+ peer_id: Optional stable interaction peer identity.If both content and parts are provided, parts takes precedence."""@@ -519,7 +536,7 @@ class LocalClient(BaseClient):content,parts,created_at,- role_id,+ peer_id,),)return attach_telemetry_payload(@@ -534,7 +551,7 @@ class LocalClient(BaseClient):content: Optional[str],parts: Optional[List[Dict[str, Any]]],created_at: Optional[str],- role_id: Optional[str],+ peer_id: Optional[str],) -> Dict[str, Any]:from openviking.message.part import Part, TextPart, part_from_dict@@ -548,12 +565,12 @@ class LocalClient(BaseClient):else:raise ValueError("Either content or parts must be provided")- if role_id is None and role == "user":- role_id = self._ctx.user.user_id- elif role_id is None and role == "assistant":- role_id = self._ctx.user.agent_id-- session.add_message(role, message_parts, role_id=role_id, created_at=created_at)+ session.add_message(+ role,+ message_parts,+ peer_id=peer_id,+ created_at=created_at,+ )return {"session_id": session_id,"message_count": len(session.messages),@@ -597,19 +614,15 @@ class LocalClient(BaseClient):elif message.get("content") is not None:message_parts = [TextPart(text=str(message["content"]))]else:- raise ValueError(f"messages[{index}]: either content or parts must be provided")-- role_id = message.get("role_id")- if role_id is None and role == "user":- role_id = self._ctx.user.user_id- elif role_id is None and role == "assistant":- role_id = self._ctx.user.agent_id+ raise ValueError(f"messages[{index}]: Either content or parts must be provided")specs.append({"role": role,"parts": message_parts,- "role_id": role_id,+ "peer_id": normalize_peer_id(+ message.get("peer_id"),+ ),"created_at": message.get("created_at"),})diff --git a/openviking/client/session.py b/openviking/client/session.pyindex 181e59c57..90956de96 100644--- a/openviking/client/session.py+++ b/openviking/client/session.py@@ -41,7 +41,7 @@ class Session:content: Optional[str] = None,parts: Optional[List[Part]] = None,created_at: Optional[str] = None,- role_id: Optional[str] = None,+ peer_id: Optional[str] = None,) -> Dict[str, Any]:"""Add a message to the session.@@ -50,7 +50,7 @@ class Session:content: Text content (simple mode)parts: Parts list (TextPart, ContextPart, ToolPart)created_at: Message creation time (ISO format string). If not provided, current time is used.- role_id: Optional explicit actor identity. Omit to let the server derive it.+ peer_id: Optional stable interaction peer identity.If both content and parts are provided, parts takes precedence.@@ -64,14 +64,14 @@ class Session:role,parts=parts_dicts,created_at=created_at,- role_id=role_id,+ peer_id=peer_id,)return await self._client.add_message(self.session_id,role,content=content,created_at=created_at,- role_id=role_id,+ peer_id=peer_id,)async def batch_add_messages(@@ -82,7 +82,7 @@ class Session:Args:messages: List of dicts, each with "role" and optionally "content",- "parts", "created_at", "role_id".+ "parts", "created_at", "peer_id".Returns:Result dict with session_id, message_count, and added count.@@ -97,6 +97,7 @@ class Session:telemetry: TelemetryRequest = False,*,keep_recent_count: int = 0,+ memory_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Commit the session (archive messages and extract memories).@@ -107,6 +108,7 @@ class Session:self.session_id,telemetry=telemetry,keep_recent_count=keep_recent_count,+ memory_policy=memory_policy,)async def commit_async(@@ -114,6 +116,7 @@ class Session:telemetry: TelemetryRequest = False,*,keep_recent_count: int = 0,+ memory_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Commit the session asynchronously (archive messages and extract memories).Used in viking bot for committing.@@ -121,7 +124,11 @@ class Session:Returns:Commit result"""- return await self.commit(telemetry=telemetry, keep_recent_count=keep_recent_count)+ return await self.commit(+ telemetry=telemetry,+ keep_recent_count=keep_recent_count,+ memory_policy=memory_policy,+ )async def delete(self) -> None:"""Delete the session."""diff --git a/openviking/core/context.py b/openviking/core/context.pyindex e43d3c3fa..ae59b8243 100644--- a/openviking/core/context.py+++ b/openviking/core/context.py@@ -73,7 +73,6 @@ class Context:user: Optional[UserIdentifier] = None,account_id: Optional[str] = None,owner_user_id: Optional[str] = None,- owner_agent_id: Optional[str] = None,owner_space: Optional[str] = None,id: Optional[str] = None,):@@ -108,9 +107,6 @@ class Context:self.owner_user_id = (owner_user_id if owner_user_id is not None else owner_fields["owner_user_id"])- self.owner_agent_id = (- owner_agent_id if owner_agent_id is not None else owner_fields["owner_agent_id"]- )self.owner_space = owner_space or self._derive_owner_space(user)self.vector: Optional[List[float]] = Noneself.vectorize = Vectorize(abstract)@@ -119,8 +115,6 @@ class Context:"""Best-effort owner space derived from URI and user."""if not user:return ""- if self.uri.startswith("viking://agent/"):- return user.agent_idif self.uri.startswith("viking://user/") or self.uri.startswith("viking://session/"):return user.user_idreturn ""@@ -181,7 +175,6 @@ class Context:"session_id": self.session_id,"account_id": self.account_id,"owner_user_id": self.owner_user_id,- "owner_agent_id": self.owner_agent_id,"owner_space": self.owner_space,}if self.level is not None:@@ -243,7 +236,6 @@ class Context:user=user_obj,account_id=data.get("account_id"),owner_user_id=data.get("owner_user_id"),- owner_agent_id=data.get("owner_agent_id"),owner_space=data.get("owner_space"),)obj.id = data.get("id", obj.id)diff --git a/openviking/core/directories.py b/openviking/core/directories.pyindex 4c0ad70ef..e83b025bf 100644--- a/openviking/core/directories.py+++ b/openviking/core/directories.py@@ -12,8 +12,6 @@ from typing import TYPE_CHECKING, Dict, List, Optionalfrom openviking.core.context import Context, Vectorizefrom openviking.core.namespace import (- agent_space_fragment,- canonical_agent_root,canonical_user_root,context_type_for_uri,user_space_fragment,@@ -78,51 +76,52 @@ PRESET_DIRECTORIES: Dict[str, DirectoryDefinition] = {"Examples: decided to refactor memory system, completed a project, attended an event. ""Events are historical records, not updated once created.",),- ],- ),- DirectoryDefinition(- path="privacy",- abstract="User privacy config root. Stores user-scoped sensitive configuration snapshots by category and target key.",- overview="Use this directory to access privacy-managed configuration values such as skill secrets. Concrete category and target-key subdirectories are created lazily by the privacy config service.",- ),- ],- ),- "agent": DirectoryDefinition(- path="",- abstract="Agent scope. Stores Agent's learning memories, instructions, and skills.",- overview="Agent-level global data storage. "- "Contains three main categories: memories-learning memories, instructions-directives, skills-capability registry.",- children=[- DirectoryDefinition(- path="memories",- abstract="Agent's long-term memory storage. Contains trajectories and experiences, managed hierarchically by type.",- overview="Use this directory to access Agent's learning memories. Contains two main categories: "- "1) trajectories-task execution records, 2) experiences-generalized lessons from trajectories.",- children=[+ DirectoryDefinition(+ path="cases",+ abstract="User's case memories. Stores concrete problem contexts and resolutions learned from sessions.",+ overview="Access when handling similar future problems. Cases are specific examples, separate from reusable patterns.",+ ),+ DirectoryDefinition(+ path="patterns",+ abstract="User's pattern memories. Stores reusable methods, workflows, and SOP-like lessons.",+ overview="Access when applying accumulated methods to new tasks. Patterns are generalized from cases and interactions.",+ ),+ DirectoryDefinition(+ path="tools",+ abstract="User's tool usage memories. Stores tool behavior, parameter experience, and failure modes.",+ overview="Access when deciding how to call tools or diagnosing tool failures.",+ ),+ DirectoryDefinition(+ path="skills",+ abstract="User's skill execution memories. Stores experience about using configured skills.",+ overview="Access when choosing or executing skills. This is memory about skill usage, not the skill definition itself.",+ ),DirectoryDefinition(path="trajectories",- abstract="Agent's execution trajectory records. Stores end-to-end task execution traces from each interaction, each trajectory is independent and not updated.",- overview="Access when reviewing how the agent handled past tasks or diagnosing execution history. "- "Trajectories are records of specific task executions, each independent and not updated once created.",+ abstract="User's execution trajectory records. Stores end-to-end task execution traces when trajectory memory is enabled.",+ overview="Access when reviewing how a previous task was executed.",),DirectoryDefinition(path="experiences",- abstract="Agent's generalized experience memories. Reusable insights and lessons distilled from execution trajectories, updated as new evidence accumulates.",- overview="Access when the agent encounters recurring situations or needs guidance from past lessons. "- "Experiences are distilled from trajectories and updated incrementally as more supporting evidence accumulates.",+ abstract="User's generalized experience memories distilled from execution trajectories.",+ overview="Access when applying lessons learned from repeated execution trajectories.",),],),DirectoryDefinition(- path="instructions",- abstract="Agent instruction set. Contains Agent's behavioral directives, rules, and constraints.",- overview="Access when Agent needs to follow specific rules. "- "Examples: planner agent has specific planning process requirements, executor agent has execution standards, etc.",+ path="privacy",+ abstract="User privacy config root. Stores user-scoped sensitive configuration snapshots by category and target key.",+ overview="Use this directory to access privacy-managed configuration values such as skill secrets. Concrete category and target-key subdirectories are created lazily by the privacy config service.",+ ),+ DirectoryDefinition(+ path="peers",+ abstract="User peer memory root. Stores the current User's long-term memory about stable interaction peers.",+ overview="Use this directory when the current User needs to distinguish long-term interaction objects such as visitors, teammates, or external contacts. Peer directories are created lazily from session peer_id values.",),DirectoryDefinition(path="skills",- abstract="Agent's skill registry. Uses Claude Skills protocol format, flat storage of callable skill definitions.",- overview="Access when Agent needs to execute specific tasks. Skills categorized by tags, "+ abstract="User skill registry. Uses Claude Skills protocol format, flat storage of callable skill definitions owned by the current User.",+ overview="Access when the current User or a proxy acting with the current User's API key needs to execute specific tasks. Skills categorized by tags, ""should retrieve relevant skills before executing tasks, select most appropriate skill to execute.",),],@@ -159,7 +158,6 @@ class DirectoryInitializer:count = 0scope_roots = {"user": PRESET_DIRECTORIES["user"],- "agent": PRESET_DIRECTORIES["agent"],"resources": PRESET_DIRECTORIES["resources"],"session": PRESET_DIRECTORIES["session"],}@@ -183,10 +181,6 @@ class DirectoryInitializer:user_space_root = canonical_user_root(ctx)user_tree = PRESET_DIRECTORIES["user"]parent_uri = "viking://user"- if ctx.namespace_policy.isolate_user_scope_by_agent:- container_uri = f"viking://user/{ctx.user.user_id}"- await self._ensure_container_directory(container_uri, parent_uri=parent_uri, ctx=ctx)- parent_uri = container_uricreated = await self._ensure_directory(uri=user_space_root,parent_uri=parent_uri,@@ -201,29 +195,8 @@ class DirectoryInitializer:return countasync def initialize_agent_directories(self, ctx: RequestContext) -> int:- """Initialize agent-space tree lazily for the current user+agent."""- if "agent" not in PRESET_DIRECTORIES:- return 0- agent_space_root = canonical_agent_root(ctx)- agent_tree = PRESET_DIRECTORIES["agent"]- parent_uri = "viking://agent"- if ctx.namespace_policy.isolate_agent_scope_by_user:- container_uri = f"viking://agent/{ctx.user.agent_id}"- await self._ensure_container_directory(container_uri, parent_uri=parent_uri, ctx=ctx)- parent_uri = container_uri- created = await self._ensure_directory(- uri=agent_space_root,- parent_uri=parent_uri,- defn=agent_tree,- scope="agent",- ctx=ctx,- )- count = 1 if created else 0- count += await self._initialize_children(- "agent", agent_tree.children, agent_space_root, ctx=ctx- )-- return count+ """Deprecated compatibility hook; agent directories are no longer initialized."""+ return 0async def _ensure_container_directory(self,@@ -313,8 +286,6 @@ class DirectoryInitializer:def _owner_space_for_scope(scope: str, ctx: RequestContext) -> str:if scope in {"user", "session"}:return user_space_fragment(ctx)- if scope == "agent":- return agent_space_fragment(ctx)return ""async def _check_agfs_files_exist(self, uri: str, ctx: RequestContext) -> bool:diff --git a/openviking/core/namespace.py b/openviking/core/namespace.pyindex 625d1c226..5ffa31472 100644--- a/openviking/core/namespace.py+++ b/openviking/core/namespace.py@@ -1,31 +1,27 @@-"""Namespace policy helpers for account/user/agent/session URIs."""+"""Namespace helpers for account/user/session URIs."""from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Optional-from openviking.server.identity import AccountNamespacePolicy, RequestContext+from openviking.server.identity import RequestContextfrom openviking_cli.utils.uri import VikingURI-_USER_SHORTHAND_SEGMENTS = {"memories", "profile.md", ".abstract.md", ".overview.md"}-_AGENT_SHORTHAND_SEGMENTS = {+_USER_SHORTHAND_SEGMENTS = {"memories","skills",- "instructions",- "workspaces",+ "profile.md",".abstract.md",".overview.md",}-_CROSS_SCOPE_OWNER_SEGMENT = {"user": "agent", "agent": "user"}_CONTENT_TYPES_BY_SCOPE = {- "user": {"memories": "memory"},- "agent": {"memories": "memory", "skills": "skill"},+ "user": {"memories": "memory", "skills": "skill"},}class NamespaceShapeError(ValueError):- """Raised when a URI does not match the active namespace policy shape."""+ """Raised when a URI does not match the supported namespace shape."""@dataclass(frozen=True)@@ -35,7 +31,6 @@ class ResolvedNamespace:uri: strscope: strowner_user_id: Optional[str] = None- owner_agent_id: Optional[str] = Noneis_container: bool = False@@ -62,7 +57,7 @@ class UriClassification:@propertydef is_agent_namespace_root(self) -> bool:- return _is_namespace_root_parts(self.parts, "agent")+ return False@propertydef is_memory_root(self) -> bool:@@ -120,23 +115,20 @@ def relative_uri_path(root_uri: str, uri: str) -> str:def _content_segment_index(parts: tuple[str, ...]) -> Optional[int]:- """Return the first content segment after a user/agent namespace root."""- if len(parts) < 2 or parts[0] not in _CONTENT_TYPES_BY_SCOPE:+ """Return the first content segment after a user namespace root."""+ if len(parts) < 2 or parts[0] != "user":return None- if parts[1] in _CONTENT_TYPES_BY_SCOPE[parts[0]]:+ if parts[1] in _CONTENT_TYPES_BY_SCOPE["user"]:return 1- if len(parts) < 3:- return None- cross_scope_segment = _CROSS_SCOPE_OWNER_SEGMENT[parts[0]]- if len(parts) >= 5 and parts[2] == cross_scope_segment:+ if len(parts) >= 5 and parts[2] == "peers" and parts[4] == "memories":return 4- return 2+ if len(parts) >= 3 and parts[2] in _CONTENT_TYPES_BY_SCOPE["user"]:+ return 2+ return Nonedef _is_namespace_root_parts(parts: tuple[str, ...], scope: str) -> bool:- return parts[:1] == (scope,) and (- len(parts) == 2 or (len(parts) == 4 and parts[2] == _CROSS_SCOPE_OWNER_SEGMENT[scope])- )+ return scope == "user" and parts[:1] == ("user",) and len(parts) == 2def classify_uri(uri: str) -> UriClassification:@@ -164,27 +156,7 @@ def canonical_user_root(ctx: RequestContext) -> str:def user_space_fragment(ctx: RequestContext) -> str:- return to_user_space(ctx.namespace_policy, ctx.user.user_id, ctx.user.agent_id)---def to_user_space(namespace_policy, user_id, agent_id) -> str:- if namespace_policy.isolate_user_scope_by_agent:- return f"{user_id}/agent/{agent_id}"- return user_id---def canonical_agent_root(ctx: RequestContext) -> str:- return f"viking://agent/{agent_space_fragment(ctx)}"---def agent_space_fragment(ctx: RequestContext) -> str:- return to_agent_space(ctx.namespace_policy, ctx.user.user_id, ctx.user.agent_id)---def to_agent_space(namespace_policy, user_id, agent_id) -> str:- if namespace_policy.isolate_agent_scope_by_user:- return f"{agent_id}/user/{user_id}"- return agent_id+ return ctx.user.user_iddef canonical_session_uri(session_id: Optional[str] = None) -> str:@@ -198,7 +170,6 @@ def visible_roots(ctx: RequestContext) -> list[str]:"viking://resources","viking://session",canonical_user_root(ctx),- canonical_agent_root(ctx),]@@ -218,7 +189,7 @@ def resolve_uri(if scope == "user":return _resolve_user_uri(parts, ctx=ctx, require_canonical=require_canonical)if scope == "agent":- return _resolve_agent_uri(parts, ctx=ctx, require_canonical=require_canonical)+ raise NamespaceShapeError("viking://agent is deprecated; use viking://user instead")if scope == "session":return _resolve_session_uri(parts)if scope in {"resources", "temp", "queue", "upload"}:@@ -246,22 +217,6 @@ def is_accessible(uri: str, ctx: RequestContext) -> bool:if target.scope == "user":if target.owner_user_id and target.owner_user_id != ctx.user.user_id:return False- if (- ctx.namespace_policy.isolate_user_scope_by_agent- and target.owner_agent_id is not None- and target.owner_agent_id != ctx.user.agent_id- ):- return False- return True- if target.scope == "agent":- if target.owner_agent_id and target.owner_agent_id != ctx.user.agent_id:- return False- if (- ctx.namespace_policy.isolate_agent_scope_by_user- and target.owner_user_id is not None- and target.owner_user_id != ctx.user.user_id- ):- return Falsereturn Truereturn True@@ -272,7 +227,6 @@ def owner_fields_for_uri(*,user=None,account_id: Optional[str] = None,- policy: Optional[AccountNamespacePolicy] = None,) -> dict:resolved_ctx = ctxif resolved_ctx is None and user is not None:@@ -281,16 +235,14 @@ def owner_fields_for_uri(resolved_ctx = RequestContext(user=user,role=Role.ROOT,- namespace_policy=policy or AccountNamespacePolicy(),)if resolved_ctx is None and account_id:from openviking.server.identity import Rolefrom openviking_cli.session.user_id import UserIdentifierresolved_ctx = RequestContext(- user=UserIdentifier(account_id, "default", "default"),+ user=UserIdentifier(account_id, "default"),role=Role.ROOT,- namespace_policy=policy or AccountNamespacePolicy(),)try:@@ -299,20 +251,16 @@ def owner_fields_for_uri(return {"uri": VikingURI.normalize(uri).rstrip("/"),"owner_user_id": None,- "owner_agent_id": None,}return {"uri": resolved.uri,"owner_user_id": resolved.owner_user_id,- "owner_agent_id": resolved.owner_agent_id,}def owner_space_for_uri(uri: str, ctx: RequestContext) -> str:"""Derive the legacy owner_space bucket for vector records from URI scope and context."""parts = uri_parts(uri)- if parts[:1] == ["agent"]:- return agent_space_fragment(ctx)if parts[:1] in (["user"], ["session"]):return user_space_fragment(ctx)return ""@@ -340,38 +288,13 @@ def _resolve_user_uri()user_id = second- policy = _require_policy(ctx)if len(parts) == 2:- if policy.isolate_user_scope_by_agent:- return ResolvedNamespace(- uri=f"viking://user/{user_id}",- scope="user",- owner_user_id=user_id,- is_container=True,- )return ResolvedNamespace(uri=f"viking://user/{user_id}",scope="user",owner_user_id=user_id,)- if policy.isolate_user_scope_by_agent:- if len(parts) < 4 or parts[2] != "agent":- raise NamespaceShapeError(- f"User URI must include /agent/{{agent_id}} under current policy: {normalized}"- )- agent_id = parts[3]- suffix = parts[4:]- canonical = f"viking://user/{user_id}/agent/{agent_id}"- if suffix:- canonical = f"{canonical}/{'/'.join(suffix)}"- return ResolvedNamespace(- uri=canonical,- scope="user",- owner_user_id=user_id,- owner_agent_id=agent_id,- )-suffix = parts[2:]canonical = f"viking://user/{user_id}"if suffix:@@ -383,71 +306,6 @@ def _resolve_user_uri()-def _resolve_agent_uri(- parts: list[str],- ctx: Optional[RequestContext],- *,- require_canonical: bool,-) -> ResolvedNamespace:- normalized = "viking://" + "/".join(parts)- if len(parts) == 1:- return ResolvedNamespace(uri="viking://agent", scope="agent", is_container=True)-- second = parts[1]- if second in _AGENT_SHORTHAND_SEGMENTS:- if require_canonical:- raise NamespaceShapeError(f"Shorthand agent URI is not allowed here: {normalized}")- if ctx is None:- raise NamespaceShapeError(f"Agent shorthand URI requires request context: {normalized}")- suffix = parts[1:]- return resolve_uri(- "/".join([canonical_agent_root(ctx)[len("viking://") :], *suffix]), ctx=ctx- )-- agent_id = second- policy = _require_policy(ctx)- if len(parts) == 2:- if policy.isolate_agent_scope_by_user:- return ResolvedNamespace(- uri=f"viking://agent/{agent_id}",- scope="agent",- owner_agent_id=agent_id,- is_container=True,- )- return ResolvedNamespace(- uri=f"viking://agent/{agent_id}",- scope="agent",- owner_agent_id=agent_id,- )-- if policy.isolate_agent_scope_by_user:- if len(parts) < 4 or parts[2] != "user":- raise NamespaceShapeError(- f"Agent URI must include /user/{{user_id}} under current policy: {normalized}"- )- user_id = parts[3]- suffix = parts[4:]- canonical = f"viking://agent/{agent_id}/user/{user_id}"- if suffix:- canonical = f"{canonical}/{'/'.join(suffix)}"- return ResolvedNamespace(- uri=canonical,- scope="agent",- owner_user_id=user_id,- owner_agent_id=agent_id,- )-- suffix = parts[2:]- canonical = f"viking://agent/{agent_id}"- if suffix:- canonical = f"{canonical}/{'/'.join(suffix)}"- return ResolvedNamespace(- uri=canonical,- scope="agent",- owner_agent_id=agent_id,- )--def _resolve_session_uri(parts: list[str]) -> ResolvedNamespace:if len(parts) == 1:return ResolvedNamespace(uri="viking://session", scope="session", is_container=True)@@ -456,9 +314,3 @@ def _resolve_session_uri(parts: list[str]) -> ResolvedNamespace:if len(parts) > 2:canonical = f"{canonical}/{'/'.join(parts[2:])}"return ResolvedNamespace(uri=canonical, scope="session")---def _require_policy(ctx: Optional[RequestContext]) -> AccountNamespacePolicy:- if ctx is None:- return AccountNamespacePolicy()- return ctx.namespace_policydiff --git a/openviking/core/peer_id.py b/openviking/core/peer_id.pynew file mode 100644index 000000000..4246f06ca--- /dev/null+++ b/openviking/core/peer_id.py@@ -0,0 +1,27 @@+"""Helpers for peer identity fields."""++from __future__ import annotations++from typing import Optional+++def normalize_peer_id(+ peer_id: Optional[str],+) -> Optional[str]:+ """Normalize a peer_id value."""+ if peer_id == "":+ peer_id = None++ normalized = peer_id+ if normalized and ("/" in normalized or "\\" in normalized):+ raise ValueError("peer_id must not contain path separators")+ return normalized+++def safe_peer_id(peer_id: Optional[str]) -> Optional[str]:+ """Return a usable peer_id, or None for empty/path-like values."""+ if not peer_id:+ return None+ if "/" in peer_id or "\\" in peer_id:+ return None+ return peer_iddiff --git a/openviking/core/retrieval_targets.py b/openviking/core/retrieval_targets.pynew file mode 100644index 000000000..12a624de4--- /dev/null+++ b/openviking/core/retrieval_targets.py@@ -0,0 +1,170 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Retrieval-only target resolution for search/find."""++from dataclasses import dataclass+from typing import List, Optional, Union++from openviking.core.namespace import (+ NamespaceShapeError,+ canonical_user_root,+ canonicalize_uri,+ uri_parts,+)+from openviking.core.peer_id import normalize_peer_id+from openviking.server.identity import RequestContext, Role+from openviking_cli.exceptions import InvalidArgumentError+from openviking_cli.retrieve import ContextType+from openviking_cli.utils.uri import VikingURI+++@dataclass(frozen=True)+class ResolvedRetrievalTargets:+ """Resolved retrieval target directories for find/search."""++ target_directories: List[str]+ first_explicit_directory: str = ""+++def resolve_retrieval_targets(+ target_uri: Union[str, List[str]],+ ctx: RequestContext,+ peer_id: Optional[str],+) -> ResolvedRetrievalTargets:+ """Resolve search/find target directories."""+ normalized_peer_id = _normalize_peer_id(peer_id)+ target_uris = _canonicalize_target_uris(target_uri, ctx)++ if not target_uris:+ return ResolvedRetrievalTargets(+ target_directories=default_target_directories(ctx, peer_id=normalized_peer_id),+ )++ target_directories: List[str] = []+ for target in target_uris:+ for target_dir in _target_directories_for_uri(target, ctx=ctx, peer_id=normalized_peer_id):+ if target_dir not in target_directories:+ target_directories.append(target_dir)+ return ResolvedRetrievalTargets(+ target_directories=target_directories,+ first_explicit_directory=target_directories[0] if target_directories else "",+ )+++def default_target_directories(+ ctx: Optional[RequestContext],+ *,+ peer_id: Optional[str] = None,+ context_type: Optional[ContextType] = None,+) -> List[str]:+ """Return default retrieval directories for a user context."""+ if not ctx or ctx.role == Role.ROOT:+ return []++ user_root = canonical_user_root(ctx)+ if context_type == ContextType.MEMORY:+ return _default_memory_targets(ctx, peer_id)+ if context_type == ContextType.RESOURCE:+ return ["viking://resources"]+ if context_type == ContextType.SKILL:+ return [f"{user_root}/skills"]+ return [+ *_default_memory_targets(ctx, peer_id),+ "viking://resources",+ f"{user_root}/skills",+ ]+++def _normalize_peer_id(peer_id: Optional[str]) -> Optional[str]:+ try:+ return normalize_peer_id(peer_id)+ except ValueError as exc:+ raise InvalidArgumentError(str(exc)) from exc+++def _canonicalize_target_uris(+ target_uri: Union[str, List[str]],+ ctx: RequestContext,+) -> List[str]:+ target_uri_list = [target_uri] if isinstance(target_uri, str) else (target_uri or [])+ target_uris: List[str] = []+ for item in target_uri_list:+ if not item or item in {"/", "viking://"}:+ continue+ try:+ target_uri = canonicalize_uri(item, ctx)+ except NamespaceShapeError as exc:+ raise InvalidArgumentError(str(exc)) from exc+ if target_uri not in target_uris:+ target_uris.append(target_uri)+ return target_uris+++def _target_directories_for_uri(+ target_uri: str,+ *,+ ctx: RequestContext,+ peer_id: Optional[str],+) -> List[str]:+ if _is_current_user_root(target_uri, ctx):+ return [*_default_memory_targets(ctx, peer_id), f"{canonical_user_root(ctx)}/skills"]++ peer_target = _resolve_peer_memory_target(target_uri, ctx=ctx, peer_id=peer_id)+ if peer_target is not None:+ return [peer_target]++ if _is_default_user_memory_root(target_uri, ctx):+ return _default_memory_targets(ctx, peer_id)++ return [target_uri]+++def _default_memory_targets(ctx: RequestContext, peer_id: Optional[str]) -> List[str]:+ user_root = canonical_user_root(ctx)+ targets = [f"{user_root}/memories"]+ if peer_id:+ targets.append(f"{user_root}/peers/{peer_id}/memories")+ return targets+++def _resolve_peer_memory_target(+ target_uri: str,+ *,+ ctx: RequestContext,+ peer_id: Optional[str],+) -> Optional[str]:+ parts = uri_parts(target_uri)+ user_root_parts = uri_parts(canonical_user_root(ctx))+ if parts[: len(user_root_parts)] != user_root_parts:+ return None++ suffix = parts[len(user_root_parts) :]+ if not suffix or suffix[0] != "peers":+ return None++ if len(suffix) == 1:+ raise InvalidArgumentError("target_uri must not point at all peer memories.")++ target_peer_id = suffix[1]+ if peer_id and target_peer_id != peer_id:+ raise InvalidArgumentError("target_uri peer does not match peer_id.")++ peer_root = f"{canonical_user_root(ctx)}/peers/{target_peer_id}"+ if len(suffix) == 2:+ return f"{peer_root}/memories"+ if suffix[2] != "memories":+ raise InvalidArgumentError("Only peer memory targets are searchable.")+ return target_uri+++def _is_current_user_root(target_uri: str, ctx: RequestContext) -> bool:+ normalized = VikingURI.normalize(target_uri).rstrip("/")+ return normalized in {"viking://user", canonical_user_root(ctx).rstrip("/")}+++def _is_default_user_memory_root(target_uri: str, ctx: RequestContext) -> bool:+ normalized = VikingURI.normalize(target_uri).rstrip("/")+ return normalized in {+ "viking://user/memories",+ f"{canonical_user_root(ctx).rstrip('/')}/memories",+ }diff --git a/openviking/eval/datasets/local_doc_example_glm5.jsonl b/openviking/eval/datasets/local_doc_example_glm5.jsonlindex dcfb23781..3032461b7 100644--- a/openviking/eval/datasets/local_doc_example_glm5.jsonl+++ b/openviking/eval/datasets/local_doc_example_glm5.jsonl@@ -1,9 +1,9 @@{"question": "OpenViking 的核心定位是什么?与传统向量数据库(如 Milvus、Pinecone)有何本质区别?", "files": ["OpenViking/README.md", "OpenViking/docs/en/concepts/01-architecture.md"], "answer": "OpenViking 是一个专门为 AI Agent 设计的开源上下文数据库(Context Database)。与传统向量数据库的本质区别在于:\n\n1. **设计范式不同**:OpenViking 采用\"文件系统范式\"统一管理记忆、资源和技能,而传统向量数据库仅提供扁平的向量存储。\n\n2. **解决的问题不同**:OpenViking 解决 Agent 开发中的五大挑战:上下文碎片化、上下文需求激增、检索效果差、上下文不可观察、记忆迭代受限。传统向量数据库主要解决向量检索问题。\n\n3. **功能特性不同**:\n - 分层上下文加载(L0/L1/L2三层结构)显著降低 Token 消耗\n - 目录递归检索结合目录定位与语义搜索\n - 可视化检索轨迹,支持调试\n - 自动会话管理,实现上下文自我迭代\n\n4. **架构层次**:OpenViking 包含 Client、Service、Retrieve、Session、Parse、Compressor、Storage 等多层架构,而传统向量数据库主要是存储和检索层。"}{"question": "分层记忆设计(L0 抽象层、L1 概述层、L2 内容层)的设计初衷是什么?三层之间如何保持语义一致性?", "files": ["OpenViking/docs/en/concepts/03-context-layers.md"], "answer": "分层记忆设计的初衷是平衡检索效率与内容完整性。\n\n**三层结构说明**:\n- **L0(Abstract)**:最简洁的内容表示,约100 tokens,用于向量检索和快速过滤,存储在 `.abstract.md` 文件中。\n- **L1(Overview)**:约2k tokens的综合摘要,包含导航指引,用于重排序和理解访问方式,存储在 `.overview.md` 文件中。\n- **L2(Detail)**:完整原始内容,无 token 限制,仅在确认需要时加载。\n\n**语义一致性保证**:\n1. **生成机制**:SemanticProcessor 采用自底向上的方式遍历目录,为每个节点生成 L0/L1,确保层级间的语义关联。\n2. **统一来源**:所有层级都源自同一份原始内容,L0 是 L1 的精炼,L1 是 L2 的结构化摘要。\n3. **渐进式加载**:检索时先通过 L0 定位,再通过 L1 确认相关性,最后按需加载 L2,保证语义传递。\n\n**API 支持**:\n```python\nabstract = client.abstract(\"viking://resources/docs/auth\") # L0\noverview = client.overview(\"viking://resources/docs/auth\") # L1\ncontent = client.read(\"viking://resources/docs/auth/oauth.md\") # L2\n```"}-{"question": "六种记忆类别(profile、preferences、entities、events、cases、patterns)的划分依据是什么?在实际应用中如何自动分类?", "files": ["OpenViking/docs/en/concepts/02-context-types.md", "OpenViking/openviking/session/compressor_v2.py"], "answer": "六种记忆类别基于人类认知模式的简化和工程考量进行划分。\n\n**划分依据**:\n\n**用户记忆**:\n- **profile**:用户基本信息,存储在 `user/memories/.overview.md`\n- **preferences**:用户偏好,按主题聚合,存储在 `user/memories/preferences/`\n- **entities**:实体记忆(人、项目、概念),存储在 `user/memories/entities/`\n- **events**:事件记录(决策、里程碑),存储在 `user/memories/events/`\n\n**Agent 记忆**:\n- **cases**:学习到的案例,存储在 `agent/memories/cases/`\n- **patterns**:学习到的模式,存储在 `agent/memories/patterns/`\n\n**自动分类机制**:\nSessionCompressorV2 通过 v2 memory schema 和 ExtractLoop 自动提取和更新记忆。流程如下:\n1. 格式化会话消息\n2. 调用 v2 memory schema templates 和 ExtractLoop\n3. LLM 返回结构化的 memory operations\n4. 根据 category 写入对应目录\n\n**更新策略**:\n- profile、preferences、entities:可追加更新\n- events、cases、patterns:不更新,作为历史记录"}-{"question": "OpenViking 如何支持多 Agent 协作场景?不同 Agent 之间的记忆如何隔离与共享?", "files": ["OpenViking/docs/en/concepts/02-context-types.md", "OpenViking/docs/en/concepts/01-architecture.md"], "answer": "OpenViking 通过 URI 命名空间和作用域设计支持多 Agent 协作。\n\n**记忆隔离机制**:\n1. **URI 命名空间**:\n - `viking://user/memories/` - 用户级记忆\n - `viking://agent/memories/` - Agent 级记忆\n - `viking://resources/` - 共享资源\n - `viking://agent/skills/` - Agent 技能\n\n2. **作用域划分**:\n - **User Scope**:用户相关的 profile、preferences、entities、events\n - **Agent Scope**:Agent 学习到的 cases、patterns\n - **Resources Scope**:共享的知识库\n\n**记忆共享机制**:\n1. **资源层共享**:所有 Agent 可以访问 `viking://resources/` 下的共享知识库。\n2. **用户记忆共享**:同一用户的不同 Agent 可以共享 `viking://user/memories/` 下的用户偏好和实体记忆。\n3. **关系管理**:通过 `.relations.json` 建立资源间的关联关系,支持跨 Agent 的上下文关联。\n\n**实际应用**:\n```python\n# Agent A 添加资源\nclient.add_resource(\"./docs/api.pdf\", to=\"viking://resources/api\")\n\n# Agent B 可以检索到\nresults = client.find(\"API usage\", target_uri=\"viking://resources/\")\n```"}+{"question": "六种记忆类别(profile、preferences、entities、events、trajectories、experiences)的划分依据是什么?在实际应用中如何自动分类?", "files": ["OpenViking/docs/en/concepts/02-context-types.md", "OpenViking/openviking/session/compressor_v2.py"], "answer": "六种记忆类别基于人类认知模式的简化和工程考量进行划分。\n\n**划分依据**:\n\n**用户记忆**:\n- **profile**:用户基本信息,存储在 `user/memories/.overview.md`\n- **preferences**:用户偏好,按主题聚合,存储在 `user/memories/preferences/`\n- **entities**:实体记忆(人、项目、概念),存储在 `user/memories/entities/`\n- **events**:事件记录(决策、里程碑),存储在 `user/memories/events/`\n\n**执行记忆**:\n- **trajectories**:学习到的案例,存储在 `user/memories/trajectories/`\n- **experiences**:学习到的模式,存储在 `user/memories/experiences/`\n\n**自动分类机制**:\nSessionCompressorV2 通过 v2 memory schema 和 ExtractLoop 自动提取和更新记忆。流程如下:\n1. 格式化会话消息\n2. 调用 v2 memory schema templates 和 ExtractLoop\n3. LLM 返回结构化的 memory operations\n4. 根据 category 写入对应目录\n\n**更新策略**:\n- profile、preferences、entities:可追加更新\n- events、trajectories、experiences:不更新,作为历史记录"}+{"question": "OpenViking 如何支持多 Agent 协作场景?不同 Agent 之间的记忆如何隔离与共享?", "files": ["OpenViking/docs/en/concepts/02-context-types.md", "OpenViking/docs/en/concepts/01-architecture.md"], "answer": "OpenViking 通过 URI 命名空间和作用域设计支持多 Agent 协作。\n\n**记忆隔离机制**:\n1. **URI 命名空间**:\n - `viking://user/memories/` - 用户级记忆\n - `viking://user/{user_id}/peers/{peer_id}/memories/` - Peer 级记忆\n - `viking://resources/` - 共享资源\n - `viking://user/skills/` - User 技能\n\n2. **作用域划分**:\n - **User Scope**:用户相关的 profile、preferences、entities、events\n - **Peer/Execution Scope**:Agent 学习到的 trajectories、experiences\n - **Resources Scope**:共享的知识库\n\n**记忆共享机制**:\n1. **资源层共享**:所有 Agent 可以访问 `viking://resources/` 下的共享知识库。\n2. **用户记忆共享**:同一用户的不同 Agent 可以共享 `viking://user/memories/` 下的用户偏好和实体记忆。\n3. **关系管理**:通过 `.relations.json` 建立资源间的关联关系,支持跨 Agent 的上下文关联。\n\n**实际应用**:\n```python\n# Agent A 添加资源\nclient.add_resource(\"./docs/api.pdf\", to=\"viking://resources/api\")\n\n# Agent B 可以检索到\nresults = client.find(\"API usage\", target_uri=\"viking://resources/\")\n```"}{"question": "会话的生命周期是如何管理的?commit_session 后记忆如何被持久化和索引?", "files": ["OpenViking/docs/en/concepts/08-session.md"], "answer": "会话生命周期遵循:创建 → 交互 → 提交 的模式。\n\n**生命周期管理**:\n1. **创建**:`session = client.session(session_id=\"chat_001\")`\n2. **交互**:\n - `session.add_message(role, parts)` - 添加消息\n - `session.used(contexts, skill)` - 记录使用的上下文/技能\n3. **提交**:`session.commit()` - 归档并提取记忆\n\n**commit 后的持久化流程**:\n1. **归档流程**:\n - 增加 compression_index\n - 复制当前消息到归档目录\n - 生成结构化摘要(LLM)\n - 清空当前消息列表\n\n2. **记忆提取**:\n - SessionCompressorV2 从消息中提取和更新记忆\n - 生成 L0(abstract)和 L1(overview)\n - 写入对应的 VikingFS 目录\n\n3. **索引构建**:\n - 对新生成的记忆内容进行向量化\n - 写入 Vector Index 支持语义检索\n\n**消息结构**:\n- Message:id、role、parts、created_at\n- Part 类型:TextPart、ContextPart、ToolPart\n\n**返回结果**:\n```python\n{\n \"status\": \"committed\",\n \"memories_extracted\": 5,\n \"active_count_updated\": 2,\n \"archived\": True\n}\n```"}-{"question": "技能系统的设计理念是什么?与传统的 Function Calling 或 Tool Use 有何不同?", "files": ["OpenViking/docs/en/api/04-skills.md", "OpenViking/docs/en/concepts/02-context-types.md"], "answer": "技能系统的设计理念是将 Agent 可调用的能力统一管理,与 Function Calling 的区别在于存储和检索方式。\n\n**设计理念**:\n1. **统一存储**:技能作为上下文的一种类型,与记忆、资源采用相同的存储范式。\n2. **分层描述**:技能同样有 L0(简短描述)、L1(详细概述)、L2(完整定义)三层结构。\n3. **语义检索**:支持通过自然语言描述检索相关技能。\n\n**与传统 Function Calling 的区别**:\n| 维度 | OpenViking Skills | Function Calling |\n|------|-------------------|-----------------|\n| 存储方式 | 文件系统 + 向量索引 | 代码定义 |\n| 检索方式 | 语义检索 + 目录定位 | 精确匹配 |\n| 描述层次 | L0/L1/L2 三层 | 单层描述 |\n| 上下文关联 | 支持关系管理 | 无 |\n\n**存储位置**:\n```\nviking://agent/skills/{skill-name}/\n├── .abstract.md # L0: 简短描述\n├── SKILL.md # L1: 详细概述\n└── scripts # L2: 完整定义\n```\n\n**支持的数据格式**:\n1. Dict(Skill 格式)\n2. Dict(MCP Tool 格式)- 自动检测并转换\n3. String(SKILL.md 内容)\n4. Path(文件或目录)"}+{"question": "技能系统的设计理念是什么?与传统的 Function Calling 或 Tool Use 有何不同?", "files": ["OpenViking/docs/en/api/04-skills.md", "OpenViking/docs/en/concepts/02-context-types.md"], "answer": "技能系统的设计理念是将 Agent 可调用的能力统一管理,与 Function Calling 的区别在于存储和检索方式。\n\n**设计理念**:\n1. **统一存储**:技能作为上下文的一种类型,与记忆、资源采用相同的存储范式。\n2. **分层描述**:技能同样有 L0(简短描述)、L1(详细概述)、L2(完整定义)三层结构。\n3. **语义检索**:支持通过自然语言描述检索相关技能。\n\n**与传统 Function Calling 的区别**:\n| 维度 | OpenViking Skills | Function Calling |\n|------|-------------------|-----------------|\n| 存储方式 | 文件系统 + 向量索引 | 代码定义 |\n| 检索方式 | 语义检索 + 目录定位 | 精确匹配 |\n| 描述层次 | L0/L1/L2 三层 | 单层描述 |\n| 上下文关联 | 支持关系管理 | 无 |\n\n**存储位置**:\n```\nviking://user/skills/{skill-name}/\n├── .abstract.md # L0: 简短描述\n├── SKILL.md # L1: 详细概述\n└── scripts # L2: 完整定义\n```\n\n**支持的数据格式**:\n1. Dict(Skill 格式)\n2. Dict(MCP Tool 格式)- 自动检测并转换\n3. String(SKILL.md 内容)\n4. Path(文件或目录)"}{"question": "OpenViking 适合哪些具体的应用场景?例如:长期记忆助手、知识库问答、代码助手等场景的适配性如何?", "files": ["OpenViking/README.md", "OpenViking/docs/en/concepts/01-architecture.md"], "answer": "OpenViking 专为 AI Agent 设计,适合需要长期上下文管理的场景。\n\n**核心应用场景**:\n\n1. **长期记忆助手**:\n - 自动从会话中提取用户偏好、实体记忆\n - 支持跨会话的记忆累积和检索\n - 适配性:★★★★★(核心场景)\n\n2. **知识库问答**:\n - 支持 PDF、Markdown、HTML 等多种文档格式\n - 分层检索提高效率和准确性\n - 适配性:★★★★★(核心场景)\n\n3. **代码助手**:\n - 支持代码仓库解析(Git/Zip)\n - 自动过滤非代码目录(.git、node_modules)\n - 语义检索代码片段\n - 适配性:★★★★☆(支持代码解析)\n\n4. **多模态助手**:\n - 支持图片、视频、音频处理\n - VLM 描述和向量化\n - 适配性:★★★★☆(需要 VLM 支持)\n\n5. **企业知识管理**:\n - 统一管理文档、代码、技能\n - 支持关系管理和关联检索\n - 适配性:★★★★★(核心场景)\n\n**场景适配关键能力**:\n- 分层上下文加载:降低 Token 成本\n- 目录递归检索:提高检索精度\n- 可视化检索轨迹:便于调试优化\n- 自动会话管理:实现记忆迭代"}{"question": "如何评估 OpenViking 的检索质量?是否有内置的评测机制或指标?", "files": ["OpenViking/openviking/eval/__init__.py:1-25", "OpenViking/examples/eval/rag_eval.py"], "answer": "OpenViking 提供了 eval 评估模块,支持 RAGAS 等主流评测工具集成。\n\n**内置评测机制**:\n\n1. **eval 模块组成**:\n - `EvalSample`:评估样本数据结构\n - `EvalDataset`:评估数据集\n - `RagasEvaluator`:RAGAS 评测适配器\n - `RAGQueryPipeline`:RAG 查询流水线\n\n2. **支持的评测指标**(通过 RAGAS):\n - **faithfulness**:答案忠实度\n - **answer_relevance**:答案相关性\n - **context_precision**:上下文精确度\n - **context_recall**:上下文召回率\n\n3. **评测流程**:\n```python\n# 准备评估样本\nsamples = [EvalSample(\n query=\"问题\",\n context=[\"检索到的上下文\"],\n response=\"生成的答案\",\n ground_truth=\"标准答案\"\n)]\n\n# 运行评测\nevaluator = RagasEvaluator()\nsummary = await evaluator.evaluate_dataset(dataset)\n```\n\n4. **CLI 评测工具**:\n```bash\nuv run rag_eval.py \\\n --docs_dir ./docs \\\n --question_file ./questions.json \\\n --output ./results.json\n```\n\n**评测报告输出**:\n- 平均分数(mean_scores)\n- 每个样本的详细分数\n- JSON 格式结果保存"}{"question": "OpenViking 与主流 RAG 框架(LlamaIndex、LangChain)的集成方式是什么?是否可以无缝替换其向量存储组件?", "files": ["OpenViking/docs/en/concepts/05-storage.md", "OpenViking/docs/en/api/06-retrieval.md"], "answer": "OpenViking 采用独立的存储架构,通过 API 接口与 RAG 框架集成。\n\n**存储架构**:\nOpenViking 使用双层存储架构,分离内容存储与索引存储:\n- **AGFS**:内容存储层,存储 L0/L1/L2 全部内容、多媒体文件、关系\n- **Vector Index**:索引存储层,存储 URI、向量、元数据(不含文件内容)\n\n**与 RAG 框架的集成方式**:\n\n1. **API 层集成**:\n - 提供 `find()` 和 `search()` API\n - `find()`:基础向量相似度搜索\n - `search()`:复杂检索(意图分析、会话上下文、查询扩展)\n\n2. **检索结果结构**:\n```python\nclass FindResult:\n memories: List[MatchedContext] # 记忆上下文\n resources: List[MatchedContext] # 资源上下文\n skills: List[MatchedContext] # 技能上下文\n```\n\n3. **替换向量存储的可行性**:\n - 可以通过 HTTP API 与 LlamaIndex/LangChain 集成\n - 但 OpenViking 提供的是完整的上下文管理方案,不仅仅是向量存储\n - 建议作为独立的上下文管理层使用\n\n**HTTP API 支持**:\n```bash\nPOST /api/v1/search/find\n{\n \"query\": \"how to authenticate users\",\n \"limit\": 10\n}\n```"}@@ -14,7 +14,7 @@{"question": "配置文件 `ov.conf` 的必填项有哪些?如何配置不同的 VLM 后端(OpenAI、Volcengine 等)?", "files": ["OpenViking/docs/en/guides/01-configuration.md:1-150"], "answer": "配置文件 `ov.conf` 包含 embedding、vlm、rerank、storage 等配置项。\n\n**必填配置项**:\n\n```json\n{\n \"embedding\": {\n \"dense\": {\n \"provider\": \"volcengine\", // 必填:volcengine/openai/vikingdb\n \"api_key\": \"your-api-key\", // 必填\n \"model\": \"doubao-embedding-vision-251215\",\n \"dimension\": 1024\n }\n },\n \"vlm\": {\n \"provider\": \"volcengine\", // 必填\n \"api_key\": \"your-api-key\", // 必填\n \"model\": \"doubao-seed-2-0-pro-260215\"\n }\n}\n```\n\n**VLM 后端配置**:\n\n1. **Volcengine(豆包模型)**:\n```json\n{\n \"vlm\": {\n \"api_base\": \"https://ark.cn-beijing.volces.com/api/v3\",\n \"api_key\": \"your-volcengine-api-key\",\n \"provider\": \"volcengine\",\n \"model\": \"doubao-seed-2-0-pro-260215\"\n }\n}\n```\n\n2. **OpenAI**:\n```json\n{\n \"vlm\": {\n \"api_base\": \"https://api.openai.com/v1\",\n \"api_key\": \"your-openai-api-key\",\n \"provider\": \"openai\",\n \"model\": \"gpt-4-vision-preview\"\n }\n}\n```\n\n**Embedding 配置**:\n\n| 参数 | 说明 |\n|------|------|\n| `provider` | volcengine/openai/vikingdb |\n| `api_key` | API 密钥 |\n| `model` | 模型名称 |\n| `dimension` | 向量维度 |\n| `input` | 输入类型:text/multimodal |\n\n**可选配置**:\n- `rerank`:重排序模型配置\n- `storage`:存储后端配置"}{"question": "`HierarchicalRetriever` 的检索流程是怎样的?如何实现从 L0 到 L2 的层级穿透检索?", "files": ["OpenViking/openviking/retrieve/hierarchical_retriever.py"], "answer": "HierarchicalRetriever 实现目录递归检索和层级穿透。\n\n**检索流程**:\n\n1. **初始化**:\n```python\nclass HierarchicalRetriever:\n MAX_CONVERGENCE_ROUNDS = 3 # 收敛轮次\n MAX_RELATIONS = 5 # 最大关联数\n SCORE_PROPAGATION_ALPHA = 0.5 # 分数传播系数\n DIRECTORY_DOMINANCE_RATIO = 1.2 # 目录分数阈值\n GLOBAL_SEARCH_TOPK = 3 # 全局检索数量\n```\n\n2. **检索模式**:\n - **THINKING**:深度思考模式\n - **QUICK**:快速检索模式\n\n3. **核心方法**:\n```python\nasync def retrieve(\n self,\n query: TypedQuery,\n limit: int = 5,\n mode: RetrieverMode = RetrieverMode.THINKING,\n score_threshold: Optional[float] = None,\n metadata_filter: Optional[Dict[str, Any]] = None,\n) -> QueryResult:\n```\n\n**层级穿透机制**:\n\n1. **L0 检索**:\n - 向量相似度搜索 `.abstract.md` 内容\n - 快速过滤不相关内容\n\n2. **L1 确认**:\n - 读取 `.overview.md` 进行重排序\n - 确认内容相关性\n\n3. **L2 加载**:\n - 按需读取完整内容\n - 仅在确认需要时加载\n\n**关键特性**:\n- 分数传播:目录分数向子节点传播\n- 目录优势:目录分数需超过最大子节点分数\n- 关联检索:自动检索关联上下文"}{"question": "语义处理队列的工作机制是什么?如何监控和调试异步处理状态?", "files": ["OpenViking/docs/en/concepts/01-architecture.md", "OpenViking/openviking/service/resource_service.py:1-80"], "answer": "语义处理队列通过 SemanticQueue 异步生成 L0/L1 内容。\n\n**工作机制**:\n\n1. **处理流水线**:\n```\nInput → Parser → TreeBuilder → AGFS → SemanticQueue → Vector Index\n```\n\n2. **队列处理**:\n - TreeBuilder 将文件移动到 AGFS 后入队\n - SemanticQueue 异步处理队列项\n - 自底向上生成 L0/L1\n\n3. **异步处理优势**:\n - 不阻塞资源添加操作\n - 支持大规模文档处理\n - LLM 调用并行化\n\n**监控和调试**:\n\n1. **等待处理完成**:\n```python\nresult = client.add_resource(\"./docs\", wait=False)\nclient.wait_processed() # 等待队列处理完成\n```\n\n2. **超时控制**:\n```python\nresult = client.add_resource(\n \"./docs\",\n wait=True,\n timeout=300 # 超时时间(秒)\n)\n```\n\n3. **DebugService**:\n - 提供 ObserverService 用于调试\n - 可视化检索轨迹\n\n4. **日志监控**:\n - 通过 logger 获取处理状态\n - 监控队列长度和处理延迟\n\n**Service 层支持**:\n- ResourceService 管理 add_resource 操作\n- wait_processed() 方法等待语义处理完成"}-{"question": "如何通过代码动态创建和管理 Session?Session 与 Memory 的关系是什么?", "files": ["OpenViking/docs/en/concepts/08-session.md", "OpenViking/openviking/session/compressor_v2.py"], "answer": "Session 通过 client API 动态创建,commit 后自动提取 Memory。\n\n**Session 创建和管理**:\n\n1. **创建 Session**:\n```python\n# 创建新会话\nsession = client.session(session_id=\"chat_001\")\n\n# 或使用 create_session\nresult = client.create_session()\n```\n\n2. **添加消息**:\n```python\nsession.add_message(\n \"user\",\n [TextPart(\"How to configure embedding?\")]\n)\n\nsession.add_message(\n \"assistant\",\n [\n TextPart(\"Here's how...\"),\n ContextPart(uri=\"viking://user/memories/profile.md\"),\n ]\n)\n```\n\n3. **记录使用**:\n```python\nsession.used(contexts=[\"viking://user/memories/profile.md\"])\nsession.used(skill={\n \"uri\": \"viking://agent/skills/code-search\",\n \"input\": \"search config\",\n \"output\": \"found 3 files\",\n \"success\": True\n})\n```\n\n4. **提交会话**:\n```python\nresult = session.commit()\n# {\"status\": \"committed\", \"memories_extracted\": 5}\n```\n\n**Session 与 Memory 的关系**:\n\n1. **Memory 来源**:\n - Memory 从 Session 消息中提取\n - SessionCompressorV2 在 commit 时触发\n\n2. **提取流程**:\n - 格式化会话消息\n - 调用 LLM 提取 6 类记忆\n - 写入对应目录并索引\n\n3. **记忆类别映射**:\n - profile → `user/memories/profile.md`\n - preferences → `user/memories/preferences/`\n - entities → `user/memories/entities/`\n - events → `user/memories/events/`\n - cases → `agent/memories/cases/`\n - patterns → `agent/memories/patterns/`"}+{"question": "如何通过代码动态创建和管理 Session?Session 与 Memory 的关系是什么?", "files": ["OpenViking/docs/en/concepts/08-session.md", "OpenViking/openviking/session/compressor_v2.py"], "answer": "Session 通过 client API 动态创建,commit 后自动提取 Memory。\n\n**Session 创建和管理**:\n\n1. **创建 Session**:\n```python\n# 创建新会话\nsession = client.session(session_id=\"chat_001\")\n\n# 或使用 create_session\nresult = client.create_session()\n```\n\n2. **添加消息**:\n```python\nsession.add_message(\n \"user\",\n [TextPart(\"How to configure embedding?\")]\n)\n\nsession.add_message(\n \"assistant\",\n [\n TextPart(\"Here's how...\"),\n ContextPart(uri=\"viking://user/memories/profile.md\"),\n ]\n)\n```\n\n3. **记录使用**:\n```python\nsession.used(contexts=[\"viking://user/memories/profile.md\"])\nsession.used(skill={\n \"uri\": \"viking://user/skills/code-search\",\n \"input\": \"search config\",\n \"output\": \"found 3 files\",\n \"success\": True\n})\n```\n\n4. **提交会话**:\n```python\nresult = session.commit()\n# {\"status\": \"committed\", \"memories_extracted\": 5}\n```\n\n**Session 与 Memory 的关系**:\n\n1. **Memory 来源**:\n - Memory 从 Session 消息中提取\n - SessionCompressorV2 在 commit 时触发\n\n2. **提取流程**:\n - 格式化会话消息\n - 调用 LLM 提取 6 类记忆\n - 写入对应目录并索引\n\n3. **记忆类别映射**:\n - profile → `user/memories/profile.md`\n - preferences → `user/memories/preferences/`\n - entities → `user/memories/entities/`\n - events → `user/memories/events/`\n - trajectories → `user/memories/trajectories/`\n - experiences → `user/memories/experiences/`"}{"question": "OpenViking Server 模式与本地模式的区别是什么?如何选择部署方式?", "files": ["OpenViking/openviking/server/bootstrap.py:1-61", "OpenViking/docs/en/concepts/01-architecture.md"], "answer": "Server 模式提供 HTTP API,本地模式直接嵌入应用。\n\n**模式对比**:\n\n| 维度 | 本地模式 | Server 模式 |\n|------|----------|-------------|\n| 访问方式 | Python SDK | HTTP API |\n| 部署复杂度 | 简单 | 需启动服务 |\n| 多客户端 | 不支持 | 支持 |\n| 资源共享 | 单进程 | 多进程共享 |\n| 适用场景 | 单机应用 | 生产环境 |\n\n**Server 模式启动**:\n\n1. **命令行启动**:\n```bash\nopenviking-server --host 0.0.0.0 --port 1933 --config ./ov.conf\n```\n\n2. **参数说明**:\n- `--host`:绑定地址\n- `--port`:端口号\n- `--config`:配置文件路径\n\n3. **HTTP API 示例**:\n```bash\ncurl -X POST http://localhost:1933/api/v1/resources \\\n -H \"Content-Type: application/json\" \\\n -H \"X-API-Key: your-key\" \\\n -d '{\"path\": \"./documents/guide.md\"}'\n```\n\n**部署方式选择**:\n\n1. **选择本地模式**:\n - 单机应用开发\n - 快速原型验证\n - 无需多客户端访问\n\n2. **选择 Server 模式**:\n - 生产环境部署\n - 多客户端/多服务访问\n - 需要集中式上下文管理\n - 微服务架构集成\n\n**Service 层复用**:\n两种模式共享 Service 层逻辑,支持 HTTP Server 和 CLI 复用。"}{"question": "如何扩展自定义的 Parser?例如支持新的文档格式或代码语言?", "files": ["OpenViking/openviking/parse/registry.py", "OpenViking/openviking/parse/parsers/base_parser.py:1-80"], "answer": "通过 ParserRegistry 注册自定义 Parser,支持 Protocol 接口。\n\n**自定义 Parser 步骤**:\n\n1. **实现 BaseParser 接口**:\n```python\nclass BaseParser(ABC):\n @abstractmethod\n async def parse(self, source: Union[str, Path], instruction: str = \"\", **kwargs) -> ParseResult:\n \"\"\"解析文档\"\"\"\n pass\n \n @abstractmethod\n async def parse_content(self, content: str, source_path: Optional[str] = None, **kwargs) -> ParseResult:\n \"\"\"解析内容\"\"\"\n pass\n \n @property\n @abstractmethod\n def supported_extensions(self) -> List[str]:\n \"\"\"支持的文件扩展名\"\"\"\n pass\n```\n\n2. **注册 Parser**:\n```python\nfrom openviking.parse.registry import get_registry\n\nclass MyParser(BaseParser):\n @property\n def supported_extensions(self) -> List[str]:\n return [\".myext\"]\n \n async def parse(self, source, instruction=\"\", **kwargs):\n # 实现解析逻辑\n return ParseResult(...)\n\n# 注册\nregistry = get_registry()\nregistry.register(\"my_parser\", MyParser())\n```\n\n3. **使用 Protocol 接口**:\n```python\nregistry.register_custom(\n handler=my_parser, # 实现 CustomParserProtocol\n extensions=[\".custom\"],\n name=\"custom_parser\"\n)\n```\n\n**内置 Parser**:\n- TextParser:纯文本\n- MarkdownParser:Markdown\n- PDFParser:PDF\n- HTMLParser:HTML\n- CodeRepositoryParser:代码仓库\n- ImageParser:图片(可选)\n\n**扩展点**:\n- `supported_extensions`:定义支持的扩展名\n- `can_parse()`:检查文件是否可解析\n- `_read_file()`:读取文件内容"}{"question": "eval 模块的 RAGAS 集成是如何实现的?如何自定义评测指标?", "files": ["OpenViking/openviking/eval/ragas.py", "OpenViking/openviking/eval/base.py:1-60"], "answer": "eval 模块通过 RagasEvaluator 适配器集成 RAGAS,支持自定义评测指标。\n\n**RAGAS 集成实现**:\n\n1. **RagasEvaluator 类**:\n```python\nclass RagasEvaluator(BaseEvaluator):\n def __init__(self, metrics=None, llm=None, embeddings=None):\n from ragas.metrics import (\n answer_relevance,\n context_precision,\n context_recall,\n faithfulness,\n )\n self.metrics = metrics or [\n faithfulness,\n answer_relevance,\n context_precision,\n context_recall,\n ]\n```\n\n2. **评测流程**:\n```python\nasync def evaluate_dataset(self, dataset: EvalDataset) -> SummaryResult:\n # 转换为 RAGAS 数据集格式\n data = {\n \"question\": [s.query for s in dataset.samples],\n \"contexts\": [s.context for s in dataset.samples],\n \"answer\": [s.response for s in dataset.samples],\n \"ground_truth\": [s.ground_truth for s in dataset.samples],\n }\n \n # 调用 RAGAS evaluate\n result = evaluate(data, metrics=self.metrics)\n```\n\n**自定义评测指标**:\n\n1. **继承 BaseEvaluator**:\n```python\nclass MyEvaluator(BaseEvaluator):\n async def evaluate_sample(self, sample: EvalSample) -> EvalResult:\n # 实现自定义评测逻辑\n scores = {\"my_metric\": 0.85}\n return EvalResult(sample=sample, scores=scores)\n```\n\n2. **自定义 RAGAS 指标**:\n```python\nfrom ragas import evaluate\nfrom ragas.metrics import Metric\n\nclass MyMetric(Metric):\n name = \"my_metric\"\n # 实现指标计算\n\nevaluator = RagasEvaluator(metrics=[MyMetric()])\n```\n\n3. **评测结果结构**:\n```python\nclass SummaryResult(BaseModel):\n dataset_name: str\n sample_count: int\n mean_scores: Dict[str, float] # 平均分数\n results: List[EvalResult] # 每个样本结果\n```"}diff --git a/openviking/integrations/langchain/client.py b/openviking/integrations/langchain/client.pyindex b9217c44c..49a4dab1f 100644--- a/openviking/integrations/langchain/client.py+++ b/openviking/integrations/langchain/client.py@@ -63,7 +63,6 @@ class OpenVikingConnection:account: str | None = Noneuser: str | None = Noneuser_id: str | None = None- agent_id: str | None = Nonepath: str | None = Nonetimeout: float = 60.0extra_headers: dict[str, str] | None = None@@ -213,7 +212,6 @@ def _create_client_from_connection(connection: OpenVikingConnection) -> Any:account=connection.account,user=connection.user,user_id=connection.user_id,- agent_id=connection.agent_id,timeout=connection.timeout,extra_headers=connection.extra_headers,)diff --git a/openviking/integrations/langchain/context.py b/openviking/integrations/langchain/context.pyindex 645b17f57..84bcaa18b 100644--- a/openviking/integrations/langchain/context.py+++ b/openviking/integrations/langchain/context.py@@ -58,12 +58,12 @@ class OpenVikingSessionContextAssembler:account: str | None = None,user: str | None = None,user_id: str | None = None,- agent_id: str | None = None,path: str | None = None,timeout: float = 60.0,extra_headers: dict[str, str] | None = None,auto_initialize: bool = True,target_uri: str | list[str] = "",+ peer_id: str | None = None,limit: int = 5,score_threshold: float | None = None,token_budget: int = 128_000,@@ -79,7 +79,6 @@ class OpenVikingSessionContextAssembler:account=account,user=user,user_id=user_id,- agent_id=agent_id,path=path,timeout=timeout,extra_headers=extra_headers,@@ -92,28 +91,39 @@ class OpenVikingSessionContextAssembler:account=account,user=user,user_id=user_id,- agent_id=agent_id,path=path,timeout=timeout,extra_headers=extra_headers,auto_initialize=auto_initialize,target_uri=target_uri,+ peer_id=peer_id,limit=limit,score_threshold=score_threshold,search_mode="search",)self.token_budget = token_budget+ self.peer_id = peer_id if peer_id is not None else getattr(self.retriever, "peer_id", None)self.include_session_context = include_session_contextself.include_active_messages = include_active_messagesself.include_recall = include_recallself.recall_header = recall_headerself._client_cache: Any = None- def assemble(self, *, session_id: str, query: str = "") -> OpenVikingAssembledContext:+ def assemble(+ self,+ *,+ session_id: str,+ query: str = "",+ peer_id: str | None = None,+ ) -> OpenVikingAssembledContext:client = self._get_client()self._ensure_session(client, session_id)session_context = self._get_session_context(client, session_id)- recall_documents = self._get_recall_documents(session_id, query)+ recall_documents = self._get_recall_documents(+ session_id,+ query,+ peer_id if peer_id is not None else self.peer_id,+ )block = self._format_context_block(session_context, recall_documents)return OpenVikingAssembledContext(block=block,@@ -148,11 +158,22 @@ class OpenVikingSessionContextAssembler:logger.debug("OpenViking session context assembly failed", exc_info=True)return {}- def _get_recall_documents(self, session_id: str, query: str) -> list[Any]:+ def _get_recall_documents(+ self,+ session_id: str,+ query: str,+ peer_id: str | None,+ ) -> list[Any]:if not self.include_recall or not query:return []try:- return list(_retriever_for_session(self.retriever, session_id).invoke(query))+ return list(+ _retriever_for_session(+ self.retriever,+ session_id,+ peer_id=peer_id,+ ).invoke(query)+ )except Exception:logger.debug("OpenViking recall retrieval failed", exc_info=True)return []@@ -207,12 +228,12 @@ def with_openviking_context(account: str | None = None,user: str | None = None,user_id: str | None = None,- agent_id: str | None = None,path: str | None = None,timeout: float = 60.0,extra_headers: dict[str, str] | None = None,auto_initialize: bool = True,session_id: str | None = None,+ peer_id: str | None = None,target_uri: str | list[str] = "",limit: int = 5,score_threshold: float | None = None,@@ -222,6 +243,7 @@ def with_openviking_context(history_messages_key: str | None = None,commit_policy: OpenVikingCommitPolicy | None = None,session_id_config_key: str = "session_id",+ peer_id_config_key: str = "peer_id",inject_context: bool = True,) -> RunnableWithMessageHistory:"""Wrap a LangChain runnable with OpenViking context and message history."""@@ -233,30 +255,35 @@ def with_openviking_context(account=account,user=user,user_id=user_id,- agent_id=agent_id,path=path,timeout=timeout,extra_headers=extra_headers,auto_initialize=auto_initialize,target_uri=target_uri,+ peer_id=peer_id,limit=limit,score_threshold=score_threshold,token_budget=token_budget,include_active_messages=False,include_recall=inject_context,)- pending_context_parts: dict[str, list[dict[str, Any]]] = {}+ pending_context_parts: dict[tuple[str, str], list[dict[str, Any]]] = {}+ active_peer_ids: dict[str, str | None] = {}def make_history(active_session_id: str) -> OpenVikingChatMessageHistory:return OpenVikingChatMessageHistory(session_id=active_session_id,+ peer_id=peer_id,+ peer_id_provider=lambda current_session_id: active_peer_ids.get(+ current_session_id,+ peer_id,+ ),client=client,url=url,api_key=api_key,account=account,user=user,user_id=user_id,- agent_id=agent_id,path=path,timeout=timeout,extra_headers=extra_headers,@@ -264,7 +291,10 @@ def with_openviking_context(token_budget=token_budget,commit_policy=commit_policy,context_parts_provider=lambda current_session_id: pending_context_parts.pop(- current_session_id,+ _pending_context_key(+ current_session_id,+ active_peer_ids.get(current_session_id, peer_id),+ ),[],),)@@ -294,27 +324,35 @@ def with_openviking_context(history_factory_config = Nonedef inject(input_value: Any, config: dict[str, Any] | None = None) -> Any:- if not inject_context:- return input_valueresolved_session_id = session_id or _session_id_from_config(config,key=session_id_config_key,)- pending_context_parts.pop(resolved_session_id, None)+ resolved_peer_id = _peer_id_from_config(+ config,+ key=peer_id_config_key,+ default=peer_id,+ )+ active_peer_ids[resolved_session_id] = resolved_peer_id+ if not inject_context:+ return input_value+ pending_key = _pending_context_key(resolved_session_id, resolved_peer_id)+ pending_context_parts.pop(pending_key, None)query = _latest_user_text_from_input(input_value, input_messages_key)- assembled = assembler.assemble(session_id=resolved_session_id, query=query)+ assembled = assembler.assemble(+ session_id=resolved_session_id,+ query=query,+ peer_id=resolved_peer_id,+ )if not assembled.block:return input_valueif assembled.context_parts:- pending_context_parts[resolved_session_id] = assembled.context_parts+ pending_context_parts[pending_key] = assembled.context_partsreturn _inject_system_context(input_value, assembled.block, input_messages_key)def clear_pending_on_error(_run: Any, config: dict[str, Any] | None = None) -> None:del config- if session_id is not None:- pending_context_parts.pop(session_id, None)- else:- pending_context_parts.clear()+ pending_context_parts.clear()bound = (RunnableLambda(inject) | runnable).with_listeners(on_error=clear_pending_on_error)return RunnableWithMessageHistory(@@ -332,6 +370,20 @@ def _session_id_from_config(config: dict[str, Any] | None, *, key: str) -> str:return _validate_session_id(configurable.get(key), key=key)+def _peer_id_from_config(+ config: dict[str, Any] | None,+ *,+ key: str,+ default: str | None,+) -> str | None:+ configurable = (config or {}).get("configurable") or {}+ value = configurable.get(key, default)+ if value is None:+ return None+ text = str(value).strip()+ return text or None++def _validate_session_id(value: Any, *, key: str) -> str:session_id = str(value or "").strip()if not session_id:@@ -343,17 +395,27 @@ def _validate_session_id(value: Any, *, key: str) -> str:return session_id-def _retriever_for_session(retriever: Any, session_id: str) -> Any:+def _retriever_for_session(+ retriever: Any,+ session_id: str,+ *,+ peer_id: str | None = None,+) -> Any:if hasattr(retriever, "model_copy"):- return retriever.model_copy(- update={- "session_id": session_id,- "search_mode": "search",- }- )+ update = {+ "session_id": session_id,+ "search_mode": "search",+ }+ if peer_id is not None:+ update["peer_id"] = peer_id+ return retriever.model_copy(update=update)return retriever+def _pending_context_key(session_id: str, peer_id: str | None) -> tuple[str, str]:+ return (session_id, peer_id or "")++def _latest_user_text_from_input(input_value: Any, input_messages_key: str | None) -> str:messages = _input_messages(input_value, input_messages_key)if messages:diff --git a/openviking/integrations/langchain/history.py b/openviking/integrations/langchain/history.pyindex 021da6219..ba5996231 100644--- a/openviking/integrations/langchain/history.py+++ b/openviking/integrations/langchain/history.py@@ -47,7 +47,6 @@ class OpenVikingChatMessageHistory(BaseChatMessageHistory):account: str | None = None,user: str | None = None,user_id: str | None = None,- agent_id: str | None = None,path: str | None = None,timeout: float = 60.0,extra_headers: dict[str, str] | None = None,@@ -56,8 +55,12 @@ class OpenVikingChatMessageHistory(BaseChatMessageHistory):persist_system_messages: bool = False,commit_policy: OpenVikingCommitPolicy | None = None,context_parts_provider: Callable[[str], list[dict[str, Any]]] | None = None,+ peer_id: str | None = None,+ peer_id_provider: Callable[[str], str | None] | None = None,):self.session_id = session_id+ self.peer_id = peer_id+ self.peer_id_provider = peer_id_providerself.token_budget = token_budget# Retained for constructor compatibility. System messages are runtime# policy, not conversation memory, so they are never persisted.@@ -71,7 +74,6 @@ class OpenVikingChatMessageHistory(BaseChatMessageHistory):account=account,user=user,user_id=user_id,- agent_id=agent_id,path=path,timeout=timeout,extra_headers=extra_headers,@@ -104,6 +106,7 @@ class OpenVikingChatMessageHistory(BaseChatMessageHistory):else [])batch = []+ effective_peer_id = self._effective_peer_id()for message in messages:for payload in langchain_message_to_openviking(message,@@ -112,6 +115,8 @@ class OpenVikingChatMessageHistory(BaseChatMessageHistory):if pending_context_parts and payload["role"] == "assistant":payload["parts"].extend(pending_context_parts)pending_context_parts = []+ if effective_peer_id is not None:+ payload["peer_id"] = effective_peer_idbatch.append(payload)if batch:@@ -140,6 +145,16 @@ class OpenVikingChatMessageHistory(BaseChatMessageHistory):logger.debug("OpenViking chat history session ensure failed", exc_info=True)pass+ def _effective_peer_id(self) -> str | None:+ if self.peer_id_provider is None:+ value = self.peer_id+ else:+ value = self.peer_id_provider(self.session_id)+ if value is None:+ return None+ text = str(value).strip()+ return text or None+def langchain_message_to_openviking(message: BaseMessage,diff --git a/openviking/integrations/langchain/middleware.py b/openviking/integrations/langchain/middleware.pyindex 5d07c3133..54c56d828 100644--- a/openviking/integrations/langchain/middleware.py+++ b/openviking/integrations/langchain/middleware.py@@ -66,13 +66,14 @@ class OpenVikingContextMiddleware(AgentMiddleware):account: str | None = None,user: str | None = None,user_id: str | None = None,- agent_id: str | None = None,path: str | None = None,target_uri: str | list[str] = "",limit: int = 5,+ peer_id: str | None = None,score_threshold: float | None = None,token_budget: int = 128_000,session_id_resolver: Callable[[dict[str, Any], Any], str] | None = None,+ peer_id_resolver: Callable[[dict[str, Any], Any], str | None] | None = None,capture_on_after_agent: bool = True,commit_on_after_agent: bool = False,commit_policy: OpenVikingCommitPolicy | None = None,@@ -88,7 +89,6 @@ class OpenVikingContextMiddleware(AgentMiddleware):account=account,user=user,user_id=user_id,- agent_id=agent_id,path=path,)self.retriever = retriever or OpenVikingRetriever(@@ -98,9 +98,9 @@ class OpenVikingContextMiddleware(AgentMiddleware):account=account,user=user,user_id=user_id,- agent_id=agent_id,path=path,target_uri=target_uri,+ peer_id=peer_id,limit=limit,score_threshold=score_threshold,search_mode="search",@@ -113,9 +113,9 @@ class OpenVikingContextMiddleware(AgentMiddleware):account=account,user=user,user_id=user_id,- agent_id=agent_id,path=path,target_uri=target_uri,+ peer_id=peer_id,limit=limit,score_threshold=score_threshold,token_budget=token_budget,@@ -125,13 +125,15 @@ class OpenVikingContextMiddleware(AgentMiddleware):recall_header=recall_header,)self.session_id_resolver = session_id_resolver+ self.peer_id = peer_id if peer_id is not None else getattr(self.retriever, "peer_id", None)+ self.peer_id_resolver = peer_id_resolverself.capture_on_after_agent = capture_on_after_agentself.commit_policy = commit_policyif commit_on_after_agent and self.commit_policy is None:self.commit_policy = OpenVikingCommitPolicy(mode="always")self.recall_header = recall_header- self._captured_signatures: dict[str, tuple[str, ...]] = {}- self._pending_context_parts: dict[str, list[dict[str, Any]]] = {}+ self._captured_signatures: dict[tuple[str, str], tuple[str, ...]] = {}+ self._pending_context_parts: dict[tuple[str, str], list[dict[str, Any]]] = {}def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], Any]) -> Any:query = get_latest_user_text(request.messages)@@ -141,13 +143,22 @@ class OpenVikingContextMiddleware(AgentMiddleware):getattr(request, "state", {}) or {},getattr(request, "runtime", None),)- self._pending_context_parts.pop(session_id, None)- assembled = self.assembler.assemble(session_id=session_id, query=query)+ peer_id = self._resolve_peer_id(+ getattr(request, "state", {}) or {},+ getattr(request, "runtime", None),+ )+ pending_key = _capture_key(session_id, peer_id)+ self._pending_context_parts.pop(pending_key, None)+ assembled = self.assembler.assemble(+ session_id=session_id,+ query=query,+ peer_id=peer_id,+ )context_block = assembled.blockif not context_block:return handler(request)if assembled.context_parts:- self._pending_context_parts[session_id] = assembled.context_parts+ self._pending_context_parts[pending_key] = assembled.context_partssystem_message = request.system_messageif system_message is None:@@ -158,7 +169,7 @@ class OpenVikingContextMiddleware(AgentMiddleware):try:return handler(request.override(system_message=updated_system))except Exception:- self._pending_context_parts.pop(session_id, None)+ self._pending_context_parts.pop(pending_key, None)raisedef after_agent(self, state: dict[str, Any], runtime: Any) -> dict[str, Any] | None:@@ -168,11 +179,13 @@ class OpenVikingContextMiddleware(AgentMiddleware):if not messages:return Nonesession_id = self._resolve_session_id(state, runtime)- previous_signatures = self._captured_signatures.get(session_id, ())+ peer_id = self._resolve_peer_id(state, runtime)+ capture_key = _capture_key(session_id, peer_id)+ previous_signatures = self._captured_signatures.get(capture_key, ())current_signatures = tuple(_message_signature(message) for message in messages)if current_signatures == previous_signatures:- self._pending_context_parts.pop(session_id, None)+ self._pending_context_parts.pop(capture_key, None)return Nonestart = 0if (@@ -184,7 +197,7 @@ class OpenVikingContextMiddleware(AgentMiddleware):client = ensure_client(self._connection)added = 0- pending_context_parts = list(self._pending_context_parts.pop(session_id, []))+ pending_context_parts = list(self._pending_context_parts.pop(capture_key, []))for message in messages[start:]:if OPENVIKING_CONTEXT_MARKER in _message_content(message):continue@@ -199,9 +212,10 @@ class OpenVikingContextMiddleware(AgentMiddleware):session_id=session_id,role=payload["role"],parts=payload["parts"],+ peer_id=peer_id,)added += 1- self._captured_signatures[session_id] = current_signatures+ self._captured_signatures[capture_key] = current_signaturesif added:apply_commit_policy(client, session_id, self.commit_policy)return None@@ -225,6 +239,24 @@ class OpenVikingContextMiddleware(AgentMiddleware):return resolvedraise ValueError(_SESSION_ID_ERROR)+ def _resolve_peer_id(self, state: dict[str, Any], runtime: Any) -> str | None:+ if self.peer_id_resolver:+ return _normalize_peer_id(self.peer_id_resolver(state, runtime))+ candidates = [+ state.get("peer_id"),+ state.get("peerId"),+ _nested_get(getattr(runtime, "context", None), "peer_id"),+ _nested_get(getattr(runtime, "context", None), "peerId"),+ _nested_get(getattr(runtime, "config", None), "configurable", "peer_id"),+ _nested_get(getattr(runtime, "config", None), "configurable", "peerId"),+ self.peer_id,+ ]+ for candidate in candidates:+ resolved = _normalize_peer_id(candidate)+ if resolved:+ return resolved+ return None+def _ensure_session(self, client: Any, session_id: str) -> None:try:call_openviking(client, "create_session", session_id=session_id)@@ -252,6 +284,17 @@ def _normalize_session_id(value: Any) -> str | None:return text or None+def _normalize_peer_id(value: Any) -> str | None:+ if value is None:+ return None+ text = str(value).strip()+ return text or None+++def _capture_key(session_id: str, peer_id: str | None) -> tuple[str, str]:+ return (session_id, peer_id or "")++def _message_role(message: Any) -> str:if isinstance(message, HumanMessage):return "user"diff --git a/openviking/integrations/langchain/retrievers.py b/openviking/integrations/langchain/retrievers.pyindex 21aeb16d1..05e4483a9 100644--- a/openviking/integrations/langchain/retrievers.py+++ b/openviking/integrations/langchain/retrievers.py@@ -38,7 +38,6 @@ class OpenVikingRetriever(BaseRetriever):account: str | None = Noneuser: str | None = Noneuser_id: str | None = None- agent_id: str | None = Nonepath: str | None = Nonetimeout: float = 60.0extra_headers: dict[str, str] | None = None@@ -47,6 +46,7 @@ class OpenVikingRetriever(BaseRetriever):target_uri: str | list[str] = ""search_mode: Literal["find", "search"] = "find"session_id: str | None = None+ peer_id: str | None = Nonelimit: int = 10score_threshold: float | None = Nonefilter: dict[str, Any] | None = None@@ -68,7 +68,6 @@ class OpenVikingRetriever(BaseRetriever):account=self.account,user=self.user,user_id=self.user_id,- agent_id=self.agent_id,path=self.path,timeout=self.timeout,extra_headers=self.extra_headers,@@ -86,6 +85,7 @@ class OpenVikingRetriever(BaseRetriever):query=query,target_uri=self.target_uri,session_id=self.session_id,+ peer_id=self.peer_id,limit=self.limit,score_threshold=self.score_threshold,filter=self.filter,diff --git a/openviking/integrations/langchain/store.py b/openviking/integrations/langchain/store.pyindex 6fbe3ab3a..28afccf06 100644--- a/openviking/integrations/langchain/store.py+++ b/openviking/integrations/langchain/store.py@@ -60,7 +60,6 @@ class OpenVikingStore(BaseStore):account: str | None = None,user: str | None = None,user_id: str | None = None,- agent_id: str | None = None,path: str | None = None,root_uri: str = "viking://user/memories/langgraph_store",index: bool | list[str] | None = None,@@ -68,6 +67,7 @@ class OpenVikingStore(BaseStore):timeout: float | None = None,search_fetch_limit: int = 50,auto_initialize: bool = True,+ peer_id: str | None = None,):if _LANGGRAPH_IMPORT_ERROR is not None:raise _LANGGRAPH_IMPORT_ERROR@@ -79,7 +79,6 @@ class OpenVikingStore(BaseStore):account=account,user=user,user_id=user_id,- agent_id=agent_id,path=path,auto_initialize=auto_initialize,)@@ -88,6 +87,7 @@ class OpenVikingStore(BaseStore):self.wait = waitself.timeout = timeoutself.search_fetch_limit = search_fetch_limit+ self.peer_id = peer_idself._client_cache: Any = Nonedef batch(self, ops: Iterable[Any]) -> list[Any]:@@ -231,6 +231,7 @@ class OpenVikingStore(BaseStore):"find",query=query,target_uri=self._index_prefix_uri(namespace_prefix),+ peer_id=self.peer_id,limit=max(limit + offset, self.search_fetch_limit),)items: list[Any] = []@@ -463,7 +464,7 @@ def _parse_canonicalized_record_uri(def _identity_relative_root_tail(classification: UriClassification) -> tuple[str, ...] | None:- if classification.scope not in {"user", "agent"}:+ if classification.scope != "user":return Noneif classification.content_index != 1:return Nonediff --git a/openviking/integrations/langchain/testing.py b/openviking/integrations/langchain/testing.pyindex 1113177b4..6448b287b 100644--- a/openviking/integrations/langchain/testing.py+++ b/openviking/integrations/langchain/testing.py@@ -11,6 +11,7 @@ from collections import defaultdictfrom datetime import datetime, timezonefrom typing import Any+from openviking.core.peer_id import normalize_peer_idfrom openviking.utils.token_estimation import estimate_text_tokens@@ -43,14 +44,18 @@ class InMemoryOpenVikingClient:limit: int = 10,score_threshold: float | None = None,filter: dict[str, Any] | None = None,+ peer_id: str | None = None,**_: Any,) -> dict[str, Any]:+ normalized_peer_id = normalize_peer_id(peer_id)self.find_calls.append({"query": query,"target_uri": target_uri,"limit": limit,"score_threshold": score_threshold,+ "filter": filter,+ "peer_id": normalized_peer_id,})return self._search(query, target_uri, limit, score_threshold)@@ -63,8 +68,10 @@ class InMemoryOpenVikingClient:limit: int = 10,score_threshold: float | None = None,filter: dict[str, Any] | None = None,+ peer_id: str | None = None,**_: Any,) -> dict[str, Any]:+ normalized_peer_id = normalize_peer_id(peer_id)self.search_calls.append({"query": query,@@ -72,6 +79,8 @@ class InMemoryOpenVikingClient:"session_id": session_id,"limit": limit,"score_threshold": score_threshold,+ "filter": filter,+ "peer_id": normalized_peer_id,})session_text = " ".join(@@ -229,18 +238,19 @@ class InMemoryOpenVikingClient:content: str | None = None,parts: list[dict] | None = None,created_at: str | None = None,- role_id: str | None = None,+ peer_id: str | None = None,**_: Any,) -> dict[str, Any]:message_parts = list(parts or [{"type": "text", "text": content or ""}])+ normalized_peer_id = normalize_peer_id(peer_id)message = {"id": f"msg_{uuid.uuid4().hex}","role": role,"parts": message_parts,"created_at": created_at or datetime.now(timezone.utc).isoformat(),}- if role_id is not None:- message["role_id"] = role_id+ if normalized_peer_id is not None:+ message["peer_id"] = normalized_peer_idself.sessions.setdefault(session_id, []).append(message)self.pending_tokens[session_id] += max(1, estimate_text_tokens(_message_text(message)))return {@@ -263,7 +273,7 @@ class InMemoryOpenVikingClient:content=message.get("content"),parts=message.get("parts"),created_at=message.get("created_at"),- role_id=message.get("role_id"),+ peer_id=message.get("peer_id"),)added += 1return {@@ -368,7 +378,7 @@ class InMemoryOpenVikingClient:def add_skill(self, data: Any, **_: Any) -> dict[str, Any]:name = data.get("name", "skill") if isinstance(data, dict) else "skill"- uri = f"viking://agent/skills/{name}.md"+ uri = f"viking://user/skills/{name}.md"self.records[uri] = str(data)return {"status": "completed", "uri": uri, "name": name}diff --git a/openviking/integrations/langchain/tools.py b/openviking/integrations/langchain/tools.pyindex 48687f4bb..743087194 100644--- a/openviking/integrations/langchain/tools.py+++ b/openviking/integrations/langchain/tools.py@@ -49,12 +49,12 @@ def create_openviking_tools(account: str | None = None,user: str | None = None,user_id: str | None = None,- agent_id: str | None = None,path: str | None = None,timeout: float = 60.0,extra_headers: dict[str, str] | None = None,auto_initialize: bool = True,profile: str = "agent",+ peer_id: str | None = None,tool_names: Iterable[str] | None = None,allow_forget: bool = False,) -> list[StructuredTool]:@@ -78,7 +78,6 @@ def create_openviking_tools(account=account,user=user,user_id=user_id,- agent_id=agent_id,path=path,timeout=timeout,extra_headers=extra_headers,@@ -106,6 +105,7 @@ def create_openviking_tools("find",query=query,target_uri=target_uri,+ peer_id=peer_id,limit=limit,score_threshold=min_score,)@@ -135,6 +135,7 @@ def create_openviking_tools(query=query,target_uri=target_uri,session_id=session_id,+ peer_id=peer_id,limit=limit,score_threshold=min_score,)@@ -285,6 +286,7 @@ def create_openviking_tools(role=message["role"],content=message.get("content"),parts=message.get("parts"),+ peer_id=peer_id,)result: dict[str, Any] = {"session_id": session_id,diff --git a/openviking/message/message.py b/openviking/message/message.pyindex 638facb6f..508096014 100644--- a/openviking/message/message.py+++ b/openviking/message/message.py@@ -10,6 +10,7 @@ from dataclasses import dataclassfrom datetime import datetime, timezonefrom typing import List, Literal, Optional+from openviking.core.peer_id import normalize_peer_idfrom openviking.message.part import ContextPart, Part, TextPart, ToolPartfrom openviking.utils.token_estimation import estimate_text_tokens@@ -21,7 +22,7 @@ class Message:id: strrole: Literal["user", "assistant"]parts: List[Part]- role_id: Optional[str] = None+ peer_id: Optional[str] = Nonecreated_at: str = None@property@@ -72,13 +73,15 @@ class Message:.isoformat(timespec="milliseconds").replace("+00:00", "Z"))- return {+ data = {"id": self.id,"role": self.role,- "role_id": self.role_id,"parts": [self._part_to_dict(p) for p in self.parts],"created_at": created_at_val,}+ if self.peer_id is not None:+ data["peer_id"] = self.peer_id+ return datadef _part_to_dict(self, part: Part) -> dict:if isinstance(part, TextPart):@@ -199,81 +202,19 @@ class Message:tool_output_group_budget_chars=p.get("tool_output_group_budget_chars"),))+ try:+ peer_id = normalize_peer_id(data.get("peer_id"))+ except ValueError:+ peer_id = data.get("peer_id")+return cls(id=data["id"],role=data["role"],parts=parts,- role_id=data.get("role_id"),+ peer_id=peer_id,created_at=data.get("created_at"),)- @classmethod- def create_user(- cls,- content: str,- msg_id: str = None,- role_id: Optional[str] = None,- ) -> "Message":- """Create user message."""- from uuid import uuid4-- return cls(- id=msg_id or f"msg_{uuid4().hex}",- role="user",- parts=[TextPart(text=content)],- role_id=role_id,- created_at=datetime.now(timezone.utc).isoformat(),- )-- @classmethod- def create_assistant(- cls,- content: str = "",- context_refs: List[dict] = None,- tool_calls: List[dict] = None,- msg_id: str = None,- role_id: Optional[str] = None,- ) -> "Message":- """Create assistant message."""- from uuid import uuid4-- parts: List[Part] = []- if content:- parts.append(TextPart(text=content))-- for ref in context_refs or []:- parts.append(- ContextPart(- uri=ref.get("uri", ""),- context_type=ref.get("context_type", "memory"),- abstract=ref.get("abstract", ""),- )- )-- for tc in tool_calls or []:- parts.append(- ToolPart(- tool_id=tc.get("id", ""),- tool_name=tc.get("name", ""),- tool_uri=tc.get("uri", ""),- skill_uri=tc.get("skill_uri", ""),- tool_input=tc.get("input"),- tool_status=tc.get("status", "pending"),- )- )-- return cls(- id=msg_id or f"msg_{uuid4().hex}",- role="assistant",- parts=parts,- role_id=role_id,- created_at=datetime.now(timezone.utc).isoformat(),- )-- def get_context_parts(self) -> List[ContextPart]:- """Get all ContextParts."""- return [p for p in self.parts if isinstance(p, ContextPart)]-def get_tool_parts(self) -> List[ToolPart]:"""Get all ToolParts."""return [p for p in self.parts if isinstance(p, ToolPart)]diff --git a/openviking/message/part.py b/openviking/message/part.pyindex f947436be..603171587 100644--- a/openviking/message/part.py+++ b/openviking/message/part.py@@ -41,7 +41,7 @@ class ToolPart:tool_id: str = ""tool_name: str = ""tool_uri: str = "" # viking://session/{user_space_name}/{session_id}/tools/{tool_id}- skill_uri: str = "" # viking://agent/{agent_id}/skills/{skill_name} or .../user/{user_id}/skills/{skill_name}+ skill_uri: str = "" # viking://user/{user_id}/skills/{skill_name}tool_input: Optional[dict] = Nonetool_output: str = ""tool_status: str = "pending" # pending | running | completed | errordiff --git a/openviking/metrics/datasources/http.py b/openviking/metrics/datasources/http.pyindex 1c5f9bbd7..160dbc0e2 100644--- a/openviking/metrics/datasources/http.py+++ b/openviking/metrics/datasources/http.py@@ -34,7 +34,6 @@ class HttpRequestLifecycleDataSource(EventMetricDataSource):account_id: str | None = None,request_id: str | None = None,user_id: str | None = None,- agent_id: str | None = None,url_path: str | None = None,) -> None:"""@@ -54,8 +53,6 @@ class HttpRequestLifecycleDataSource(EventMetricDataSource):payload["request_id"] = str(request_id)if user_id is not None:payload["user_id"] = str(user_id)- if agent_id is not None:- payload["agent_id"] = str(agent_id)if url_path is not None:payload["url_path"] = str(url_path)EventMetricDataSource._emit("http.request", payload)diff --git a/openviking/observability/events.py b/openviking/observability/events.pyindex 2f84e7675..690d93eb1 100644--- a/openviking/observability/events.py+++ b/openviking/observability/events.py@@ -30,7 +30,6 @@ class ObservabilityEvent:request_id: str | None = Noneaccount_id: str | None = Noneuser_id: str | None = None- agent_id: str | None = Noneclass ObservabilitySubscriber(Protocol):@@ -119,7 +118,6 @@ def _metadata_from_context(payload: dict[str, Any]) -> dict[str, str | None]:"request_id": _first(payload.get("request_id"), getattr(root, "request_id", None)),"account_id": _first(payload.get("account_id"), getattr(root, "account_id", None)),"user_id": _first(payload.get("user_id"), getattr(root, "user_id", None)),- "agent_id": _first(payload.get("agent_id"), getattr(root, "agent_id", None)),}@@ -133,7 +131,6 @@ def build_event(event_name: str, payload: dict[str, Any] | None = None) -> Obserrequest_id=metadata["request_id"],account_id=metadata["account_id"],user_id=metadata["user_id"],- agent_id=metadata["agent_id"],)@@ -157,7 +154,7 @@ def make_payload_subscriber(def _subscriber(event: ObservabilityEvent) -> None:payload = dict(event.payload)- for key in ("request_id", "account_id", "user_id", "agent_id"):+ for key in ("request_id", "account_id", "user_id"):if payload.get(key) is None:value = getattr(event, key)if value is not None:diff --git a/openviking/observability/http_observability_middleware.py b/openviking/observability/http_observability_middleware.pyindex f58582100..2f2507b47 100644--- a/openviking/observability/http_observability_middleware.py+++ b/openviking/observability/http_observability_middleware.py@@ -685,7 +685,6 @@ def apply_http_metrics_finalize(account_id=final_account_id,request_id=root_attrs.request_id,user_id=root_attrs.user_id,- agent_id=root_attrs.agent_id,url_path=root_attrs.url_path,)diff --git a/openviking/observability/usage_audit/README.md b/openviking/observability/usage_audit/README.mdindex bbd6d025c..371e67478 100644--- a/openviking/observability/usage_audit/README.md+++ b/openviking/observability/usage_audit/README.md@@ -154,7 +154,6 @@ vector filter,也不从历史写入事件累计当前库存。- `request_id`- `account_id`- `user_id`-- `agent_id`- `method`- `route`- `api_type`@@ -232,15 +231,6 @@ GET /api/v1/console/dashboard/summary"find": 10,"search": 4,"total": 14- },- "agent_overview": {- "total": 2,- "items": [- {- "agent_id": "agent-1",- "last_seen_at": "2026-05-12T10:00:00+08:00"- }- ]}}}@@ -343,7 +333,6 @@ curl -X POST "http://127.0.0.1:1933/api/v1/search/find" \-H "Authorization: Bearer $OPENVIKING_API_KEY" \-H "X-OpenViking-Account: default" \-H "X-OpenViking-User: default" \- -H "X-OpenViking-Agent: default" \-H "Content-Type: application/json" \-d '{"query":"hello","limit":3}'```@@ -355,7 +344,6 @@ curl "http://127.0.0.1:1933/api/v1/console/dashboard/summary" \-H "Authorization: Bearer $OPENVIKING_API_KEY" \-H "X-OpenViking-Account: default" \-H "X-OpenViking-User: default" \- -H "X-OpenViking-Agent: default"```如果使用 Console server,则访问 `/console/api/v1/ov/console/*` 代理路径。diff --git a/openviking/observability/usage_audit/api_service.py b/openviking/observability/usage_audit/api_service.pyindex efdda5233..05db1863d 100644--- a/openviking/observability/usage_audit/api_service.py+++ b/openviking/observability/usage_audit/api_service.py@@ -55,17 +55,10 @@ class UsageAuditQueryService:today_retrievals = await self._store.get_today_retrievals(account_id=ctx.account_id, user_date=today, tz=tz)- agent_overview = await self._store.get_agent_overview(- account_id=ctx.account_id,- user_date=today,- tz=tz,- limit=5,- )return {"context_counts": context_counts,"today_tokens": today_tokens,"today_retrievals": today_retrievals,- "agent_overview": agent_overview,}async def token_series(diff --git a/openviking/observability/usage_audit/inventory.py b/openviking/observability/usage_audit/inventory.pyindex cf996ed9d..b32dbb26c 100644--- a/openviking/observability/usage_audit/inventory.py+++ b/openviking/observability/usage_audit/inventory.py@@ -9,7 +9,7 @@ import loggingimport timefrom typing import Any-from openviking.core.namespace import canonical_agent_root, canonical_user_root+from openviking.core.namespace import canonical_user_rootfrom openviking.pyagfs.exceptions import AGFSNotFoundErrorfrom openviking.server.identity import RequestContextfrom openviking_cli.exceptions import NotFoundError@@ -23,12 +23,12 @@ class ContextInventoryProvider:def __init__(self, service: Any, *, ttl_seconds: float = 10.0) -> None:self._service = serviceself._ttl_seconds = max(float(ttl_seconds), 0.0)- self._cache: dict[tuple[str, str, str], tuple[float, dict[str, int]]] = {}+ self._cache: dict[tuple[str, str], tuple[float, dict[str, int]]] = {}self._lock = asyncio.Lock()async def get_counts(self, ctx: RequestContext) -> dict[str, int]:"""Return current context counts for the caller's tenant scope."""- key = (ctx.account_id, ctx.user.user_id, ctx.user.agent_id)+ key = (ctx.account_id, ctx.user.user_id)now = time.monotonic()cached = self._cache.get(key)if cached and now - cached[0] < self._ttl_seconds:@@ -44,15 +44,12 @@ class ContextInventoryProvider:async def _read_counts(self, ctx: RequestContext) -> dict[str, int]:user_root = canonical_user_root(ctx)- agent_root = canonical_agent_root(ctx)- files, skills, user_memories, agent_memories = await asyncio.gather(+ files, skills, memories = await asyncio.gather(self._stat_count("viking://resources", ctx=ctx),- self._stat_count(f"{agent_root}/skills", ctx=ctx),+ self._stat_count(f"{user_root}/skills", ctx=ctx),self._stat_count(f"{user_root}/memories", ctx=ctx),- self._stat_count(f"{agent_root}/memories", ctx=ctx),)- memories = user_memories + agent_memoriesreturn {"files": files,"skills": skills,diff --git a/openviking/observability/usage_audit/projection.py b/openviking/observability/usage_audit/projection.pyindex cc71f84f2..53bda6abb 100644--- a/openviking/observability/usage_audit/projection.py+++ b/openviking/observability/usage_audit/projection.py@@ -36,7 +36,6 @@ class UsageAuditProjection:token_rows: dict[tuple, int] = field(default_factory=dict)retrieval_rows: dict[tuple, tuple[int, int]] = field(default_factory=dict)context_rows: dict[tuple, int] = field(default_factory=dict)- agent_rows: dict[tuple, tuple[int, str]] = field(default_factory=dict)audit_rows: list[tuple] = field(default_factory=list)touched_audit_accounts: set[str] = field(default_factory=set)@@ -76,14 +75,12 @@ def project_events(token_rows: defaultdict[tuple, int] = defaultdict(int)retrieval_rows: defaultdict[tuple, tuple[int, int]] = defaultdict(lambda: (0, 0))context_rows: defaultdict[tuple, int] = defaultdict(int)- agent_rows: dict[tuple, tuple[int, str]] = {}audit_rows: list[tuple] = []touched_audit_accounts: set[str] = set()for event in events:account_id = normalize_identity(event.account_id, unknown=True)user_id = normalize_identity(event.user_id)- agent_id = normalize_identity(event.agent_id)utc_dt = _utc_dt(event)event_date = utc_dt.date().isoformat()event_hour = int(utc_dt.hour)@@ -95,7 +92,6 @@ def project_events(token_rows,account_id=account_id,user_id=user_id,- agent_id=agent_id,event_date=event_date,event_hour=event_hour,source="vlm",@@ -111,7 +107,6 @@ def project_events(token_rows,account_id=account_id,user_id=user_id,- agent_id=agent_id,event_date=event_date,event_hour=event_hour,source="embedding",@@ -127,7 +122,6 @@ def project_events(token_rows,account_id=account_id,user_id=user_id,- agent_id=agent_id,event_date=event_date,event_hour=event_hour,source="rerank",@@ -148,14 +142,12 @@ def project_events(context_rows=context_rows,audit_rows=audit_rows,touched_audit_accounts=touched_audit_accounts,- agent_rows=agent_rows,)return UsageAuditProjection(token_rows=dict(token_rows),retrieval_rows=dict(retrieval_rows),context_rows=dict(context_rows),- agent_rows=agent_rows,audit_rows=audit_rows,touched_audit_accounts=touched_audit_accounts,)@@ -173,7 +165,6 @@ def _add_token_rows(*,account_id: str,user_id: str,- agent_id: str,event_date: str,event_hour: int,source: str,@@ -190,7 +181,6 @@ def _add_token_rows(key = (account_id,user_id,- agent_id,event_date,event_hour,source,@@ -203,7 +193,6 @@ def _add_token_rows(key = (account_id,user_id,- agent_id,event_date,event_hour,source,@@ -224,7 +213,6 @@ def _project_http_request(context_rows: defaultdict[tuple, int],audit_rows: list[tuple],touched_audit_accounts: set[str],- agent_rows: dict[tuple, tuple[int, str]],) -> None:payload = event.payloadroute = str(payload.get("route") or "")@@ -240,9 +228,7 @@ def _project_http_request(unknown=True,)audit_user = normalize_identity(payload.get("user_id") or event.user_id) or None- audit_agent = normalize_identity(payload.get("agent_id") or event.agent_id) or Nonerow_user = audit_user or ""- row_agent = audit_agent or ""status = "success" if 200 <= status_code < 400 else "error"retrieval_operation = retrieval_operation_for_http(method, route)@@ -250,7 +236,6 @@ def _project_http_request(key = (audit_account,row_user,- row_agent,event_date,hour,retrieval_operation,@@ -261,7 +246,7 @@ def _project_http_request(context_operation = context_write_operation_for_http(method, route, status_code)if context_operation:- key = (audit_account, row_user, row_agent, event_date, hour, context_operation)+ key = (audit_account, row_user, event_date, hour, context_operation)context_rows[key] += 1audit_rows.append(@@ -269,7 +254,6 @@ def _project_http_request(payload.get("request_id") or event.request_id,audit_account,audit_user,- audit_agent,str(payload.get("method") or ""),route,str(payload.get("api_type") or derive_api_type(route)),@@ -279,13 +263,6 @@ def _project_http_request())touched_audit_accounts.add(audit_account)- if audit_agent:- agent_key = (audit_account, audit_agent, event_date)- prev_count, prev_seen = agent_rows.get(agent_key, (0, ""))- agent_rows[agent_key] = (- prev_count + 1,- max(prev_seen, created_at) if prev_seen else created_at,- )def should_skip_audit_route(route: str) -> bool:diff --git a/openviking/observability/usage_audit/schema.py b/openviking/observability/usage_audit/schema.pyindex c736a1beb..1a5bafefe 100644--- a/openviking/observability/usage_audit/schema.py+++ b/openviking/observability/usage_audit/schema.py@@ -5,14 +5,13 @@All time-keyed columns (`date_utc`, `hour_utc`, `created_at`) are persisted inUTC. The viewer's timezone is applied at read time so a single store canserve any region. Token and retrieval rollups are hour-grained so cross-tz-"today" queries can slice at user-local day boundaries; agent activity stays-daily, filtered by `last_seen_at` at read time.+"today" queries can slice at user-local day boundaries."""# Bump when the table layout changes incompatibly. Stored on the `_schema_meta`# row so `SQLiteUsageAuditStore.initialize` can reset the local SQLite store# when an older snapshot is detected.-SCHEMA_VERSION = 3+SCHEMA_VERSION = 4SQLITE_SCHEMA = """CREATE TABLE IF NOT EXISTS _schema_meta (@@ -23,7 +22,6 @@ CREATE TABLE IF NOT EXISTS _schema_meta (CREATE TABLE IF NOT EXISTS usage_token_hourly (account_id TEXT NOT NULL,user_id TEXT NOT NULL,- agent_id TEXT NOT NULL,date_utc TEXT NOT NULL,hour_utc INTEGER NOT NULL,source TEXT NOT NULL,@@ -33,7 +31,7 @@ CREATE TABLE IF NOT EXISTS usage_token_hourly (token_count INTEGER NOT NULL DEFAULT 0,updated_at TEXT NOT NULL,PRIMARY KEY (- account_id, user_id, agent_id, date_utc, hour_utc,+ account_id, user_id, date_utc, hour_utc,source, token_type, provider, model_name));@@ -43,7 +41,6 @@ CREATE INDEX IF NOT EXISTS idx_usage_token_account_dateCREATE TABLE IF NOT EXISTS usage_retrieval_hourly (account_id TEXT NOT NULL,user_id TEXT NOT NULL,- agent_id TEXT NOT NULL,date_utc TEXT NOT NULL,hour_utc INTEGER NOT NULL,operation TEXT NOT NULL,@@ -52,7 +49,7 @@ CREATE TABLE IF NOT EXISTS usage_retrieval_hourly (result_count INTEGER NOT NULL DEFAULT 0,updated_at TEXT NOT NULL,PRIMARY KEY (- account_id, user_id, agent_id, date_utc, hour_utc, operation, status+ account_id, user_id, date_utc, hour_utc, operation, status));CREATE INDEX IF NOT EXISTS idx_usage_retrieval_account_date@@ -61,37 +58,23 @@ CREATE INDEX IF NOT EXISTS idx_usage_retrieval_account_dateCREATE TABLE IF NOT EXISTS usage_context_write_bucket (account_id TEXT NOT NULL,user_id TEXT NOT NULL,- agent_id TEXT NOT NULL,date_utc TEXT NOT NULL,hour_utc INTEGER NOT NULL,operation TEXT NOT NULL,count INTEGER NOT NULL DEFAULT 0,updated_at TEXT NOT NULL,PRIMARY KEY (- account_id, user_id, agent_id, date_utc, hour_utc, operation+ account_id, user_id, date_utc, hour_utc, operation));CREATE INDEX IF NOT EXISTS idx_usage_context_write_account_dateON usage_context_write_bucket(account_id, date_utc, hour_utc);-CREATE TABLE IF NOT EXISTS usage_agent_activity_daily (- account_id TEXT NOT NULL,- agent_id TEXT NOT NULL,- date_utc TEXT NOT NULL,- request_count INTEGER NOT NULL DEFAULT 0,- last_seen_at TEXT NOT NULL,- updated_at TEXT NOT NULL,- PRIMARY KEY (account_id, agent_id, date_utc)-);-CREATE INDEX IF NOT EXISTS idx_usage_agent_activity_account_date- ON usage_agent_activity_daily(account_id, date_utc, last_seen_at);-CREATE TABLE IF NOT EXISTS request_audit (id INTEGER PRIMARY KEY AUTOINCREMENT,request_id TEXT,account_id TEXT NOT NULL,user_id TEXT,- agent_id TEXT,method TEXT NOT NULL,route TEXT NOT NULL,api_type TEXT NOT NULL,@@ -119,6 +102,5 @@ RESET_ON_SCHEMA_UPGRADE_TABLES = ("usage_token_hourly","usage_retrieval_hourly","usage_context_write_bucket",- "usage_agent_activity_daily","request_audit",)diff --git a/openviking/observability/usage_audit/sqlite_store.py b/openviking/observability/usage_audit/sqlite_store.pyindex df1d3009d..16027b9be 100644--- a/openviking/observability/usage_audit/sqlite_store.py+++ b/openviking/observability/usage_audit/sqlite_store.py@@ -119,7 +119,6 @@ class SQLiteUsageAuditStore:self._write_token_rows(conn, projection.token_rows, updated_at)self._write_retrieval_rows(conn, projection.retrieval_rows, updated_at)self._write_context_rows(conn, projection.context_rows, updated_at)- self._write_agent_rows(conn, projection.agent_rows, updated_at)self._write_audit_rows(conn, projection.audit_rows)self._trim_usage_rows(conn, self._usage_max_dates(projection))self._trim_audit_rows(conn, projection.touched_audit_accounts)@@ -133,13 +132,13 @@ class SQLiteUsageAuditStore:conn.executemany("""INSERT INTO usage_token_hourly (- account_id, user_id, agent_id, date_utc, hour_utc,+ account_id, user_id, date_utc, hour_utc,source, token_type, provider, model_name,token_count, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)ON CONFLICT (- account_id, user_id, agent_id, date_utc, hour_utc,+ account_id, user_id, date_utc, hour_utc,source, token_type, provider, model_name)DO UPDATE SET@@ -154,12 +153,12 @@ class SQLiteUsageAuditStore:conn.executemany("""INSERT INTO usage_retrieval_hourly (- account_id, user_id, agent_id, date_utc, hour_utc,+ account_id, user_id, date_utc, hour_utc,operation, status, request_count, result_count, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)ON CONFLICT (- account_id, user_id, agent_id, date_utc, hour_utc, operation, status+ account_id, user_id, date_utc, hour_utc, operation, status)DO UPDATE SETrequest_count = request_count + excluded.request_count,@@ -177,12 +176,12 @@ class SQLiteUsageAuditStore:conn.executemany("""INSERT INTO usage_context_write_bucket (- account_id, user_id, agent_id, date_utc, hour_utc,+ account_id, user_id, date_utc, hour_utc,operation, count, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?)+ VALUES (?, ?, ?, ?, ?, ?, ?)ON CONFLICT (- account_id, user_id, agent_id, date_utc, hour_utc, operation+ account_id, user_id, date_utc, hour_utc, operation)DO UPDATE SETcount = count + excluded.count,@@ -191,32 +190,15 @@ class SQLiteUsageAuditStore:[(*key, value, updated_at) for key, value in rows.items() if value > 0],)- @staticmethod- def _write_agent_rows(conn, rows: dict[tuple, tuple[int, str]], updated_at: str) -> None:- conn.executemany(- """- INSERT INTO usage_agent_activity_daily (- account_id, agent_id, date_utc, request_count, last_seen_at, updated_at- )- VALUES (?, ?, ?, ?, ?, ?)- ON CONFLICT (account_id, agent_id, date_utc)- DO UPDATE SET- request_count = request_count + excluded.request_count,- last_seen_at = MAX(last_seen_at, excluded.last_seen_at),- updated_at = excluded.updated_at- """,- [(*key, count, last_seen, updated_at) for key, (count, last_seen) in rows.items()],- )-@staticmethoddef _write_audit_rows(conn, rows: list[tuple]) -> None:conn.executemany("""INSERT INTO request_audit (- request_id, account_id, user_id, agent_id, method, route,+ request_id, account_id, user_id, method, route,api_type, status_code, duration_ms, created_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",rows,)@@ -262,7 +244,6 @@ class SQLiteUsageAuditStore:"usage_token_hourly","usage_retrieval_hourly","usage_context_write_bucket",- "usage_agent_activity_daily",):conn.execute(f"DELETE FROM {table} WHERE account_id = ? AND date_utc < ?",@@ -272,14 +253,12 @@ class SQLiteUsageAuditStore:@staticmethoddef _usage_max_dates(projection: UsageAuditProjection) -> dict[str, str]:max_dates: dict[str, str] = {}- # token_rows: (account, user, agent, date_utc, hour_utc, source, ...)- SQLiteUsageAuditStore._merge_max_dates(max_dates, projection.token_rows, date_index=3)- # retrieval_rows: (account, user, agent, date_utc, hour_utc, op, status)- SQLiteUsageAuditStore._merge_max_dates(max_dates, projection.retrieval_rows, date_index=3)- # context_rows: (account, user, agent, date_utc, hour_utc, op)- SQLiteUsageAuditStore._merge_max_dates(max_dates, projection.context_rows, date_index=3)- # agent_rows: (account, agent, date_utc)- SQLiteUsageAuditStore._merge_max_dates(max_dates, projection.agent_rows, date_index=2)+ # token_rows: (account, user, date_utc, hour_utc, source, ...)+ SQLiteUsageAuditStore._merge_max_dates(max_dates, projection.token_rows, date_index=2)+ # retrieval_rows: (account, user, date_utc, hour_utc, op, status)+ SQLiteUsageAuditStore._merge_max_dates(max_dates, projection.retrieval_rows, date_index=2)+ # context_rows: (account, user, date_utc, hour_utc, op)+ SQLiteUsageAuditStore._merge_max_dates(max_dates, projection.context_rows, date_index=2)return max_dates@staticmethod@@ -367,65 +346,6 @@ class SQLiteUsageAuditStore:result["total"] = sum(result.values())return result- async def get_agent_overview(- self,- *,- account_id: str,- user_date: str,- tz: tzinfo,- limit: int = 5,- ) -> dict[str, Any]:- async with self._lock:- return await asyncio.to_thread(- self._get_agent_overview_sync,- account_id,- user_date,- tz,- int(limit),- )-- def _get_agent_overview_sync(- self, account_id: str, user_date: str, tz: tzinfo, limit: int- ) -> dict[str, Any]:- assert self._conn is not None- day = date.fromisoformat(user_date)- utc_start, utc_end = _user_day_window_utc(day, tz)- utc_start_iso = utc_start.isoformat()- utc_end_iso = utc_end.isoformat()- # last_seen_at is stored as a UTC ISO string by projection.py; compare- # lexicographically — ISO-8601 with fixed UTC offset is sort-safe.- total_cur = self._conn.execute(- """- SELECT COUNT(DISTINCT agent_id) AS total- FROM usage_agent_activity_daily- WHERE account_id = ?- AND last_seen_at >= ?- AND last_seen_at < ?- """,- (account_id, utc_start_iso, utc_end_iso),- )- total = int(total_cur.fetchone()["total"] or 0)- cur = self._conn.execute(- """- SELECT agent_id, MAX(last_seen_at) AS last_seen_at- FROM usage_agent_activity_daily- WHERE account_id = ?- AND last_seen_at >= ?- AND last_seen_at < ?- GROUP BY agent_id- ORDER BY last_seen_at DESC- LIMIT ?- """,- (account_id, utc_start_iso, utc_end_iso, limit),- )- return {- "total": total,- "items": [- {"agent_id": row["agent_id"], "last_seen_at": row["last_seen_at"]}- for row in cur.fetchall()- ],- }-async def get_token_series(self,*,@@ -706,7 +626,7 @@ class SQLiteUsageAuditStore:offset = max(page - 1, 0) * page_sizerows = self._conn.execute(f"""- SELECT request_id, account_id, user_id, agent_id, method, route, api_type,+ SELECT request_id, account_id, user_id, method, route, api_type,status_code, duration_ms, created_atFROM request_auditWHERE {where_sql}diff --git a/openviking/observability/usage_audit/store.py b/openviking/observability/usage_audit/store.pyindex ee00ef561..2ea423719 100644--- a/openviking/observability/usage_audit/store.py+++ b/openviking/observability/usage_audit/store.py@@ -36,11 +36,6 @@ class UsageAuditStore(Protocol):) -> dict[str, int]:"""Return successful find/search counts for one account and date."""- async def get_agent_overview(- self, *, account_id: str, user_date: str, tz: tzinfo, limit: int = 5- ) -> dict[str, Any]:- """Return distinct agent count and recent agents for the viewer's day."""-async def get_token_series(self,*,diff --git a/openviking/parse/tree_builder.py b/openviking/parse/tree_builder.pyindex 88850a9c4..18e33a667 100644--- a/openviking/parse/tree_builder.py+++ b/openviking/parse/tree_builder.py@@ -75,8 +75,7 @@ class TreeBuilder:if scope == "user":# user resources go to memories (no separate resources dir)return "viking://user"- # Agent scope- return "viking://agent"+ raise ValueError(f"unsupported tree scope: {scope}")# ============================================================================# v5.0 Methods (temporary directory + SemanticQueue architecture)@@ -133,9 +132,7 @@ class TreeBuilder:except FileNotFoundError:raiseexcept Exception as e:- raise FileNotFoundError(- f"Parent URI does not exist: {effective_parent_uri}"- ) from e+ raise FileNotFoundError(f"Parent URI does not exist: {effective_parent_uri}") from eif not stat_result.get("isDir"):raise ValueError(f"Parent URI is not a directory: {effective_parent_uri}")base_uri = effective_parent_uridiff --git a/openviking/prompts/templates/memory/experiences.yaml b/openviking/prompts/templates/memory/experiences.yamlindex f0b6fd7ab..c16b58ed9 100644--- a/openviking/prompts/templates/memory/experiences.yaml+++ b/openviking/prompts/templates/memory/experiences.yaml@@ -3,7 +3,7 @@ description: |A generalizable, reusable insight distilled from agent execution — not a process record.Captures a transferable pattern: what situation triggers it, what approach works, and why.-directory: "viking://agent/{{ agent_space }}/memories/experiences"+directory: "viking://user/{{ user_space }}/memories/experiences"filename_template: "{{ experience_name }}.md"enabled: trueoperation_mode: "upsert"diff --git a/openviking/prompts/templates/memory/identity.yaml b/openviking/prompts/templates/memory/identity.yamlindex a5dfbb684..ebc95e59d 100644--- a/openviking/prompts/templates/memory/identity.yaml+++ b/openviking/prompts/templates/memory/identity.yaml@@ -1,7 +1,7 @@memory_type: identitydescription: |Agent identity: name, creature type, vibe/temperament, signature emoji, avatar path, and self introduction.-directory: "viking://agent/{{ agent_space }}/memories"+directory: "viking://user/{{ user_space }}/memories"filename_template: "identity.md"enabled: trueoperation_mode: "upsert"@@ -57,4 +57,4 @@ fields:type: stringdescription: Self introductionmerge_op: patch- init_value: "The start of figuring out who you are."\ No newline at end of file+ init_value: "The start of figuring out who you are."diff --git a/openviking/prompts/templates/memory/skills.yaml b/openviking/prompts/templates/memory/skills.yamlindex 82d06e2ff..4054648f0 100644--- a/openviking/prompts/templates/memory/skills.yaml+++ b/openviking/prompts/templates/memory/skills.yaml@@ -1,7 +1,7 @@memory_type: skillsdescription: |Record all skills uses,-directory: "viking://agent/{{ agent_space }}/memories/skills"+directory: "viking://user/{{ user_space }}/memories/skills"filename_template: "{{ skill_name }}.md"enabled: truecontent_template: |diff --git a/openviking/prompts/templates/memory/soul.yaml b/openviking/prompts/templates/memory/soul.yamlindex bddcd6aa6..e569fd682 100644--- a/openviking/prompts/templates/memory/soul.yaml+++ b/openviking/prompts/templates/memory/soul.yaml@@ -1,7 +1,7 @@memory_type: souldescription: |Agent soul: core truths, boundaries, vibe, and continuity - defines who the agent is.-directory: "viking://agent/{{ agent_space }}/memories"+directory: "viking://user/{{ user_space }}/memories"filename_template: "soul.md"enabled: trueoperation_mode: "upsert"@@ -40,4 +40,4 @@ fields:type: stringdescription: Memory continuitymerge_op: patch- init_value: These files are your memory. Read them. Update them. If you change this file, tell the user.\ No newline at end of file+ init_value: These files are your memory. Read them. Update them. If you change this file, tell the user.diff --git a/openviking/prompts/templates/memory/tools.yaml b/openviking/prompts/templates/memory/tools.yamlindex 2d60eae46..8169b0d8e 100644--- a/openviking/prompts/templates/memory/tools.yaml+++ b/openviking/prompts/templates/memory/tools.yaml@@ -12,7 +12,7 @@ description: |- Trivial tool calls without learning value- Duplicate patterns already captured- Tool calls with no meaningful outcome-directory: "viking://agent/{{ agent_space }}/memories/tools"+directory: "viking://user/{{ user_space }}/memories/tools"filename_template: "{{ tool_name }}.md"enabled: truecontent_template: |diff --git a/openviking/prompts/templates/memory/trajectories.yaml b/openviking/prompts/templates/memory/trajectories.yamlindex 100e73e15..d4318103d 100644--- a/openviking/prompts/templates/memory/trajectories.yaml+++ b/openviking/prompts/templates/memory/trajectories.yaml@@ -10,7 +10,7 @@ embedding_template: |-{{ retrieval_anchor }}-directory: "viking://agent/{{ agent_space }}/memories/trajectories"+directory: "viking://user/{{ user_space }}/memories/trajectories"filename_template: "{{ trajectory_name }}_{{ extract_context.get_session_timestamp() }}.md"enabled: trueoperation_mode: "add_only"diff --git a/openviking/prompts/templates/skill_extract/session_skills.yaml b/openviking/prompts/templates/skill_extract/session_skills.yamlindex edbf8a0e5..71b4832a8 100644--- a/openviking/prompts/templates/skill_extract/session_skills.yaml+++ b/openviking/prompts/templates/skill_extract/session_skills.yaml@@ -100,7 +100,7 @@ description: |- Day3:输入 “分析这道新题”- Day7:输入 “再分析一道题”- 应用结果:Day3 和 Day7 自动应用 Day1 的规则,三次输出格式、细节保持一致。-directory: "viking://agent/{{ agent_space }}/skills"+directory: "viking://user/{{ user_space }}/skills"filename_template: "{{ skill_name }}/SKILL.md"enabled: truefields:diff --git a/openviking/resource/watch_manager.py b/openviking/resource/watch_manager.pyindex 87105c935..cdad6d94f 100644--- a/openviking/resource/watch_manager.py+++ b/openviking/resource/watch_manager.py@@ -48,7 +48,6 @@ class WatchTask(BaseModel):is_active: bool = Field(default=True, description="Whether the task is active")account_id: str = Field(default="default", description="Account ID (tenant)")user_id: str = Field(default="default", description="User ID who created this task")- agent_id: str = Field(default="default", description="Agent ID who created this task")original_role: str = Field(default="user", description="Role used to execute this task")class Config:@@ -78,7 +77,6 @@ class WatchTask(BaseModel):"is_active": self.is_active,"account_id": self.account_id,"user_id": self.user_id,- "agent_id": self.agent_id,"original_role": self.original_role,}@@ -275,7 +273,6 @@ class WatchManager:task: WatchTask,account_id: str,user_id: str,- agent_id: str,role: str,) -> bool:"""Check if user has permission to access/modify a task.@@ -284,7 +281,6 @@ class WatchManager:task: The task to check permission foraccount_id: Requester's account IDuser_id: Requester's user ID- agent_id: Requester's agent IDrole: Requester's role (ROOT/ADMIN/USER)Returns:@@ -293,7 +289,7 @@ class WatchManager:Notes:- ROOT can access all tasks.- ADMIN can access tasks within the same account.- - USER can only access tasks they created within the same account and agent.+ - USER can only access tasks they created within the same account."""role_value = (role or "").lower()if role_value == "root":@@ -305,7 +301,7 @@ class WatchManager:if role_value == "admin":return True- return task.user_id == user_id and task.agent_id == agent_id+ return task.user_id == user_iddef _check_uri_conflict(self, to_uri: Optional[str], exclude_task_id: Optional[str] = None@@ -336,7 +332,6 @@ class WatchManager:path: str,account_id: str = "default",user_id: str = "default",- agent_id: str = "default",original_role: str = "user",to_uri: Optional[str] = None,parent_uri: Optional[str] = None,@@ -353,7 +348,6 @@ class WatchManager:path: Resource path to monitoraccount_id: Account ID (tenant)user_id: User ID who creates this task- agent_id: Agent ID who creates this taskto_uri: Target URIparent_uri: Parent URIreason: Reason for monitoring@@ -391,7 +385,6 @@ class WatchManager:processor_kwargs=processor_kwargs or {},account_id=account_id,user_id=user_id,- agent_id=agent_id,original_role=original_role,)@@ -424,7 +417,6 @@ class WatchManager:summarize: Optional[bool] = None,processor_kwargs: Optional[Dict[str, Any]] = None,is_active: Optional[bool] = None,- agent_id: str = "default",) -> WatchTask:"""Update an existing monitoring task.@@ -433,7 +425,6 @@ class WatchManager:account_id: Requester's account IDuser_id: Requester's user IDrole: Requester's role (ROOT/ADMIN/USER)- agent_id: Requester's agent IDpath: New resource pathto_uri: New target URIparent_uri: New parent URI@@ -455,9 +446,9 @@ class WatchManager:if not task:raise ValueError(f"Task {task_id} not found")- if not self._check_permission(task, account_id, user_id, agent_id, role):+ if not self._check_permission(task, account_id, user_id, role):raise PermissionDeniedError(- f"User {account_id}/{user_id}/{agent_id} does not have permission to update task {task_id}"+ f"User {account_id}/{user_id} does not have permission to update task {task_id}")if self._check_uri_conflict(to_uri, exclude_task_id=task_id):@@ -527,7 +518,6 @@ class WatchManager:account_id: str,user_id: str,role: str,- agent_id: str = "default",) -> bool:"""Delete a monitoring task.@@ -536,7 +526,6 @@ class WatchManager:account_id: Requester's account IDuser_id: Requester's user IDrole: Requester's role (ROOT/ADMIN/USER)- agent_id: Requester's agent IDReturns:True if task was deleted, False if not found@@ -549,9 +538,9 @@ class WatchManager:if not task:return False- if not self._check_permission(task, account_id, user_id, agent_id, role):+ if not self._check_permission(task, account_id, user_id, role):raise PermissionDeniedError(- f"User {account_id}/{user_id}/{agent_id} does not have permission to delete task {task_id}"+ f"User {account_id}/{user_id} does not have permission to delete task {task_id}")self._tasks.pop(task_id, None)@@ -569,7 +558,6 @@ class WatchManager:account_id: str = "default",user_id: str = "default",role: str = "root",- agent_id: str = "default",) -> Optional[WatchTask]:"""Get a monitoring task by ID.@@ -578,7 +566,6 @@ class WatchManager:account_id: Requester's account IDuser_id: Requester's user IDrole: Requester's role (ROOT/ADMIN/USER)- agent_id: Requester's agent IDReturns:WatchTask if found and accessible, None otherwise@@ -588,7 +575,7 @@ class WatchManager:if not task:return None- if not self._check_permission(task, account_id, user_id, agent_id, role):+ if not self._check_permission(task, account_id, user_id, role):return Nonereturn task@@ -599,7 +586,6 @@ class WatchManager:user_id: str,role: str,active_only: bool = False,- agent_id: str = "default",) -> List[WatchTask]:"""Get all monitoring tasks accessible by the user.@@ -607,7 +593,6 @@ class WatchManager:account_id: Requester's account IDuser_id: Requester's user IDrole: Requester's role (ROOT/ADMIN/USER)- agent_id: Requester's agent IDactive_only: If True, only return active tasksReturns:@@ -616,7 +601,7 @@ class WatchManager:async with self._lock:tasks = []for task in self._tasks.values():- if not self._check_permission(task, account_id, user_id, agent_id, role):+ if not self._check_permission(task, account_id, user_id, role):continueif active_only and not task.is_active:continue@@ -629,7 +614,6 @@ class WatchManager:account_id: str,user_id: str,role: str,- agent_id: str = "default",) -> Optional[WatchTask]:"""Get a monitoring task by target URI.@@ -638,7 +622,6 @@ class WatchManager:account_id: Requester's account IDuser_id: Requester's user IDrole: Requester's role (ROOT/ADMIN/USER)- agent_id: Requester's agent IDReturns:WatchTask if found and accessible, None otherwise@@ -652,7 +635,7 @@ class WatchManager:if not task:return None- if not self._check_permission(task, account_id, user_id, agent_id, role):+ if not self._check_permission(task, account_id, user_id, role):return Nonereturn taskdiff --git a/openviking/resource/watch_scheduler.py b/openviking/resource/watch_scheduler.pyindex fe151bb9a..d1f32a1e2 100644--- a/openviking/resource/watch_scheduler.py+++ b/openviking/resource/watch_scheduler.py@@ -230,7 +230,6 @@ class WatchScheduler:user = UserIdentifier(account_id=task.account_id,user_id=task.user_id,- agent_id=task.agent_id,)role_value = getattr(task, "original_role", None) or Role.USER.valuetry:@@ -289,7 +288,6 @@ class WatchScheduler:account_id=task.account_id,user_id=task.user_id,role=getattr(task, "original_role", None) or Role.USER.value,- agent_id=task.agent_id,is_active=False,))diff --git a/openviking/retrieve/hierarchical_retriever.py b/openviking/retrieve/hierarchical_retriever.pyindex eea4b6b8d..9d79a1710 100644--- a/openviking/retrieve/hierarchical_retriever.py+++ b/openviking/retrieve/hierarchical_retriever.py@@ -15,12 +15,12 @@ import timefrom datetime import datetimefrom typing import Any, Dict, List, Optional, Tuple-from openviking.core.namespace import canonical_agent_root, canonical_user_root+from openviking.core.retrieval_targets import default_target_directoriesfrom openviking.models.embedder.base import EmbedResult, embed_compatfrom openviking.models.rerank import RerankClientfrom openviking.retrieve.memory_lifecycle import hotness_scorefrom openviking.retrieve.retrieval_stats import get_stats_collector-from openviking.server.identity import RequestContext, Role+from openviking.server.identity import RequestContextfrom openviking.storage import VikingDBManager, VikingDBManagerProxyfrom openviking.storage.viking_fs import get_viking_fsfrom openviking.telemetry import get_current_telemetry@@ -140,11 +140,11 @@ class HierarchicalRetriever:query_vector = result.dense_vectorsparse_query_vector = result.sparse_vector- # Step 1: Determine starting directories based on target_directories or context_type+ # Step 1: Determine starting directories based on explicit target dirs.if target_dirs:root_uris = target_dirselse:- root_uris = self._get_root_uris_for_type(query.context_type, ctx=ctx)+ root_uris = default_target_directories(ctx, context_type=query.context_type)# Step 2: Global vector search to supplement starting pointsglobal_results = await self._global_vector_search(@@ -625,34 +625,3 @@ class HierarchicalRetriever:if uri.endswith("/") and not uri.endswith("://"):uri = uri.rstrip("/")return f"{uri}/{suffix}"-- def _get_root_uris_for_type(- self, context_type: Optional[ContextType], ctx: Optional[RequestContext] = None- ) -> List[str]:- """Return starting directory URI list based on context_type and user context.-- When context_type is None, returns roots for all types.- ROOT has no space, relies on global_vector_search without URI prefix filter.- """- if not ctx or ctx.role == Role.ROOT:- return []-- user_root = canonical_user_root(ctx)- agent_root = canonical_agent_root(ctx)- if context_type is None:- return [- f"{user_root}/memories",- f"{agent_root}/memories",- "viking://resources",- f"{agent_root}/skills",- ]- elif context_type == ContextType.MEMORY:- return [- f"{user_root}/memories",- f"{agent_root}/memories",- ]- elif context_type == ContextType.RESOURCE:- return ["viking://resources"]- elif context_type == ContextType.SKILL:- return [f"{agent_root}/skills"]- return []diff --git a/openviking/server/api_keys/legacy.py b/openviking/server/api_keys/legacy.pyindex caca99fd2..d0ab22c38 100644--- a/openviking/server/api_keys/legacy.py+++ b/openviking/server/api_keys/legacy.py@@ -15,7 +15,7 @@ from argon2.exceptions import VerifyMismatchErrorfrom openviking.pyagfs import AsyncAGFSClientfrom openviking.server.api_keys.models import AccountInfo, UserKeyEntry-from openviking.server.identity import AccountNamespacePolicy, ResolvedIdentity, Role+from openviking.server.identity import ResolvedIdentity, Rolefrom openviking.storage.viking_fs import VikingFSfrom openviking_cli.exceptions import (AlreadyExistsError,@@ -30,7 +30,6 @@ logger = get_logger(__name__)ACCOUNTS_PATH = "/local/_system/accounts.json"USERS_PATH_TEMPLATE = "/local/{account_id}/_system/users.json"-SETTINGS_PATH_TEMPLATE = "/local/{account_id}/_system/setting.json"# Argon2id parameters - export with LEGACY_ prefix for reuse in new.py@@ -74,7 +73,6 @@ class LegacyAPIKeyManager:async def load(self) -> None:"""Load accounts and user keys from VikingFS into memory."""accounts_data = await self._read_json(ACCOUNTS_PATH)- fresh_workspace = accounts_data is Noneif accounts_data is None:# First run: create default accountnow = datetime.now(timezone.utc).isoformat()@@ -85,28 +83,11 @@ class LegacyAPIKeyManager:users_path = USERS_PATH_TEMPLATE.format(account_id=account_id)users_data = await self._read_json(users_path)users = users_data.get("users", {}) if users_data else {}- settings_path = SETTINGS_PATH_TEMPLATE.format(account_id=account_id)- settings_data = await self._read_json(settings_path)- namespace_policy, should_persist_settings, inferred_from_legacy = (- self._resolve_namespace_policy(- settings_data,- allow_legacy_inference=not fresh_workspace,- )- )self._accounts[account_id] = AccountInfo(created_at=info.get("created_at", ""),users=users,- namespace_policy=namespace_policy,)- if should_persist_settings:- await self._save_settings_json(account_id, settings_data=settings_data)- if inferred_from_legacy:- logger.info(- "Inferred namespace policy for legacy account %s using the historical "- "default user-shared/agent-shared layout",- account_id,- )for user_id, user_info in users.items():key_or_hash = user_info.get("key", "")@@ -158,28 +139,6 @@ class LegacyAPIKeyManager:sum(len(info.users) for info in self._accounts.values()),)- def _resolve_namespace_policy(- self,- settings_data: Optional[dict],- *,- allow_legacy_inference: bool,- ) -> tuple[AccountNamespacePolicy, bool, bool]:- """Resolve persisted namespace policy, with one-time inference for legacy accounts."""- namespace_data = settings_data.get("namespace") if isinstance(settings_data, dict) else None- if isinstance(namespace_data, dict):- return AccountNamespacePolicy.from_dict(namespace_data), False, False-- if allow_legacy_inference:- return self._infer_legacy_namespace_policy(), True, True- return AccountNamespacePolicy(), True, False-- def _infer_legacy_namespace_policy(self) -> AccountNamespacePolicy:- """Map pre-policy accounts to the compatibility default namespace policy."""- return AccountNamespacePolicy(- isolate_user_scope_by_agent=False,- isolate_agent_scope_by_user=False,- )-def resolve(self, api_key: str) -> ResolvedIdentity:"""Resolve an API key to identity. Sequential matching: root key first, then user key index."""if not api_key:@@ -200,7 +159,6 @@ class LegacyAPIKeyManager:role=entry.role,account_id=entry.account_id,user_id=entry.user_id,- namespace_policy=self.get_account_policy(entry.account_id),)else:# Verify plaintext key@@ -209,7 +167,6 @@ class LegacyAPIKeyManager:role=entry.role,account_id=entry.account_id,user_id=entry.user_id,- namespace_policy=self.get_account_policy(entry.account_id),)raise UnauthenticatedError("Invalid API Key")@@ -218,8 +175,6 @@ class LegacyAPIKeyManager:self,account_id: str,admin_user_id: str,- *,- namespace_policy: Optional[AccountNamespacePolicy] = None,) -> str:"""Create a new account (workspace) with its first admin user.@@ -238,7 +193,6 @@ class LegacyAPIKeyManager:now = datetime.now(timezone.utc).isoformat()key = self._generate_api_key()- policy = namespace_policy or AccountNamespacePolicy()if self._api_key_hashing_enabled:stored_key = self._hash_api_key(key)@@ -259,7 +213,6 @@ class LegacyAPIKeyManager:self._accounts[account_id] = AccountInfo(created_at=now,users={admin_user_id: user_info},- namespace_policy=policy,)entry = UserKeyEntry(@@ -278,7 +231,6 @@ class LegacyAPIKeyManager:await self._save_accounts_json()await self._save_users_json(account_id)- await self._save_settings_json(account_id)return keyasync def delete_account(self, account_id: str) -> None:@@ -488,19 +440,10 @@ class LegacyAPIKeyManager:"account_id": account_id,"created_at": info.created_at,"user_count": len(info.users),- **info.namespace_policy.to_dict(),})return result- def get_account_policy(self, account_id: Optional[str]) -> AccountNamespacePolicy:- if not account_id:- return AccountNamespacePolicy()- account = self._accounts.get(account_id)- if account is None:- return AccountNamespacePolicy()- return account.namespace_policy-def get_users(self,account_id: str,@@ -698,18 +641,3 @@ class LegacyAPIKeyManager:data = {"users": account.users}path = USERS_PATH_TEMPLATE.format(account_id=account_id)await self._write_json(path, data)-- async def _save_settings_json(- self,- account_id: str,- *,- settings_data: Optional[dict] = None,- ) -> None:- """Persist account namespace settings."""- account = self._accounts.get(account_id)- if account is None:- return- path = SETTINGS_PATH_TEMPLATE.format(account_id=account_id)- merged_settings = dict(settings_data) if isinstance(settings_data, dict) else {}- merged_settings["namespace"] = account.namespace_policy.to_dict()- await self._write_json(path, merged_settings)diff --git a/openviking/server/api_keys/models.py b/openviking/server/api_keys/models.pyindex cb95298a0..84713295f 100644--- a/openviking/server/api_keys/models.py+++ b/openviking/server/api_keys/models.py@@ -5,7 +5,7 @@from dataclasses import dataclass, fieldfrom typing import Dict-from openviking.server.identity import AccountNamespacePolicy, Role+from openviking.server.identity import Role@dataclass@@ -25,4 +25,3 @@ class AccountInfo:created_at: strusers: Dict[str, dict] = field(default_factory=dict)- namespace_policy: AccountNamespacePolicy = field(default_factory=AccountNamespacePolicy)diff --git a/openviking/server/api_keys/new.py b/openviking/server/api_keys/new.pyindex bb99dda9b..10cf5f26a 100644--- a/openviking/server/api_keys/new.py+++ b/openviking/server/api_keys/new.py@@ -15,7 +15,7 @@ from openviking.server.api_keys.legacy import (LegacyAPIKeyManager,)from openviking.server.api_keys.models import AccountInfo, UserKeyEntry-from openviking.server.identity import AccountNamespacePolicy, ResolvedIdentity, Role+from openviking.server.identity import ResolvedIdentity, Rolefrom openviking.storage.viking_fs import VikingFSfrom openviking_cli.exceptions import InvalidArgumentError, UnauthenticatedErrorfrom openviking_cli.session.user_id import validate_account_id, validate_user_id@@ -141,7 +141,6 @@ class NewAPIKeyManager:role=Role(user_info.get("role", "user")),account_id=account_id,user_id=user_id,- namespace_policy=self.get_account_policy(account_id),)else:# Plaintext key@@ -150,7 +149,6 @@ class NewAPIKeyManager:role=Role(user_info.get("role", "user")),account_id=account_id,user_id=user_id,- namespace_policy=self.get_account_policy(account_id),)except Exception:# If parsing fails or verification fails, fall through to try legacy path@@ -163,8 +161,6 @@ class NewAPIKeyManager:self,account_id: str,admin_user_id: str,- *,- namespace_policy: Optional[AccountNamespacePolicy] = None,) -> str:"""Create a new account (workspace) with its first admin user.@@ -180,7 +176,6 @@ class NewAPIKeyManager:# Generate new format keykey = generate_api_key(account_id, admin_user_id)- policy = namespace_policy or AccountNamespacePolicy()# Use legacy to create account but with our new key# We temporarily replace the generate method, call, then restore@@ -217,7 +212,6 @@ class NewAPIKeyManager:self._legacy._accounts[account_id] = AccountInfo(created_at=now,users={admin_user_id: user_info},- namespace_policy=policy,)entry = UserKeyEntry(@@ -235,7 +229,6 @@ class NewAPIKeyManager:await self._legacy._save_accounts_json()await self._legacy._save_users_json(account_id)- await self._legacy._save_settings_json(account_id)return keyasync def delete_account(self, account_id: str) -> None:@@ -379,9 +372,6 @@ class NewAPIKeyManager:"""List all accounts."""return self._legacy.get_accounts()- def get_account_policy(self, account_id: Optional[str]) -> AccountNamespacePolicy:- return self._legacy.get_account_policy(account_id)-def get_users(self,account_id: str,@@ -461,14 +451,3 @@ class NewAPIKeyManager:async def _save_users_json(self, account_id: str) -> None:return await self._legacy._save_users_json(account_id)-- async def _save_settings_json(- self,- account_id: str,- *,- settings_data: Optional[dict] = None,- ) -> None:- return await self._legacy._save_settings_json(- account_id,- settings_data=settings_data,- )diff --git a/openviking/server/app.py b/openviking/server/app.pyindex 06a972747..58a2499d1 100644--- a/openviking/server/app.py+++ b/openviking/server/app.py@@ -190,18 +190,25 @@ def create_app("APIKeyManager initialized with api_key_hashing_enabled=%s",config.api_key_hashing_enabled,)+ if effective_auth_mode == AuthMode.TRUSTED:+ logger.info(+ "Trusted mode enabled: authentication trusts X-OpenViking-Account/User "+ "headers and requires the configured server API key on each request. "+ "Only expose this server behind a trusted network boundary or "+ "identity-injecting gateway."+ )elif effective_auth_mode == AuthMode.TRUSTED:app.state.api_key_manager = Noneif config.root_api_key and config.root_api_key != "":logger.info(- "Trusted mode enabled: authentication trusts X-OpenViking-Account/User/Agent "+ "Trusted mode enabled: authentication trusts X-OpenViking-Account/User ""headers and requires the configured server API key on each request. ""Only expose this server behind a trusted network boundary or ""identity-injecting gateway.")else:logger.warning(- "Trusted mode enabled: authentication uses X-OpenViking-Account/User/Agent "+ "Trusted mode enabled: authentication uses X-OpenViking-Account/User ""headers without API keys. This is only allowed on localhost. ""Only expose this server behind a trusted network boundary or ""identity-injecting gateway after configuring server.root_api_key."diff --git a/openviking/server/auth.py b/openviking/server/auth.pyindex 9ea7d9d26..30826f56b 100644--- a/openviking/server/auth.py+++ b/openviking/server/auth.py@@ -8,7 +8,6 @@ from typing import Optionalfrom fastapi import Depends, Header, Requestfrom openviking.server.identity import (- AccountNamespacePolicy,AuthMode,RequestContext,ResolvedIdentity,@@ -29,19 +28,25 @@ from openviking_cli.session.user_id import UserIdentifier_ROLE_RANK = {Role.USER: 0, Role.ADMIN: 1, Role.ROOT: 2}-_ROOT_IMPLICIT_TENANT_ALLOWED_PATHS = {+_TRUSTED_RELAXED_IDENTITY_PREFIXES = ("/api/v1/admin",)+_API_KEY_ROOT_ALLOWED_PATHS = {"/api/v1/system/status","/api/v1/system/wait","/api/v1/debug/health",}-_ROOT_IMPLICIT_TENANT_ALLOWED_PREFIXES = (+_API_KEY_ROOT_ALLOWED_PREFIXES = ("/api/v1/admin","/api/v1/observer",+ "/api/v1/console",)-_ROOT_EXPLICIT_ACCOUNT_ONLY_PATHS = {- "/api/v1/content/reindex",-}-_TRUSTED_RELAXED_IDENTITY_PREFIXES = ("/api/v1/admin",)+++def _api_key_root_can_access_path(path: str) -> bool:+ if path in _API_KEY_ROOT_ALLOWED_PATHS:+ return True+ if path.startswith(_API_KEY_ROOT_ALLOWED_PREFIXES):+ return True+ return Falsedef _auth_mode(request: Request) -> AuthMode:@@ -51,25 +56,6 @@ def _auth_mode(request: Request) -> AuthMode:return AuthMode.API_KEY-def _root_request_requires_explicit_tenant(path: str) -> bool:- """Return True when a ROOT request targets tenant-scoped data APIs.-- Root still needs access to admin and monitoring endpoints without a tenant- context. For data APIs, implicit fallback to default/default is misleading.- """- if path in _ROOT_IMPLICIT_TENANT_ALLOWED_PATHS:- return False- if path in _ROOT_EXPLICIT_ACCOUNT_ONLY_PATHS:- return False- if path.startswith(_ROOT_IMPLICIT_TENANT_ALLOWED_PREFIXES):- return False- return True---def _root_request_requires_explicit_account_only(path: str) -> bool:- return path in _ROOT_EXPLICIT_ACCOUNT_ONLY_PATHS--def _trusted_request_requires_explicit_identity(path: str) -> bool:if path.startswith(_TRUSTED_RELAXED_IDENTITY_PREFIXES):return False@@ -129,7 +115,6 @@ async def _try_resolve_oauth_token(*,x_openviking_account: Optional[str],x_openviking_user: Optional[str],- x_openviking_agent: Optional[str],) -> Optional[ResolvedIdentity]:"""Attempt to verify the bearer as an OAuth-issued opaque access token.@@ -191,47 +176,23 @@ async def _try_resolve_oauth_token(account_id = record.account_iduser_id = record.user_id- # Header overrides mirror the API-key path: ROOT may override identity;- # ADMIN may override user and agent (within its own account); USER may- # override only agent. The OAuth claims pin the issuing identity, so any- # cross-account/user override beyond what each role can do is a 403.- if role == Role.ROOT:- effective_account = x_openviking_account or account_id- effective_user = x_openviking_user or user_id- elif role == Role.ADMIN:- if x_openviking_account and x_openviking_account != account_id:- raise PermissionDeniedError(- "X-OpenViking-Account cannot override the account for ADMIN OAuth tokens."- )- effective_account = account_id- effective_user = x_openviking_user or user_id- else: # Role.USER- if x_openviking_account and x_openviking_account != account_id:- raise PermissionDeniedError(- "X-OpenViking-Account cannot override the account for USER OAuth tokens."- )- if x_openviking_user and x_openviking_user != user_id:- raise PermissionDeniedError(- "X-OpenViking-User cannot override the user for USER OAuth tokens."- )- effective_account = account_id- effective_user = user_id-- effective_agent = x_openviking_agent or "default"+ # OAuth tokens are API-key-mode credentials with pinned claims. Header-based+ # identity assertion belongs to trusted mode only, so headers may not change+ # the effective account/user here.+ if x_openviking_account:+ raise PermissionDeniedError(+ "X-OpenViking-Account can only assert identity in trusted mode."+ )+ if x_openviking_user:+ raise PermissionDeniedError("X-OpenViking-User can only assert identity in trusted mode.")- namespace_policy = AccountNamespacePolicy()- if api_key_manager is not None and hasattr(api_key_manager, "get_account_policy"):- try:- namespace_policy = api_key_manager.get_account_policy(effective_account)- except Exception: # noqa: BLE001- pass+ effective_account = account_id+ effective_user = user_idreturn ResolvedIdentity(role=role,account_id=effective_account,user_id=effective_user,- agent_id=effective_agent,- namespace_policy=namespace_policy,from_oauth=True,)@@ -242,7 +203,6 @@ async def resolve_identity(authorization: Optional[str] = Header(None),x_openviking_account: Optional[str] = Header(None, alias="X-OpenViking-Account"),x_openviking_user: Optional[str] = Header(None, alias="X-OpenViking-User"),- x_openviking_agent: Optional[str] = Header(None, alias="X-OpenViking-Agent"),) -> ResolvedIdentity:"""Resolve API key to identity.@@ -255,7 +215,6 @@ async def resolve_identity(api_key_manager = getattr(request.app.state, "api_key_manager", None)x_openviking_account = _normalize_header_value(x_openviking_account)x_openviking_user = _normalize_header_value(x_openviking_user)- x_openviking_agent = _normalize_header_value(x_openviking_agent)api_key = _extract_api_key(x_api_key, authorization)if auth_mode == AuthMode.DEV:@@ -264,7 +223,6 @@ async def resolve_identity(role=Role.ROOT,account_id=x_openviking_account or "default",user_id=x_openviking_user or "default",- agent_id=x_openviking_agent or "default",)if auth_mode == AuthMode.TRUSTED:@@ -295,15 +253,21 @@ async def resolve_identity(effective_account_id = explicit_account_id or x_openviking_accounteffective_user_id = explicit_user_id or x_openviking_user- # Check if this is an admin path without identity+ # Admin paths may omit identity completely, but partial identity is rejected.is_admin_path = request.url.path.startswith(_TRUSTED_RELAXED_IDENTITY_PREFIXES)if is_admin_path:- return ResolvedIdentity(- role=Role.ROOT,- account_id="trusted",- user_id="trusted",- agent_id=x_openviking_agent or "default",- )+ if bool(effective_account_id) != bool(effective_user_id):+ raise InvalidArgumentError(+ "Trusted mode requests must include "+ "X-OpenViking-Account or explicit account_id in the URL and "+ "X-OpenViking-User or explicit user_id in the URL."+ )+ if not effective_account_id and not effective_user_id:+ return ResolvedIdentity(+ role=Role.ROOT,+ account_id="trusted",+ user_id="trusted",+ )if _trusted_request_requires_explicit_identity(request.url.path):missing_fields = []@@ -324,7 +288,6 @@ async def resolve_identity(role=trusted_role,account_id=effective_account_id or "trusted",user_id=effective_user_id or "trusted",- agent_id=x_openviking_agent or "default",)# AuthMode.API_KEY@@ -345,36 +308,21 @@ async def resolve_identity(api_key,x_openviking_account=x_openviking_account,x_openviking_user=x_openviking_user,- x_openviking_agent=x_openviking_agent,)if oauth_identity is not None:return oauth_identityidentity = api_key_manager.resolve(api_key)- if identity.role == Role.ROOT:- identity.account_id = x_openviking_account or identity.account_id or "default"- identity.user_id = x_openviking_user or identity.user_id or "default"- identity.agent_id = x_openviking_agent or identity.agent_id or "default"- return identity-identity.account_id = identity.account_id or "default"- if x_openviking_account and x_openviking_account != identity.account_id:- raise PermissionDeniedError(- "X-OpenViking-Account cannot override the account for ADMIN/USER API keys."- )-- if identity.role == Role.ADMIN:- identity.user_id = x_openviking_user or identity.user_id or "default"- identity.agent_id = x_openviking_agent or identity.agent_id or "default"- return identity-identity.user_id = identity.user_id or "default"- if x_openviking_user and x_openviking_user != identity.user_id:++ if x_openviking_account:raise PermissionDeniedError(- "USER API keys cannot override X-OpenViking-User; the effective user is derived "- "from the key."+ "X-OpenViking-Account can only assert identity in trusted mode.")- identity.agent_id = x_openviking_agent or identity.agent_id or "default"+ if x_openviking_user:+ raise PermissionDeniedError("X-OpenViking-User can only assert identity in trusted mode.")+return identity@@ -391,20 +339,13 @@ async def get_request_context(and api_key_manager is not Noneand identity.role == Role.ROOTand not identity.from_oauth+ and not _api_key_root_can_access_path(path)):- account_header = request.headers.get("X-OpenViking-Account")- if _root_request_requires_explicit_account_only(path):- if not account_header:- raise InvalidArgumentError(- "ROOT requests to reindex must include X-OpenViking-Account header."- )- elif _root_request_requires_explicit_tenant(path):- user_header = request.headers.get("X-OpenViking-User")- if not account_header or not user_header:- raise InvalidArgumentError(- "ROOT requests to tenant-scoped APIs must include X-OpenViking-Account "- "and X-OpenViking-User headers. Use a user key for regular data access."- )+ raise PermissionDeniedError(+ "ROOT API keys cannot access tenant-scoped data APIs in api_key mode. "+ "Use a user/admin API key for data access, or trusted mode for upstream "+ "identity assertion."+ )if auth_mode == AuthMode.TRUSTED:is_admin_path = path.startswith(_TRUSTED_RELAXED_IDENTITY_PREFIXES)@@ -420,14 +361,8 @@ async def get_request_context(user=UserIdentifier(identity.account_id or "default",identity.user_id or "default",- identity.agent_id or "default",),role=identity.role,- namespace_policy=(- api_key_manager.get_account_policy(identity.account_id)- if api_key_manager is not None and hasattr(api_key_manager, "get_account_policy")- else identity.namespace_policy- ),from_oauth=identity.from_oauth,)# Update the unified root observability context after authentication succeeds.@@ -435,7 +370,6 @@ async def get_request_context(request_state=request.state,account_id=identity.account_id,user_id=identity.user_id,- agent_id=identity.agent_id,)return ctxdiff --git a/openviking/server/identity.py b/openviking/server/identity.pyindex b35dfd2d3..164bdbd24 100644--- a/openviking/server/identity.py+++ b/openviking/server/identity.py@@ -28,29 +28,6 @@ class AuthMode(str, Enum):DEV = "dev"-@dataclass(frozen=True)-class AccountNamespacePolicy:- """Account-level namespace isolation policy."""-- isolate_user_scope_by_agent: bool = False- isolate_agent_scope_by_user: bool = False-- @classmethod- def from_dict(cls, data: Optional[dict]) -> "AccountNamespacePolicy":- if not isinstance(data, dict):- return cls()- return cls(- isolate_user_scope_by_agent=bool(data.get("isolate_user_scope_by_agent", False)),- isolate_agent_scope_by_user=bool(data.get("isolate_agent_scope_by_user", False)),- )-- def to_dict(self) -> dict:- return {- "isolate_user_scope_by_agent": self.isolate_user_scope_by_agent,- "isolate_agent_scope_by_user": self.isolate_agent_scope_by_user,- }--@dataclassclass ResolvedIdentity:"""Output of auth middleware: raw identity resolved from API Key."""@@ -58,8 +35,6 @@ class ResolvedIdentity:role: Roleaccount_id: Optional[str] = Noneuser_id: Optional[str] = None- agent_id: Optional[str] = None- namespace_policy: AccountNamespacePolicy = field(default_factory=AccountNamespacePolicy)# True when this identity was minted from an OAuth-issued bearer token;# downstream checks (e.g. ROOT-requires-explicit-tenant headers) can skip# rules that target raw API-key auth, since OAuth claims already pin@@ -73,7 +48,6 @@ class RequestContext:user: UserIdentifierrole: Role- namespace_policy: AccountNamespacePolicy = field(default_factory=AccountNamespacePolicy)# Mirrors ResolvedIdentity.from_oauth. Routes that mint OAuth state# (OTP issuance, oauth-verify) reject callers with from_oauth=True to# prevent a stolen access token from laundering itself into a long-lived@@ -84,25 +58,6 @@ class RequestContext:def account_id(self) -> str:return self.user.account_id- def resolve_role_id(self, message_role: str, override: Optional[str] = None) -> Optional[str]:- """Resolve the role_id for a message, with fallback to ctx identity.-- `message_role` is the message-level role ("user" / "assistant"), distinct- from `RequestContext.role` (the authz role).-- - If `override` is truthy, returns it as-is (caller-supplied wins).- - For message_role="user", falls back to `user.user_id`.- - For message_role="assistant", falls back to `user.agent_id`.- - Any other message_role returns None when no override is given.- """- if override:- return override- if message_role == "user":- return self.user.user_id- if message_role == "assistant":- return self.user.agent_id- return None-@dataclassclass ToolContext:@@ -126,7 +81,3 @@ class ToolContext:@propertydef account_id(self) -> str:return self.request_ctx.user.account_id-- @property- def namespace_policy(self) -> AccountNamespacePolicy:- return self.request_ctx.namespace_policydiff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.pyindex a42e487fb..d222606a9 100644--- a/openviking/server/mcp_endpoint.py+++ b/openviking/server/mcp_endpoint.py@@ -10,7 +10,7 @@ Mounted on the FastAPI app at /mcp. The MCP session manager lifecycle istied to the FastAPI app lifespan (not a sub-app lifespan) so the task groupis always initialized before requests arrive.-Identity headers (X-OpenViking-Account, X-OpenViking-User, X-OpenViking-Agent)+Identity headers (X-OpenViking-Account, X-OpenViking-User)are extracted from HTTP request scope and propagated via contextvars."""@@ -145,7 +145,6 @@ class _IdentityASGIMiddleware:authorization=request.headers.get("authorization"),x_openviking_account=request.headers.get("x-openviking-account"),x_openviking_user=request.headers.get("x-openviking-user"),- x_openviking_agent=request.headers.get("x-openviking-agent"),)except (UnauthenticatedError, PermissionDeniedError, InvalidArgumentError) as exc:status = (@@ -175,10 +174,8 @@ class _IdentityASGIMiddleware:user=UserIdentifier(identity.account_id or "default",identity.user_id or "default",- identity.agent_id or "default",),role=identity.role,- namespace_policy=identity.namespace_policy,)url_info = {"x_forwarded_proto": request.headers.get("x-forwarded-proto"),@@ -214,6 +211,7 @@ async def find(limit: int = 10,min_score: float = 0.35,level: Optional[List[int]] = None,+ peer_id: Optional[str] = None,) -> str:"""Fast semantic retrieval without session context. Returns ranked memories, resources, and skills with URI, abstract, and score."""service = get_service()@@ -221,6 +219,7 @@ async def find(query=query,ctx=_get_ctx(),target_uri=target_uri,+ peer_id=peer_id,limit=limit,score_threshold=min_score,level=level,@@ -236,6 +235,7 @@ async def search(limit: int = 10,min_score: float = 0.35,level: Optional[List[int]] = None,+ peer_id: Optional[str] = None,) -> str:"""Deep semantic retrieval with optional session context and intent analysis. Returns ranked memories, resources, and skills with URI, abstract, and score."""service = get_service()@@ -248,6 +248,7 @@ async def search(query=query,ctx=ctx,target_uri=target_uri,+ peer_id=peer_id,session=session,limit=limit,score_threshold=min_score,@@ -366,7 +367,6 @@ async def remember(messages: list[StoreMessage]) -> str:session.add_message(msg.role,[TextPart(text=msg.content)],- role_id=ctx.resolve_role_id(msg.role),)await service.sessions.commit_async(session_id, ctx)return f"Stored {len(messages)} message(s) and committed for memory extraction."@@ -565,7 +565,6 @@ async def add_resource(token, expires_at = upload_token_store.issue(ctx.user.account_id,ctx.user.user_id,- ctx.user.agent_id,ttl_seconds=ttl_seconds,)base_url, url_source = _resolve_public_base_url()@@ -613,7 +612,7 @@ async def add_resource(@mcp.tool()async def list_watches() -> str:- """List watch tasks (auto-refresh subscriptions) visible to the current agent.+ """List watch tasks (auto-refresh subscriptions) visible to the current user.Each line shows: target URI, refresh interval (minutes), active/paused status,and the next scheduled execution time. Returns "No watch tasks." when empty.@@ -634,7 +633,6 @@ async def list_watches() -> str:ctx.user.user_id,ctx.role.value,active_only=False,- agent_id=ctx.user.agent_id,)if not tasks:return "No watch tasks."@@ -670,7 +668,6 @@ async def cancel_watch(to_uri: str) -> str:ctx.account_id,ctx.user.user_id,ctx.role.value,- ctx.user.agent_id,)if task is None:return f"No watch task found for {to_uri}"@@ -686,7 +683,6 @@ async def cancel_watch(to_uri: str) -> str:ctx.account_id,ctx.user.user_id,ctx.role.value,- ctx.user.agent_id,)except _wm_mod.PermissionDeniedError:return f"Permission denied for {to_uri}"diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.pyindex 684930f43..1d97d521c 100644--- a/openviking/server/routers/admin.py+++ b/openviking/server/routers/admin.py@@ -13,10 +13,10 @@ from openviking.server.auth import ()from openviking.server.config import ServerConfigfrom openviking.server.dependencies import get_service-from openviking.server.identity import AccountNamespacePolicy, RequestContext, Role+from openviking.server.identity import RequestContext, Rolefrom openviking.server.models import Responsefrom openviking.storage.viking_fs import get_viking_fs-from openviking_cli.exceptions import InvalidArgumentError, NotFoundError, PermissionDeniedError+from openviking_cli.exceptions import InvalidArgumentError, PermissionDeniedErrorfrom openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils.logger import get_logger@@ -28,8 +28,6 @@ router = APIRouter(prefix="/api/v1/admin", tags=["admin"])class CreateAccountRequest(BaseModel):account_id: stradmin_user_id: str- isolate_user_scope_by_agent: bool = False- isolate_agent_scope_by_user: bool = Falseclass RegisterUserRequest(BaseModel):@@ -91,27 +89,20 @@ async def create_account():"""Create a new account (workspace) with its first admin user."""manager = _get_api_key_manager(request)- policy = AccountNamespacePolicy(- isolate_user_scope_by_agent=body.isolate_user_scope_by_agent,- isolate_agent_scope_by_user=body.isolate_agent_scope_by_user,- )user_key = await manager.create_account(body.account_id,body.admin_user_id,- namespace_policy=policy,)service = get_service()account_ctx = RequestContext(- user=UserIdentifier(body.account_id, body.admin_user_id, "default"),+ user=UserIdentifier(body.account_id, body.admin_user_id),role=Role.ADMIN,- namespace_policy=policy,)await service.initialize_account_directories(account_ctx)await service.initialize_user_directories(account_ctx)result = {"account_id": body.account_id,"admin_user_id": body.admin_user_id,- **policy.to_dict(),}if _should_expose_user_key(request):result["user_key"] = user_key@@ -142,7 +133,7 @@ async def delete_account(# Build a ROOT-level context scoped to the target account for cleanupcleanup_ctx = RequestContext(- user=UserIdentifier(account_id, "system", "system"),+ user=UserIdentifier(account_id, "system"),role=Role.ROOT,)@@ -150,7 +141,6 @@ async def delete_account(viking_fs = get_viking_fs()account_prefixes = ["viking://user/",- "viking://agent/","viking://session/","viking://resources/",]@@ -192,9 +182,8 @@ async def register_user(user_key = await manager.register_user(account_id, body.user_id, resolved_role.value)service = get_service()user_ctx = RequestContext(- user=UserIdentifier(account_id, body.user_id, "default"),+ user=UserIdentifier(account_id, body.user_id),role=Role.USER,- namespace_policy=manager.get_account_policy(account_id),)await service.initialize_user_directories(user_ctx)result = {@@ -226,48 +215,6 @@ async def list_users(return Response(status="ok", result=users)[email protected]("/accounts/{account_id}/agents")-@require_auth_root_or_admin-async def list_agents(- request: Request,- account_id: str = Path(..., description="Account ID"),- ctx: RequestContext = Depends(get_request_context),-):- """List agent namespaces that have data under an account."""- _check_account_access(ctx, account_id)- manager = _get_api_key_manager(request)- manager.get_users(account_id, limit=1, expose_key=False)- policy = manager.get_account_policy(account_id)- viking_fs = get_viking_fs()- list_ctx = RequestContext(- user=UserIdentifier(account_id, "system", "system"),- role=Role.ROOT,- namespace_policy=policy,- )-- try:- entries = await viking_fs.ls("viking://agent", ctx=list_ctx, output="original")- except NotFoundError:- entries = []-- agents = []- for entry in entries:- if not entry.get("isDir", False):- continue- agent_id = str(entry.get("name", "")).strip()- if not agent_id:- continue- agents.append(- {- "agent_id": agent_id,- "uri": f"viking://agent/{agent_id}",- }- )-- agents.sort(key=lambda item: item["agent_id"])- return Response(status="ok", result=agents)--@router.delete("/accounts/{account_id}/users/{user_id}")@require_auth_root_or_adminasync def remove_user(diff --git a/openviking/server/routers/resources.py b/openviking/server/routers/resources.pyindex d4983ce7d..b1612859b 100644--- a/openviking/server/routers/resources.py+++ b/openviking/server/routers/resources.py@@ -10,7 +10,7 @@ from pydantic import BaseModel, ConfigDict, model_validatorfrom openviking.core.path_variables import resolve_path_variablesfrom openviking.server.auth import get_request_contextfrom openviking.server.dependencies import get_service-from openviking.server.identity import AccountNamespacePolicy, RequestContext, Role+from openviking.server.identity import RequestContext, Rolefrom openviking.server.local_input_guard import require_remote_resource_sourcefrom openviking.server.responses import response_from_resultfrom openviking.server.telemetry import run_operation@@ -149,24 +149,23 @@ async def temp_upload_signed("""Upload via short-lived signed token. Used by the MCP progressive-upload flow.No identity headers required — the token (issued by ``add_resource`` MCP for local-file- paths) carries the bound (account_id, user_id, agent_id). The token is consumed on first+ paths) carries the bound (account_id, user_id). The token is consumed on firstuse; subsequent attempts return 401. The server mints the ``temp_file_id`` at write time- and returns it in the response body; the agent then calls ``add_resource`` with that id.+ and returns it in the response body; the caller then calls ``add_resource`` with that id.Persistence flows through :class:`TempUploadStore`, so the same local/shared upload modesand size limit (``temp_upload.shared_max_size_bytes``) as the auth'd ``/temp_upload`` routeapply here too."""try:- account_id, user_id, agent_id = upload_token_store.consume(token)+ account_id, user_id = upload_token_store.consume(token)except UploadTokenError as exc:raise HTTPException(status_code=401, detail=str(exc)) from exctry:ctx = RequestContext(- user=UserIdentifier(account_id, user_id, agent_id),+ user=UserIdentifier(account_id, user_id),role=Role.USER,- namespace_policy=AccountNamespacePolicy(),)except ValueError as exc:raise HTTPException(status_code=400, detail=f"invalid identity in token: {exc}") from excdiff --git a/openviking/server/routers/search.py b/openviking/server/routers/search.pyindex de2f4ec63..31569ea1a 100644--- a/openviking/server/routers/search.py+++ b/openviking/server/routers/search.py@@ -6,9 +6,10 @@ import mathfrom typing import Any, Dict, List, Literal, Optional, Unionfrom fastapi import APIRouter, Depends-from pydantic import BaseModel+from pydantic import BaseModel, model_validatorfrom openviking.core.path_variables import resolve_path_variables+from openviking.core.peer_id import normalize_peer_idfrom openviking.pyagfs.exceptions import AGFSClientError, AGFSNotFoundErrorfrom openviking.server.auth import get_request_contextfrom openviking.server.dependencies import get_service@@ -71,6 +72,7 @@ class FindRequest(BaseModel):query: strtarget_uri: Union[str, List[str]] = ""+ peer_id: Optional[str] = Nonelimit: int = 10node_limit: Optional[int] = Nonescore_threshold: Optional[float] = None@@ -82,12 +84,18 @@ class FindRequest(BaseModel):level: Optional[Union[int, str, List[int]]] = Nonetelemetry: TelemetryRequest = False+ @model_validator(mode="after")+ def normalize_request_peer_id(self) -> "FindRequest":+ self.peer_id = normalize_peer_id(self.peer_id)+ return self+class SearchRequest(BaseModel):"""Request model for search with session."""query: strtarget_uri: Union[str, List[str]] = ""+ peer_id: Optional[str] = Nonesession_id: Optional[str] = Nonelimit: int = 10node_limit: Optional[int] = None@@ -101,6 +109,11 @@ class SearchRequest(BaseModel):level: Optional[Union[int, str, List[int]]] = Nonetelemetry: TelemetryRequest = False+ @model_validator(mode="after")+ def normalize_request_peer_id(self) -> "SearchRequest":+ self.peer_id = normalize_peer_id(self.peer_id)+ return self+class GrepRequest(BaseModel):"""Request model for grep."""@@ -143,6 +156,7 @@ async def find(query=request.query,ctx=_ctx,target_uri=resolved_target_uri,+ peer_id=request.peer_id,limit=actual_limit,score_threshold=request.score_threshold,filter=effective_filter,@@ -185,6 +199,7 @@ async def search(query=request.query,ctx=_ctx,target_uri=resolved_target_uri,+ peer_id=request.peer_id,session=session,limit=actual_limit,score_threshold=request.score_threshold,diff --git a/openviking/server/routers/sessions.py b/openviking/server/routers/sessions.pyindex 5636abbd4..08ff9f90c 100644--- a/openviking/server/routers/sessions.py+++ b/openviking/server/routers/sessions.py@@ -8,6 +8,7 @@ from fastapi import APIRouter, Body, Depends, Path, Query, Requestfrom pydantic import BaseModel, Field, model_validatorfrom openviking.core.path_variables import resolve_path_variables+from openviking.core.peer_id import normalize_peer_idfrom openviking.message.part import Part, TextPart, part_from_dictfrom openviking.server.auth import get_request_contextfrom openviking.server.dependencies import get_service@@ -83,7 +84,7 @@ class AddMessageRequest(BaseModel):"""role: str- role_id: Optional[str] = None+ peer_id: Optional[str] = Nonecontent: Optional[str] = Noneparts: Optional[List[Dict[str, Any]]] = Nonecreated_at: Optional[str] = None@@ -93,6 +94,7 @@ class AddMessageRequest(BaseModel):def validate_content_or_parts(self) -> "AddMessageRequest":if self.content is None and self.parts is None:raise ValueError("Either 'content' or 'parts' must be provided")+ self.peer_id = normalize_peer_id(self.peer_id)return self@@ -114,6 +116,7 @@ class CreateSessionRequest(BaseModel):"""Request model for creating a session."""session_id: Optional[str] = None+ memory_policy: Optional[Dict[str, Any]] = Nonetelemetry: TelemetryRequest = False@@ -168,8 +171,11 @@ async def create_session(async def _create() -> dict[str, Any]:await service.initialize_user_directories(_ctx)- await service.initialize_agent_directories(_ctx)- session = await service.sessions.create(_ctx, request.session_id)+ session = await service.sessions.create(+ _ctx,+ request.session_id,+ memory_policy=request.memory_policy,+ )return {"session_id": session.session_id,"user": session.user.to_dict(),@@ -206,10 +212,7 @@ async def get_session(try:session = await service.sessions.get(session_id, _ctx, auto_create=auto_create)except NotFoundError:- return Response(- status="error",- error=ErrorInfo(code="NOT_FOUND", message=f"Session {session_id} not found"),- )+ return error_response("NOT_FOUND", f"Session {session_id} not found")result = session.meta.to_dict()result["user"] = session.user.to_dict()result["pending_tokens"] = int(session.meta.pending_tokens or 0)@@ -293,8 +296,7 @@ async def get_session_context()service = get_service()- session = service.sessions.session(_ctx, session_id)- await session.load()+ session = await service.sessions.get(session_id, _ctx, auto_create=False)result = await session.get_session_context(token_budget=token_budget)return Response(status="ok", result=_to_jsonable(result))@@ -309,8 +311,7 @@ async def get_session_archive(from openviking_cli.exceptions import NotFoundErrorservice = get_service()- session = service.sessions.session(_ctx, session_id)- await session.load()+ session = await service.sessions.get(session_id, _ctx, auto_create=False)try:result = await session.get_session_archive(archive_id)except NotFoundError:@@ -351,6 +352,7 @@ class CommitRequest(BaseModel):"(default 10); compact path passes 0 to archive everything."),)+ memory_policy: Optional[Dict[str, Any]] = Nonetelemetry: TelemetryRequest = False@@ -371,7 +373,10 @@ async def commit_session(operation="session.commit",telemetry=body.telemetry,fn=lambda: service.sessions.commit_async(- session_id, _ctx, keep_recent_count=body.keep_recent_count+ session_id,+ _ctx,+ keep_recent_count=body.keep_recent_count,+ memory_policy=body.memory_policy,),)return Response(@@ -417,15 +422,18 @@ async def add_message(async def _add() -> dict[str, Any]:session = await service.sessions.get(session_id, _ctx, auto_create=True)- role_id = _ctx.resolve_role_id(request.role, request.role_id)parts = _resolve_message_parts(request)- session.add_messages([{- "role": request.role,- "parts": parts,- "role_id": role_id,- "created_at": request.created_at,- }])+ session.add_messages(+ [+ {+ "role": request.role,+ "parts": parts,+ "peer_id": request.peer_id,+ "created_at": request.created_at,+ }+ ]+ )return {"session_id": session_id,"message_count": len(session.messages),@@ -456,14 +464,15 @@ async def batch_add_messages(session = await service.sessions.get(session_id, _ctx, auto_create=True)specs = []for msg_request in request.messages:- role_id = _ctx.resolve_role_id(msg_request.role, msg_request.role_id)parts = _resolve_message_parts(msg_request)- specs.append({- "role": msg_request.role,- "parts": parts,- "role_id": role_id,- "created_at": msg_request.created_at,- })+ specs.append(+ {+ "role": msg_request.role,+ "parts": parts,+ "peer_id": msg_request.peer_id,+ "created_at": msg_request.created_at,+ }+ )msgs = session.add_messages(specs)return {"session_id": session_id,@@ -487,8 +496,7 @@ async def record_used():"""Record actually used contexts and skills in a session."""service = get_service()- session = service.sessions.session(_ctx, session_id)- await session.load()+ session = await service.sessions.get(session_id, _ctx, auto_create=False)# Resolve path variables in contextsresolved_contexts = Nonediff --git a/openviking/server/routers/system.py b/openviking/server/routers/system.pyindex 93bc08699..0b0058ab0 100644--- a/openviking/server/routers/system.py+++ b/openviking/server/routers/system.py@@ -49,7 +49,6 @@ async def health_check(request: Request):authorization = request.headers.get("Authorization")x_openviking_account = request.headers.get("X-OpenViking-Account")x_openviking_user = request.headers.get("X-OpenViking-User")- x_openviking_agent = request.headers.get("X-OpenViking-Agent")# Get effective auth mode from configeffective_auth_mode = AuthMode.API_KEY@@ -66,11 +65,9 @@ async def health_check(request: Request):authorization=authorization,x_openviking_account=x_openviking_account,x_openviking_user=x_openviking_user,- x_openviking_agent=x_openviking_agent,)result["account_id"] = str(identity.account_id)result["user_id"] = str(identity.user_id)- result["agent_id"] = str(identity.agent_id)result["role"] = identity.role.valueexcept Exception as e:logger.warning(f"Failed to resolve identity: {e}")@@ -141,9 +138,7 @@ async def readiness_check(request: Request):ov_config = OpenVikingConfigSingleton.get_instance()embedder = ov_config.embedding.get_embedder()if embedder is not None:- probe_result = await asyncio.wait_for(- _embedding_probe(embedder), timeout=10.0- )+ probe_result = await asyncio.wait_for(_embedding_probe(embedder), timeout=10.0)checks["embedding"] = probe_resultelse:checks["embedding"] = "not_configured"diff --git a/openviking/server/routers/watches.py b/openviking/server/routers/watches.pyindex 27dcdeb05..32ce94e9d 100644--- a/openviking/server/routers/watches.py+++ b/openviking/server/routers/watches.py@@ -90,7 +90,7 @@ def _scheduler():def _identity(ctx: RequestContext):- return (ctx.account_id, ctx.user.user_id, ctx.role.value, ctx.user.agent_id)+ return (ctx.account_id, ctx.user.user_id, ctx.role.value)async def _resolve_task(@@ -113,11 +113,11 @@ async def _resolve_task(raise InvalidArgumentError("Either {task_id} or ?to_uri= is required")wm = _wm()- account_id, user_id, role, agent_id = _identity(ctx)+ account_id, user_id, role = _identity(ctx)if task_id:- task = await wm.get_task(task_id, account_id, user_id, role, agent_id)+ task = await wm.get_task(task_id, account_id, user_id, role)else:- task = await wm.get_task_by_uri(to_uri, account_id, user_id, role, agent_id)+ task = await wm.get_task_by_uri(to_uri, account_id, user_id, role)# `wm.get_task*` return None for both "task does not exist" and "task# exists but the caller fails the permission check" (watch_manager.py# `_check_permission`). Collapsing both into 404 is deliberate: it avoids@@ -155,15 +155,13 @@ async def list_or_get_watch(URI still 404s — the active-only filter stays consistent in both modes."""wm = _wm()- account_id, user_id, role, agent_id = _identity(_ctx)+ account_id, user_id, role = _identity(_ctx)if to_uri:- task = await wm.get_task_by_uri(to_uri, account_id, user_id, role, agent_id)+ task = await wm.get_task_by_uri(to_uri, account_id, user_id, role)if task is None or (active_only and not task.is_active):raise NotFoundError(to_uri, "watch_task")return Response(status="ok", result=task.to_dict())- tasks = await wm.get_all_tasks(- account_id, user_id, role, active_only=active_only, agent_id=agent_id- )+ tasks = await wm.get_all_tasks(account_id, user_id, role, active_only=active_only)return Response(status="ok", result={"tasks": [t.to_dict() for t in tasks], "total": len(tasks)})@@ -203,14 +201,13 @@ async def _patch_impl(target: WatchTask, body: UpdateWatchRequest, ctx: RequestCit to 404 to stay consistent with the pre-check behavior."""wm = _wm()- account_id, user_id, role, agent_id = _identity(ctx)+ account_id, user_id, role = _identity(ctx)try:updated = await wm.update_task(target.task_id,account_id,user_id,role,- agent_id=agent_id,watch_interval=body.watch_interval,is_active=body.is_active,reason=body.reason,@@ -258,9 +255,9 @@ async def patch_watch_by_uri(async def _delete_impl(target: WatchTask, ctx: RequestContext):wm = _wm()- account_id, user_id, role, agent_id = _identity(ctx)+ account_id, user_id, role = _identity(ctx)try:- ok = await wm.delete_task(target.task_id, account_id, user_id, role, agent_id)+ ok = await wm.delete_task(target.task_id, account_id, user_id, role)except wm_mod.PermissionDeniedError as e:raise _translate_perm(e, target.to_uri or target.task_id) from eif not ok:diff --git a/openviking/server/temp_upload_store.py b/openviking/server/temp_upload_store.pyindex 40bb4f1e3..e79a6e10f 100644--- a/openviking/server/temp_upload_store.py+++ b/openviking/server/temp_upload_store.py@@ -111,7 +111,6 @@ class TempUploadStore:return RequestContext(user=ctx.user,role=Role.ROOT,- namespace_policy=ctx.namespace_policy,)async def save_upload(@@ -223,7 +222,6 @@ class TempUploadStore:"temp_file_id": temp_file_id,"account": ctx.account_id,"user": ctx.user.user_id,- "agent": ctx.user.agent_id,"original_filename": upload_file.filename or "","content_type": getattr(upload_file, "content_type", None),"file_ext": Path(upload_file.filename or "").suffix,diff --git a/openviking/server/upload_token_store.py b/openviking/server/upload_token_store.pyindex 6a9d272db..a9f770525 100644--- a/openviking/server/upload_token_store.py+++ b/openviking/server/upload_token_store.py@@ -2,14 +2,14 @@# SPDX-License-Identifier: AGPL-3.0"""In-memory store for short-lived upload tokens used by the MCP progressive upload flow.-Issued by the MCP ``add_resource`` tool when an agent passes a local-file path; consumed by+Issued by the MCP ``add_resource`` tool when a caller passes a local-file path; consumed by``POST /api/v1/resources/temp_upload_signed``. Tokens are 6-character base62 strings indexedin a process-local dict — no signing key, no on-disk state, no replay-set bookkeeping.``dict.pop`` doubles as the consume-and-burn primitive.-The token only carries the identity bound at issue time (account/user/agent). The+The token only carries the identity bound at issue time (account/user). The``temp_file_id`` is minted by :class:`openviking.server.temp_upload_store.TempUploadStore`-at upload time and returned to the agent in the upload response body — the token does+at upload time and returned in the upload response body — the token doesnot pre-bind a filename, so the upload can flow through either the local or sharedTempUploadStore mode without a side-channel.@@ -38,7 +38,6 @@ class UploadTokenError(Exception):class _TokenInfo:account_id: struser_id: str- agent_id: strexpires_at: float@@ -50,13 +49,12 @@ class UploadTokenStore:self,account_id: str,user_id: str,- agent_id: str,ttl_seconds: int,) -> Tuple[str, float]:- """Mint a fresh token bound to (account, user, agent). Returns (token, expires_at)."""+ """Mint a fresh token bound to (account, user). Returns (token, expires_at)."""self._purge_expired()expires_at = time.time() + max(1, ttl_seconds)- info = _TokenInfo(account_id, user_id, agent_id, expires_at)+ info = _TokenInfo(account_id, user_id, expires_at)for _ in range(8):token = "".join(secrets.choice(_TOKEN_ALPHABET) for _ in range(_TOKEN_LENGTH))if token not in self._store:@@ -64,8 +62,8 @@ class UploadTokenStore:return token, expires_atraise RuntimeError("upload_token_store: failed to mint a unique token after 8 attempts")- def consume(self, token: str) -> Tuple[str, str, str]:- """Pop the token and validate it. Returns (account_id, user_id, agent_id) on success."""+ def consume(self, token: str) -> Tuple[str, str]:+ """Pop the token and validate it. Returns (account_id, user_id) on success."""if not token:raise UploadTokenError("missing upload token")info = self._store.pop(token, None)@@ -73,7 +71,7 @@ class UploadTokenStore:raise UploadTokenError("unknown or already-consumed upload token")if info.expires_at < time.time():raise UploadTokenError("upload token expired")- return info.account_id, info.user_id, info.agent_id+ return info.account_id, info.user_iddef peek(self, token: str) -> Optional[_TokenInfo]:"""Read a token without consuming. Test helper only."""diff --git a/openviking/service/core.py b/openviking/service/core.pyindex 90eaab648..c0debccdf 100644--- a/openviking/service/core.py+++ b/openviking/service/core.py@@ -69,9 +69,7 @@ class OpenVikingService:path=path,)self._config = config- self._user = user or UserIdentifier(- config.default_account, config.default_user, config.default_agent- )+ self._user = user or UserIdentifier(config.default_account, config.default_user)# Infrastructureself._agfs_client: Optional[Any] = Nonediff --git a/openviking/service/reindex_executor.py b/openviking/service/reindex_executor.pyindex 1ec209968..4a1988d05 100644--- a/openviking/service/reindex_executor.py+++ b/openviking/service/reindex_executor.py@@ -79,7 +79,6 @@ class ReindexExecutor:SUPPORTED_MODES_BY_TYPE = {"global_namespace": {"vectors_only", "semantic_and_vectors"},- "agent_namespace": {"vectors_only", "semantic_and_vectors"},"user_namespace": {"vectors_only", "semantic_and_vectors"},"skill_namespace": {"vectors_only", "semantic_and_vectors"},"resource": {"vectors_only", "semantic_and_vectors"},@@ -161,12 +160,14 @@ class ReindexExecutor:return "global_namespace"if parts == ("user",):return "user_namespace"- if parts == ("agent",):- return "agent_namespace"if classification.is_user_namespace_root:return "user_namespace"- if classification.is_agent_namespace_root:- return "agent_namespace"+ if parts[0] == "agent":+ raise OpenVikingError(+ "viking://agent is deprecated; use viking://user instead.",+ code="UNSUPPORTED_URI",+ details={"uri": uri},+ )if classification.is_memory:return "memory"if classification.is_skill_namespace:@@ -179,7 +180,7 @@ class ReindexExecutor:code="UNSUPPORTED_URI",details={"uri": uri},)- if parts[0] in {"resources", "user", "agent"}:+ if parts[0] in {"resources", "user"}:return "resource"raise OpenVikingError(f"Unsupported reindex URI: {uri}",@@ -371,12 +372,6 @@ class ReindexExecutor:mode=mode,run=run,)- elif object_type == "agent_namespace":- await self._reindex_agent_namespace(- uri=uri,- mode=mode,- run=run,- )elif object_type == "user_namespace":await self._reindex_user_namespace(uri=uri,@@ -537,7 +532,7 @@ class ReindexExecutor:recursive=True,account_id=ctx.account_id,user_id=ctx.user.user_id,- agent_id=ctx.user.agent_id,+ peer_id=ctx.user.user_id,role=ctx.role.value,skip_vectorization=True,)@@ -712,87 +707,6 @@ class ReindexExecutor:)return- memory_roots: list[str] = []- resource_directories: list[str] = []- resource_files: list[str] = []-- for entry in entries:- entry_uri = entry.get("uri")- if not entry_uri:- continue- classification = classify_uri(entry_uri)- if classification.is_memory:- if entry.get("isDir") and classification.is_memory_root:- memory_roots.append(entry_uri)- continue- if not self._is_resource_entry_for_namespace(entry_uri, target_root):- continue- if entry.get("isDir"):- resource_directories.append(entry_uri)- elif not self._is_hidden_meta_file(entry_uri):- resource_files.append(entry_uri)-- for memory_root in sorted(set(memory_roots)):- memory_mode = (- "semantic_and_vectors" if mode == "semantic_and_vectors" else "vectors_only"- )- await self._reindex_memory(- uri=memory_root,- mode=memory_mode,- run=run,- )-- if mode == "semantic_and_vectors":- (- resource_directories,- resource_files,- ) = await self._refresh_namespace_resource_semantics(- target_root=target_root,- directories=resource_directories,- files=resource_files,- run=run,- )-- await self._reindex_resource_vectors_from_entries(- root_uri=target_root,- directories=resource_directories,- files=resource_files,- counters=counters,- ctx=ctx,- )-- async def _reindex_agent_namespace(- self,- *,- uri: str,- mode: str,- run: _ReindexRunContext,- ) -> None:- counters = run.counters- ctx = run.ctx- normalized_uri = uri.rstrip("/")- target_root = normalized_uri if normalized_uri else uri- viking_fs = get_viking_fs()- try:- entries = await self._tree_all(viking_fs, target_root, show_all_hidden=True, ctx=ctx)- except Exception as exc:- raise NotFoundError(uri, "resource") from exc-- if target_root == "viking://agent":- agent_roots = [- entry.get("uri")- for entry in entries- if entry.get("isDir") and classify_uri(entry.get("uri", "")).is_agent_namespace_root- ]- if agent_roots:- for agent_root in sorted(set(agent_roots)):- await self._reindex_agent_namespace(- uri=agent_root,- mode=mode,- run=run,- )- return-memory_roots: list[str] = []skill_roots: list[str] = []resource_directories: list[str] = []@@ -874,7 +788,6 @@ class ReindexExecutor:raise NotFoundError(uri, "resource") from excuser_roots: list[str] = []- agent_roots: list[str] = []resource_directories: list[str] = []resource_files: list[str] = []@@ -882,18 +795,13 @@ class ReindexExecutor:entry_uri = entry.get("uri")if not entry_uri:continue- if entry_uri in {"viking://user", "viking://agent"}:+ if entry_uri == "viking://user":continueif entry_uri.startswith("viking://user/"):remainder = entry_uri[len("viking://user/") :]if entry.get("isDir") and remainder and "/" not in remainder:user_roots.append(entry_uri)continue- if entry_uri.startswith("viking://agent/"):- remainder = entry_uri[len("viking://agent/") :]- if entry.get("isDir") and remainder and "/" not in remainder:- agent_roots.append(entry_uri)- continueif entry_uri == "viking://session" or entry_uri.startswith("viking://session/"):continueif not self._is_global_resource_entry(entry_uri):@@ -910,13 +818,6 @@ class ReindexExecutor:run=run,)- for agent_root in sorted(set(agent_roots)):- await self._reindex_agent_namespace(- uri=agent_root,- mode=mode,- run=run,- )-if mode == "semantic_and_vectors":(resource_directories,diff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.pyindex 1f5c56c1c..a0a72f98c 100644--- a/openviking/service/resource_service.py+++ b/openviking/service/resource_service.py@@ -801,7 +801,6 @@ class ResourceService:account_id=ctx.account_id,user_id=ctx.user.user_id,role=ctx.role.value,- agent_id=ctx.user.agent_id,)if existing_task:if existing_task.is_active:@@ -815,7 +814,6 @@ class ResourceService:account_id=ctx.account_id,user_id=ctx.user.user_id,role=ctx.role.value,- agent_id=ctx.user.agent_id,path=path,to_uri=to_uri,parent_uri=parent_uri,@@ -835,7 +833,6 @@ class ResourceService:path=path,account_id=ctx.account_id,user_id=ctx.user.user_id,- agent_id=ctx.user.agent_id,original_role=ctx.role.value,to_uri=to_uri,parent_uri=parent_uri,@@ -864,7 +861,6 @@ class ResourceService:account_id=ctx.account_id,user_id=ctx.user.user_id,role=ctx.role.value,- agent_id=ctx.user.agent_id,)if existing_task:await watch_manager.update_task(@@ -872,7 +868,6 @@ class ResourceService:account_id=ctx.account_id,user_id=ctx.user.user_id,role=ctx.role.value,- agent_id=ctx.user.agent_id,is_active=False,)logger.info(diff --git a/openviking/service/search_service.py b/openviking/service/search_service.pyindex f57debb03..f192e12d3 100644--- a/openviking/service/search_service.py+++ b/openviking/service/search_service.py@@ -46,6 +46,7 @@ class SearchService:query: str,ctx: RequestContext,target_uri: Union[str, List[str]] = "",+ peer_id: Optional[str] = None,session: Optional["Session"] = None,limit: int = 10,score_threshold: Optional[float] = None,@@ -78,6 +79,7 @@ class SearchService:query=query,ctx=ctx,target_uri=target_uri,+ peer_id=peer_id,session_info=session_info,limit=limit,score_threshold=score_threshold,@@ -91,6 +93,7 @@ class SearchService:query: str,ctx: RequestContext,target_uri: Union[str, List[str]] = "",+ peer_id: Optional[str] = None,limit: int = 10,score_threshold: Optional[float] = None,filter: Optional[Dict] = None,@@ -116,6 +119,7 @@ class SearchService:query=query,ctx=ctx,target_uri=target_uri,+ peer_id=peer_id,limit=limit,score_threshold=score_threshold,filter=filter,diff --git a/openviking/service/session_service.py b/openviking/service/session_service.pyindex 3bb1218cf..0cf5fc38b 100644--- a/openviking/service/session_service.py+++ b/openviking/service/session_service.py@@ -13,6 +13,7 @@ from openviking.server.config import ToolOutputExternalizationConfigfrom openviking.server.identity import RequestContext, Rolefrom openviking.service.task_tracker import get_task_trackerfrom openviking.session import Session+from openviking.session.memory_policy import MemoryPolicyfrom openviking.storage import VikingDBManagerfrom openviking.storage.viking_fs import VikingFSfrom openviking_cli.exceptions import AlreadyExistsError, NotFoundError, NotInitializedError@@ -109,13 +110,28 @@ class SessionService:tool_output_externalization_config=self._tool_output_externalization_config,)- async def create(self, ctx: RequestContext, session_id: Optional[str] = None) -> Session:+ @staticmethod+ def _assert_session_owner(session: Session, ctx: RequestContext) -> None:+ meta = session.meta+ if (+ meta.created_by_account_id != ctx.account_id+ or meta.created_by_user_id != ctx.user.user_id+ ):+ raise NotFoundError(session.session_id, "session")++ async def create(+ self,+ ctx: RequestContext,+ session_id: Optional[str] = None,+ memory_policy: Optional[Dict[str, Any]] = None,+ ) -> Session:"""Create a session and persist its root path.Args:ctx: Request contextsession_id: Optional session ID. If provided, creates a session with the given ID.If None, creates a new session with auto-generated ID.+ memory_policy: Optional default extraction policy for future commits.Raises:AlreadyExistsError: If a session with the given ID already exists@@ -127,6 +143,9 @@ class SessionService:if await existing.exists():raise AlreadyExistsError(f"Session '{session_id}' already exists")session = self.session(ctx, session_id)+ if memory_policy is not None:+ policy = MemoryPolicy.from_dict(memory_policy)+ session.meta.memory_policy = policy.to_dict()await session.ensure_exists()self._record_lifecycle_metric("create", "ok")return session@@ -152,6 +171,7 @@ class SessionService:raise NotFoundError(session_id, "session")await session.ensure_exists()await session.load()+ self._assert_session_owner(session, ctx)self._record_lifecycle_metric("get", "ok")return sessionexcept Exception:@@ -174,6 +194,12 @@ class SessionService:name = entry.get("name", "")if name in [".", ".."]:continue+ try:+ session = self.session(ctx, name)+ await session.load()+ self._assert_session_owner(session, ctx)+ except Exception:+ continuesessions.append({"session_id": name,@@ -218,6 +244,7 @@ class SessionService:session_id: str,ctx: RequestContext,keep_recent_count: int = 0,+ memory_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Commit a session (archive messages and extract memories).@@ -230,13 +257,19 @@ class SessionService:Returns:Commit result"""- return await self.commit_async(session_id, ctx, keep_recent_count=keep_recent_count)+ return await self.commit_async(+ session_id,+ ctx,+ keep_recent_count=keep_recent_count,+ memory_policy=memory_policy,+ )async def commit_async(self,session_id: str,ctx: RequestContext,keep_recent_count: int = 0,+ memory_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Async commit a session.@@ -254,7 +287,10 @@ class SessionService:"""self._ensure_initialized()session = await self.get(session_id, ctx)- result = await session.commit_async(keep_recent_count=keep_recent_count)+ result = await session.commit_async(+ keep_recent_count=keep_recent_count,+ memory_policy=memory_policy,+ )self._record_lifecycle_metric("commit", "ok" if result.get("status") else "error")self._record_archive_metric("ok" if result.get("archived") else "skip")return result@@ -279,7 +315,7 @@ class SessionService:"""self._ensure_initialized()if not self._session_compressor:- raise NotInitializedError("SessionCompressor")+ raise NotInitializedError("SessionCompressorV2")session = await self.get(session_id, ctx)session_uri = canonical_session_uri(session_id)diff --git a/openviking/session/compressor_v2.py b/openviking/session/compressor_v2.pyindex 88b8ebc27..e2ad593c7 100644--- a/openviking/session/compressor_v2.py+++ b/openviking/session/compressor_v2.py@@ -13,16 +13,16 @@ from datetime import datetimefrom typing import Any, Awaitable, Callable, Dict, List, Optionalfrom openviking.core.context import Context-from openviking.core.namespace import (- to_agent_space,- to_user_space,-)from openviking.message import Messagefrom openviking.server.identity import RequestContextfrom openviking.session.memory import ExtractLoop, MemoryUpdaterfrom openviking.session.memory.dataclass import ResolvedOperations, StoredLinkfrom openviking.session.memory.memory_isolation_handler import MemoryIsolationHandler-from openviking.session.memory.memory_updater import ExtractContext, MemoryUpdateResult, write_stored_links+from openviking.session.memory.memory_updater import (+ ExtractContext,+ MemoryUpdateResult,+ write_stored_links,+)from openviking.session.memory.utils.json_parser import JsonUtilsfrom openviking.session.memory.utils.memory_file_utils import MemoryFileUtilsfrom openviking.session.memory.utils.uri import render_template@@ -84,13 +84,11 @@ def _render_memory_schema_locks(ctx: RequestContext,viking_fs: VikingFS,user_ids: list[str],- agent_ids: list[str],+ isolation_handler: Optional[MemoryIsolationHandler] = None,) -> tuple[list[str], list[str]]:exact_paths: list[str] = []tree_paths: list[str] = []- policy = ctx.namespace_policyuser_ids = user_ids or ["default"]- agent_ids = agent_ids or ["default"]for schema in schemas:directory_template = getattr(schema, "directory", "") or ""@@ -98,20 +96,26 @@ def _render_memory_schema_locks(continuefilename_template = getattr(schema, "filename_template", "") or ""- for user_id in user_ids:- for agent_id in agent_ids:- template_vars = {- "user_space": to_user_space(policy, user_id, agent_id),- "agent_space": to_agent_space(policy, user_id, agent_id),- }- directory_uri = render_template(directory_template, template_vars)+ if isolation_handler:+ for directory_uri in isolation_handler.render_schema_directories(schema):if _filename_has_variables(schema) or not filename_template:_append_unique(tree_paths, viking_fs._uri_to_path(directory_uri, ctx))continue-- filename = render_template(filename_template, template_vars)+ filename = render_template(filename_template, {}, None)file_uri = f"{directory_uri.rstrip('/')}/{filename.lstrip('/')}"_append_unique(exact_paths, viking_fs._uri_to_path(file_uri, ctx))+ continue++ for user_id in user_ids:+ template_vars = {"user_space": user_id}+ directory_uri = render_template(directory_template, template_vars)+ if _filename_has_variables(schema) or not filename_template:+ _append_unique(tree_paths, viking_fs._uri_to_path(directory_uri, ctx))+ continue++ filename = render_template(filename_template, template_vars)+ file_uri = f"{directory_uri.rstrip('/')}/{filename.lstrip('/')}"+ _append_unique(exact_paths, viking_fs._uri_to_path(file_uri, ctx))return exact_paths, tree_paths@@ -223,6 +227,9 @@ class SessionCompressorV2:strict_extract_errors: bool = False,latest_archive_overview: str = "",archive_uri: Optional[str] = None,+ allowed_memory_types: Optional[set[str]] = None,+ allow_self_memory: bool = True,+ allowed_peer_ids: Optional[set[str]] = None,) -> List[Context]:"""Extract long-term memories from messages using v2 templating system.@@ -237,6 +244,9 @@ class SessionCompressorV2:strict_extract_errors: If True, raise exceptions on extraction errors.latest_archive_overview: Overview of latest archive for context.archive_uri: Archive URI for writing memory_diff.json.+ allowed_memory_types: Optional set of memory types this phase may update.+ allow_self_memory: Whether operations without peer_id may write self memory.+ allowed_peer_ids: Peer IDs that may be written by this extraction."""if not messages:@@ -254,7 +264,8 @@ class SessionCompressorV2:from openviking.session.memory.memory_type_registry import create_default_registryregistry = create_default_registry()- await registry.initialize_memory_files(ctx)+ if allow_self_memory:+ await registry.initialize_memory_files(ctx)# Initialize telemetry counters before extraction.telemetry = get_current_telemetry()@@ -287,7 +298,13 @@ class SessionCompressorV2:extract_context = ExtractContext(messages)# Create MemoryIsolationHandler- isolation_handler = MemoryIsolationHandler(ctx, extract_context)+ isolation_handler = MemoryIsolationHandler(+ ctx,+ extract_context,+ allowed_memory_types=allowed_memory_types,+ allow_self=allow_self_memory,+ allowed_peer_ids=allowed_peer_ids,+ )isolation_handler.prepare_messages()# 获取所有记忆 schema 目录并加锁(仅在有锁管理器时)orchestrator = self._get_or_create_react(@@ -305,7 +322,7 @@ class SessionCompressorV2:ctx=ctx,viking_fs=viking_fs,user_ids=read_scope.user_ids,- agent_ids=read_scope.agent_ids,+ isolation_handler=isolation_handler,)logger.debug(f"Memory schema locks: exact={exact_lock_paths}, tree={tree_lock_dirs}"@@ -449,13 +466,23 @@ class SessionCompressorV2:strict_extract_errors: bool = False,latest_archive_overview: str = "",archive_uri: str = "",+ allowed_memory_types: Optional[set[str]] = None,+ include_session_skills: Optional[bool] = None,) -> Dict[str, List[Any]]:"""Two-phase agent-scope extraction for trajectories, experiences, and session skills."""config = get_openviking_config()- include_trajectories = bool(getattr(config.memory, "agent_memory_enabled", False))- include_session_skills = bool(- getattr(config.memory, "session_skill_extraction_enabled", False)+ allowed_agent_types = (+ {"trajectories", "experiences"}+ if allowed_memory_types is None+ else set(allowed_memory_types))+ agent_memory_enabled = bool(getattr(config.memory, "agent_memory_enabled", False))+ include_trajectories = agent_memory_enabled and "trajectories" in allowed_agent_types+ include_experiences = agent_memory_enabled and "experiences" in allowed_agent_types+ if include_session_skills is None:+ include_session_skills = bool(+ getattr(config.memory, "session_skill_extraction_enabled", False)+ )empty_result: Dict[str, List[Any]] = {"contexts": [], "session_skills": []}if not (include_trajectories or include_session_skills):return empty_result@@ -485,6 +512,7 @@ class SessionCompressorV2:ctx=ctx,strict_extract_errors=strict_extract_errors,phase_label="trajectory",+ allowed_memory_types=allowed_agent_types,)if traj_result is None:return empty_result@@ -501,7 +529,7 @@ class SessionCompressorV2:# once per duplicate and generate near-identical experiences.written_trajectory_uris = list(dict.fromkeys(written_trajectory_uris))- if not include_trajectories or not written_trajectory_uris:+ if not include_trajectories or not include_experiences or not written_trajectory_uris:if not written_trajectory_uris:tracer.info("No trajectories extracted; skipping experience phase")return {@@ -559,6 +587,7 @@ class SessionCompressorV2:strict_extract_errors=strict_extract_errors,phase_label=f"experience({traj_uri})",post_apply=_append_sources_before_unlock,+ allowed_memory_types=allowed_agent_types,)if exp_result is None:fallback_uris = await self._single_existing_experience_uris(@@ -655,6 +684,7 @@ class SessionCompressorV2:strict_extract_errors: bool,phase_label: str,post_apply: Optional[ExtractPostApply] = None,+ allowed_memory_types: Optional[set[str]] = None,):"""Run one ExtractLoop phase with its own lock scope, then apply operations.@@ -672,9 +702,13 @@ class SessionCompressorV2:viking_fs = get_viking_fs()# Build isolation_handler BEFORE creating the orchestrator so that- # ExtractLoop.resolve_operations() can call fill_role_ids() correctly.+ # ExtractLoop.resolve_operations() can fill identity fields correctly.extract_context = ExtractContext(messages)- isolation_handler = MemoryIsolationHandler(ctx, extract_context)+ isolation_handler = MemoryIsolationHandler(+ ctx,+ extract_context,+ allowed_memory_types=allowed_memory_types,+ )isolation_handler.prepare_messages()# Inject context into provider (mirrors extract_long_term_memories pattern)@@ -705,13 +739,12 @@ class SessionCompressorV2:if getattr(schema, "memory_type", None) != SESSION_SKILL_MEMORY_TYPE]user_ids = [ctx.user.user_id] if ctx and ctx.user else ["default"]- agent_ids = [ctx.user.agent_id] if ctx and ctx.user else ["default"]exact_lock_paths, tree_lock_dirs = _render_memory_schema_locks(schemas=schemas,ctx=ctx,viking_fs=viking_fs,user_ids=user_ids,- agent_ids=agent_ids,+ isolation_handler=isolation_handler,)retry_interval = config.memory.v2_lock_retry_interval_seconds@@ -974,6 +1007,7 @@ class SessionCompressorV2:viking_fs,) -> None:from datetime import timezone+from openviking.session.memory.merge_op.link_merge import merge_linksraw = await viking_fs.read_file(exp_uri, ctx=ctx) or ""@@ -983,7 +1017,9 @@ class SessionCompressorV2:# write_stored_links writes it to exp.links (forward) and traj.backlinks (reverse) automatically.now = datetime.now(timezone.utc).isoformat()links = [- StoredLink(from_uri=exp_uri, to_uri=t, link_type="derived_from", weight=1.0, created_at=now)+ StoredLink(+ from_uri=exp_uri, to_uri=t, link_type="derived_from", weight=1.0, created_at=now+ )for t in traj_uris]@@ -993,7 +1029,9 @@ class SessionCompressorV2:if links_changed:await viking_fs.write_file(exp_uri, MemoryFileUtils.write(mf), ctx=ctx)- tracer.info(f"[agent_link] wrote exp→traj links -> {exp_uri} (traj_count={len(traj_uris)})")+ tracer.info(+ f"[agent_link] wrote exp→traj links -> {exp_uri} (traj_count={len(traj_uris)})"+ )else:tracer.info(f"[agent_link] links already present, skip: {exp_uri}")diff --git a/openviking/session/memory/agent_experience_context_provider.py b/openviking/session/memory/agent_experience_context_provider.pyindex 12d7492c0..b8ac9386c 100644--- a/openviking/session/memory/agent_experience_context_provider.py+++ b/openviking/session/memory/agent_experience_context_provider.py@@ -12,7 +12,6 @@ source_trajectories as grounding material.from typing import Any, Dict, List, Optional-from openviking.core.namespace import to_agent_space, to_user_spacefrom openviking.server.identity import RequestContextfrom openviking.session.memory.dataclass import MemoryFilefrom openviking.session.memory.session_extract_context_provider import (@@ -102,18 +101,13 @@ All memory content must be written in {output_language}.return ""if ctx and ctx.user:- user_space = to_user_space(ctx.namespace_policy, ctx.user.user_id, ctx.user.agent_id)- agent_space = to_agent_space(ctx.namespace_policy, ctx.user.user_id, ctx.user.agent_id)+ user_space = ctx.user.user_idelse:user_space = "default"- agent_space = "default"return TemplateUtils.render(schema.directory,- {- "user_space": user_space,- "agent_space": agent_space,- },+ {"user_space": user_space},)async def _load_source_trajectories(diff --git a/openviking/session/memory/extract_loop.py b/openviking/session/memory/extract_loop.pyindex 4d4187eef..5e6c89bd8 100644--- a/openviking/session/memory/extract_loop.py+++ b/openviking/session/memory/extract_loop.py@@ -322,7 +322,7 @@ The final output of the model must strictly follow the JSON Schema format shownfor item in items:item_dict = dict(item)item_dict["memory_type"] = memory_type- self._isolation_handler.fill_role_ids(item_dict, role_scope=role_scope)+ self._isolation_handler.fill_identity_fields(item_dict, role_scope=role_scope)page_id = item_dict.pop("page_id", None)resolved_op = ResolvedOperation(diff --git a/openviking/session/memory/memory_isolation_handler.py b/openviking/session/memory/memory_isolation_handler.pyindex cea9e65a0..68a75a596 100644--- a/openviking/session/memory/memory_isolation_handler.py+++ b/openviking/session/memory/memory_isolation_handler.py@@ -1,141 +1,141 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""-Memory Isolation Handler - 处理记忆的隔离机制+"""Memory isolation helpers for resolving session memory write targets."""-根据 account namespace policy 和 session 参与者列表,-计算记忆的写入目录并校验 role_id。-"""--from dataclasses import dataclass+from dataclasses import dataclass, fieldfrom typing import Any, Dict, List, Optional, Set-from openviking.core.namespace import to_agent_space, to_user_space+from openviking.core.peer_id import safe_peer_idfrom openviking.server.identity import RequestContextfrom openviking.session.memory.dataclass import MemoryTypeSchema, ResolvedOperationfrom openviking.session.memory.memory_updater import ExtractContext-from openviking.session.memory.utils.uri import generate_uri+from openviking.session.memory.utils.uri import generate_uri, render_templatefrom openviking_cli.utils import get_logger-from openviking_cli.utils.config import get_openviking_configlogger = get_logger(__name__)@dataclassclass RoleScope:- """Role 作用范围 - 从 messages 推断的可访问范围"""+ """Participant scope inferred from session messages."""++ user_ids: List[str]+ peer_ids: List[str] = field(default_factory=list)- user_ids: List[str] # 参与者中的 user_id 列表- agent_ids: List[str] # 参与者中的 agent_id 列表++def peer_user_space(user_space: str, peer_id: str) -> str:+ """Return the user-space fragment for memory about a stable peer."""+ return f"{user_space}/peers/{peer_id}"class MemoryIsolationHandler:"""Memory isolation handler."""- def __init__(self, ctx: RequestContext, extract_context: Any):+ def __init__(+ self,+ ctx: RequestContext,+ extract_context: Any,+ allowed_memory_types: Optional[Set[str]] = None,+ allow_self: bool = True,+ allowed_peer_ids: Optional[Set[str]] = None,+ ):self.ctx = ctxself._extract_context = extract_context- config = get_openviking_config()- self.role_id_memory_isolation_enabled = (- config.memory.role_id_memory_isolation_enabled if config.memory else False+ self.allowed_memory_types = (+ {str(item) for item in allowed_memory_types}+ if allowed_memory_types is not None+ else None)+ peer_ids = {safe_peer_id(item) for item in allowed_peer_ids or set()}+ peer_ids = {item for item in peer_ids if item}+ self.allow_self = bool(allow_self)+ self.allowed_peer_ids = peer_ids+ self.allow_peer = bool(peer_ids)def prepare_messages(self) -> None:- """开关关闭时,规范化 messages 中的 role_id,缺失时回退到登录身份。"""- if self.role_id_memory_isolation_enabled:- return- messages = self._extract_context.messages if self._extract_context else []- for msg in messages:- msg.role_id = None+ """No-op hook kept for the extraction pipeline."""+ returndef get_read_scope(self) -> RoleScope:user_ids = set()- agent_ids = set()-- # 先从 messages 中提取 role_id- messages = self._extract_context.messages if self._extract_context else []- for msg in messages:- role = msg.role- role_id = msg.role_id- if not role_id:- continue- if role == "user":- user_ids.add(role_id)- elif role == "assistant":- agent_ids.add(role_id)-- # 只有当 messages 中没有提取到 user_ids/agent_ids 时,才添加 ctx 中的 userid/agentid+ peer_ids = set()+if self.ctx and self.ctx.user:user_id = self.ctx.user.user_id- agent_id = self.ctx.user.agent_id- if not user_ids and user_id:+ if user_id:user_ids.add(user_id)- if not agent_ids and agent_id:- agent_ids.add(agent_id)++ if self.allow_peer:+ peer_ids.update(self.allowed_peer_ids)return RoleScope(- user_ids=list(user_ids),- agent_ids=list(agent_ids),+ user_ids=sorted(user_ids),+ peer_ids=sorted(peer_ids),)- def fill_role_ids(self, item_dict: Dict[str, Any], role_scope: RoleScope) -> None:- user_ids = set()- agent_ids = set()-- def add_role_id(role_ids, role_id, scope_ids):- if role_id is None:- return- if role_id not in scope_ids:- return- role_ids.add(role_id)-- def add_user_id(user_id):- add_role_id(user_ids, user_id, role_scope.user_ids)-- def add_agent_id(agent_id):- add_role_id(agent_ids, agent_id, role_scope.agent_ids)-- def check_set_default():- if not user_ids:- user_ids.add(role_scope.user_ids[0])- if not agent_ids:- agent_ids.add(role_scope.agent_ids[0])-- if item_dict.get("ranges") is None:- add_user_id(item_dict.get("user_id"))- add_agent_id(item_dict.get("agent_id"))- check_set_default()- item_dict["user_id"] = list(user_ids)[0]- item_dict["agent_id"] = list(agent_ids)[0]+ def fill_identity_fields(self, item_dict: Dict[str, Any], role_scope: RoleScope) -> None:+ del role_scope+ if self.ctx and self.ctx.user and self.ctx.user.user_id:+ item_dict["user_id"] = self.ctx.user.user_id+ item_dict.pop("user_ids", None)+ peer_id = safe_peer_id(item_dict.get("peer_id"))+ if peer_id:+ item_dict["peer_id"] = peer_idelse:- # 使用 ExtractContext 的方法解析 ranges- msg_range = self._extract_context.read_message_ranges(item_dict.get("ranges"))- # elements 是 List[List[Message]] - 遍历所有消息组- for msg_group in msg_range.elements:- for msg in msg_group:- if msg.role == "user":- add_user_id(msg.role_id)- elif msg.role == "assistant":- add_agent_id(msg.role_id)- check_set_default()- item_dict["user_ids"] = list(user_ids)- item_dict["agent_ids"] = list(agent_ids)-- def _extract_role_ids_from_messages_range(- self, ranges: Optional[str], user_ids: Set[str], agent_ids: Set[str]- ):- """- 从 events 的 ranges 字段提取涉及的 role_id。+ item_dict.pop("peer_id", None)++ def allows_schema(self, memory_type_schema: MemoryTypeSchema) -> bool:+ memory_type = getattr(memory_type_schema, "memory_type", "")+ if self.allowed_memory_types is not None and memory_type not in self.allowed_memory_types:+ return False+ return True++ def _can_write_peer(self, peer_id: str) -> bool:+ return self.allow_peer and peer_id in self.allowed_peer_ids++ def render_schema_directories(self, memory_type_schema: MemoryTypeSchema) -> List[str]:+ user_id = self.ctx.user.user_id if self.ctx and self.ctx.user else "default"+ user_space = user_id+ user_spaces: List[str] = []+ if self.allow_self:+ user_spaces.append(user_space)+ if self.allow_peer:+ for peer_id in sorted(self.allowed_peer_ids):+ user_spaces.append(peer_user_space(user_space, peer_id))++ directories = []+ for target_user_space in dict.fromkeys(user_spaces):+ directories.append(+ render_template(+ memory_type_schema.directory,+ {"user_space": target_user_space},+ self._extract_context,+ )+ )+ return directories- 解析 ranges 格式,提取范围内的所有 user 角色的消息参与者。- """+ def _range_targets(self, ranges: Any) -> tuple[bool, List[str]]:if not ranges or not self._extract_context:- return-- messages = self._extract_context.messages- if not messages:- return []+ return False, []+ try:+ msg_range = self._extract_context.read_message_ranges(str(ranges))+ except Exception:+ logger.warning("Failed to parse memory ranges for peer routing: %s", ranges)+ return False, []++ include_self = False+ peer_ids = set()+ for msg_group in getattr(msg_range, "elements", []) or []:+ for msg in msg_group:+ raw_peer_id = getattr(msg, "peer_id", None)+ peer_id = safe_peer_id(raw_peer_id)+ if peer_id:+ if self._can_write_peer(peer_id):+ peer_ids.add(peer_id)+ elif self.allow_self:+ include_self = True+ return include_self, sorted(peer_ids)def calculate_memory_uris(self,@@ -143,27 +143,61 @@ class MemoryIsolationHandler:operation: ResolvedOperation,extract_context: ExtractContext,):- policy = self.ctx.namespace_policy-- user_ids = operation.memory_fields.get("user_ids") or [- operation.memory_fields.get("user_id")- ]- agent_ids = operation.memory_fields.get("agent_ids") or [- operation.memory_fields.get("agent_id")- ]+ if not self.allows_schema(memory_type_schema):+ return []++ if not self.ctx or not self.ctx.user:+ return []++ user_id = self.ctx.user.user_id+ operation.memory_fields["user_id"] = user_id++ peer_ids_to_write: List[str] = []+ include_self = False++ if operation.memory_fields.get("ranges") is not None:+ include_self, peer_ids_to_write = self._range_targets(+ operation.memory_fields.get("ranges"),+ )+ operation.memory_fields.pop("peer_id", None)+ else:+ raw_peer_id = operation.memory_fields.get("peer_id")+ peer_id = safe_peer_id(raw_peer_id)+ if raw_peer_id and not peer_id:+ return []+ if peer_id:+ if not self._can_write_peer(peer_id):+ return []+ peer_ids_to_write = [peer_id]+ operation.memory_fields["peer_id"] = peer_id+ elif self.allow_self:+ include_self = True+ operation.memory_fields.pop("peer_id", None)++ if not include_self and not peer_ids_to_write:+ return []+# 文件uris = set()- for user_id in user_ids:- for agent_id in agent_ids:- user_space = to_user_space(policy, user_id, agent_id)- agent_space = to_agent_space(policy, user_id, agent_id)- uri = generate_uri(+ user_space = user_id+ if include_self:+ uris.add(+ generate_uri(memory_type=memory_type_schema,fields=operation.memory_fields,user_space=user_space,- agent_space=agent_space,extract_context=extract_context,)- uris.add(uri)+ )+ for peer_id in peer_ids_to_write:+ target_user_space = peer_user_space(user_space, peer_id)+ uris.add(+ generate_uri(+ memory_type=memory_type_schema,+ fields=operation.memory_fields,+ user_space=target_user_space,+ extract_context=extract_context,+ )+ )return list(uris)diff --git a/openviking/session/memory/memory_type_registry.py b/openviking/session/memory/memory_type_registry.pyindex 0f0b5542f..970570bf7 100644--- a/openviking/session/memory/memory_type_registry.py+++ b/openviking/session/memory/memory_type_registry.py@@ -9,7 +9,7 @@ from typing import Any, Dict, List, Optionalimport yaml-from openviking.core.namespace import agent_space_fragment, user_space_fragment+from openviking.core.namespace import user_space_fragmentfrom openviking.prompts.manager import PromptManagerfrom openviking.session.memory.dataclass import MemoryField, MemoryTypeSchemafrom openviking.session.memory.merge_op import MergeOp@@ -132,12 +132,11 @@ class MemoryTypeRegistry:return list(self._types.keys())return [mt.memory_type for mt in self._types.values() if mt.enabled]- def list_search_uris(self, user_space: str, agent_space: str) -> List[str]:+ def list_search_uris(self, user_space: str) -> List[str]:"""List all directory URIs for search scope.Args:user_space: User space name- agent_space: Agent space nameReturns:List of directory URIs from enabled schemas@@ -147,10 +146,7 @@ class MemoryTypeRegistry:if schema.directory:dir_path = TemplateUtils.render(schema.directory,- {- "user_space": user_space,- "agent_space": agent_space,- },+ {"user_space": user_space},)uris.append(dir_path)return uris@@ -243,17 +239,16 @@ class MemoryTypeRegistry:Skip templates like entities.yaml where filename requires external parameters.Args:- ctx: Request context (must have user with user_space_name and agent_space_name)+ ctx: Request context."""from openviking.storage.viking_fs import get_viking_fslogger = get_logger(__name__)user_space = user_space_fragment(ctx) if ctx and ctx.user else "default"- agent_space = agent_space_fragment(ctx) if ctx and ctx.user else "default"logger.info(- f"[MemoryTypeRegistry] Starting memory files initialization for user={user_space}, agent={agent_space}"+ f"[MemoryTypeRegistry] Starting memory files initialization for user={user_space}")viking_fs = get_viking_fs()@@ -278,17 +273,11 @@ class MemoryTypeRegistry:try:directory = TemplateUtils.render(schema.directory,- {- "user_space": user_space,- "agent_space": agent_space,- },+ {"user_space": user_space},)filename = TemplateUtils.render(schema.filename_template,- {- "user_space": user_space,- "agent_space": agent_space,- },+ {"user_space": user_space},)except Exception:continuediff --git a/openviking/session/memory/memory_updater.py b/openviking/session/memory/memory_updater.pyindex e901d20f5..cedacd706 100644--- a/openviking/session/memory/memory_updater.py+++ b/openviking/session/memory/memory_updater.py@@ -240,8 +240,8 @@ class MessageRange:result = []for i, msg_group in enumerate(self.elements):for msg in msg_group:- role_id = msg.role_id if msg.role_id else msg.role- result.append(f"[{role_id}]: {msg.content}")+ speaker = msg.peer_id or msg.role+ result.append(f"[{speaker}]: {msg.content}")# Add "..." separator between non-contiguous message groupsif i < len(self.elements) - 1:result.append("...")diff --git a/openviking/session/memory/schema_model_generator.py b/openviking/session/memory/schema_model_generator.pyindex f88dd775f..a2baeb68d 100644--- a/openviking/session/memory/schema_model_generator.py+++ b/openviking/session/memory/schema_model_generator.py@@ -78,18 +78,22 @@ class SchemaModelGenerator:Args:memory_type: The memory type schema- role_scope: Role scope to determine if user_id/agent_id fields are needed+ role_scope: Role scope to determine if user_id fields are neededReturns:Dynamically created flat Pydantic model class"""# Determine cache key based on role_scope+ has_peer_scope = bool(role_scope and role_scope.peer_ids)if role_scope and len(role_scope.user_ids) > 1:cache_key = f"{memory_type.memory_type}_multi_user"model_name = f"{to_pascal_case(memory_type.memory_type)}DataMultiUser"else:cache_key = memory_type.memory_typemodel_name = f"{to_pascal_case(memory_type.memory_type)}Data"+ if has_peer_scope:+ cache_key = f"{cache_key}_peer"+ model_name = f"{model_name}Peer"# Check cache for both single and multi-user casesif cache_key in self._flat_data_models:@@ -98,7 +102,7 @@ class SchemaModelGenerator:# Build field definitions - no memory_type field neededfield_definitions: Dict[str, Tuple[Type[Any], Any]] = {}- # Add user_id and agent_id fields when multiple users are in scope+ # Add user_id when multiple users are in scope# Skip if schema has "ranges" field (like events) - these are message-based and don't need user isolationhas_ranges = any(field.name == "ranges" for field in memory_type.fields)if role_scope and len(role_scope.user_ids) > 1 and not has_ranges:@@ -106,10 +110,18 @@ class SchemaModelGenerator:str,Field(..., description="User ID to distinguish which user's memory to write"),)- if role_scope and len(role_scope.agent_ids) > 1 and not has_ranges:- field_definitions["agent_id"] = (- str,- Field(..., description="Agent ID to distinguish which agent's memory to write"),+ if has_peer_scope and not has_ranges:+ peer_values = ", ".join(role_scope.peer_ids)+ field_definitions["peer_id"] = (+ Optional[str],+ Field(+ None,+ description=(+ "Stable peer identity to write peer memory for. "+ "Use only when the memory describes a peer instead of the current user. "+ f"Available peer_id values in this session: {peer_values}"+ ),+ ),)field_definitions["page_id"] = (@@ -246,7 +258,7 @@ class SchemaModelGenerator:for mt in enabled_memory_types:flat_model = self.create_flat_data_model(mt, role_scope)- # Always use List to support multiple users' memories (e.g., identity for different user_id/agent_id)+ # Always use List to support multiple users' memories.field_definitions[mt.memory_type] = (List[flat_model], # type: ignoreField(@@ -351,3 +363,111 @@ class SchemaModelGenerator:"""memory_model = self.create_discriminated_union_model()return memory_model.model_json_schema()+++class SchemaPromptGenerator:+ """+ Prompt generator that incorporates schema information into LLM prompts.++ Generates descriptive text about memory types and their fields+ based on the YAML schema definitions.+ """++ def __init__(+ self,+ schemas: List[MemoryTypeSchema],+ template_context: Optional[Dict[str, Any]] = None,+ ):+ self.schemas = schemas+ self._template_context = dict(template_context or {})++ def _render_description(self, description: str) -> str:+ if not description:+ return description+ return TemplateUtils.render(description, self._template_context)++ def generate_type_descriptions(self) -> str:+ """+ Generate descriptions of all memory types.++ Returns:+ Formatted string with all memory type descriptions+ """+ lines = ["## Available Memory Types"]++ for mt in self.schemas:+ lines.append(f"\n### {mt.memory_type}")+ lines.append(f"{self._render_description(mt.description)}")++ # Add URI format information+ if mt.directory or mt.filename_template:+ lines.append("\n**URI Format:**")+ if mt.directory and mt.filename_template:+ lines.append(f"- URI: `{mt.directory}/{mt.filename_template}`")+ elif mt.directory:+ lines.append(f"- Directory: `{mt.directory}`")+ elif mt.filename_template:+ lines.append(f"- Filename: `{mt.filename_template}`")++ # Add variable substitution info+ lines.append("\n**Variable Substitution:**")+ lines.append("- `{{ user_space }}` → 'default'")+ if mt.fields:+ for field in mt.fields:+ lines.append(f"- `{{ {field.name} }}` → use value from fields")++ if mt.fields:+ lines.append("\n**Fields:**")+ for field in mt.fields:+ lines.append(+ f"- `{field.name}` ({field.field_type.value}): {self._render_description(field.description)}"+ )++ return "\n".join(lines)++ def generate_field_descriptions(self, memory_type: str) -> Optional[str]:+ """+ Generate descriptions for a specific memory type's fields.++ Args:+ memory_type: The memory type to describe++ Returns:+ Formatted string with field descriptions, or None if not found+ """+ mt = next((s for s in self.schemas if s.memory_type == memory_type), None)+ if not mt:+ return None++ lines = [f"### {mt.memory_type} Fields"]+ for field in mt.fields:+ lines.append(f"- `{field.name}`: {self._render_description(field.description)}")++ return "\n".join(lines)++ def get_full_prompt_context(self) -> Dict[str, Any]:+ """+ Get the full prompt context including all schema information.++ Returns:+ Dictionary with all prompt context components+ """+ return {+ "type_descriptions": self.generate_type_descriptions(),+ "memory_types": [+ {+ "memory_type": mt.memory_type,+ "description": mt.description,+ "fields": [+ {+ "name": f.name,+ "type": f.field_type.value,+ "description": f.description,+ "merge_op": f.merge_op.value,+ }+ for f in mt.fields+ ],+ }+ for mt in self.schemas+ ],+ }diff --git a/openviking/session/memory/session_extract_context_provider.py b/openviking/session/memory/session_extract_context_provider.pyindex 49cddb1c5..643cca82d 100644--- a/openviking/session/memory/session_extract_context_provider.py+++ b/openviking/session/memory/session_extract_context_provider.py@@ -10,13 +10,16 @@ import jsonimport osfrom typing import TYPE_CHECKING, Any, Dict, List, Optional-from openviking.core.namespace import to_agent_space, to_user_spacefrom openviking.message.part import ToolPartfrom openviking.prompts.manager import PromptManagerfrom openviking.server.identity import RequestContext, ToolContextfrom openviking.session.memory.core import ExtractContextProviderfrom openviking.session.memory.dataclass import MemoryFile-from openviking.session.memory.memory_isolation_handler import MemoryIsolationHandler, RoleScope+from openviking.session.memory.memory_isolation_handler import (+ MemoryIsolationHandler,+ RoleScope,+ peer_user_space,+)from openviking.session.memory.memory_type_registry import (MemoryTypeRegistry,resolve_memory_templates_dir,@@ -138,6 +141,15 @@ All memory content MUST be written in {output_language}.## URI HandlingThe system automatically generates URIs based on memory_type and fields. Just provide correct memory_type and fields.++## Self and Peer Memory+When a memory item describes the current user, omit peer_id.+When a memory item describes a peer, set peer_id to one of the peer_id values allowed by+the output schema. Do not invent peer_id values.+For events with ranges, the system derives self/peer targets from the message range.+Message role is authoritative: user-role content is the source for profile/preferences/entities/events,+and assistant-role content is the source for cases/patterns/tools/skills. Do not infer ownership+from neighboring messages."""return goal@@ -219,9 +231,9 @@ After exploring, analyze the conversation and output ALL memory write/edit/deletreturn "\n".join(formatted_parts) if formatted_parts else msg.contentdef format_message_header(msg: Message, idx: int) -> str:- """Format message header with role and role_id."""- role_id_display = msg.role_id if msg.role_id else msg.role- return f"[{idx}][{msg.role}][{role_id_display}]: {format_message_with_parts(msg)}"+ """Format message header with role and stable interaction peer when present."""+ speaker = msg.peer_id or msg.role+ return f"[{idx}][{msg.role}][{speaker}]: {format_message_with_parts(msg)}"conversation_sections.append("\n".join([format_message_header(msg, idx) for idx, msg in enumerate(messages)])@@ -277,7 +289,7 @@ After exploring, analyze the conversation and output ALL memory write/edit/deletfor msg in self.messages:role = getattr(msg, "role", "")- role_id = getattr(msg, "role_id", "") or role+ speaker = getattr(msg, "peer_id", "") or roleparts = getattr(msg, "parts", [])text_parts: List[str] = []@@ -297,14 +309,14 @@ After exploring, analyze the conversation and output ALL memory write/edit/delettool_parts.append(tool_part)if text_parts:- section = f"{role_id}: " + "\n".join(text_parts)+ section = f"{speaker}: " + "\n".join(text_parts)if role == "user":primary_sections.append(section)else:supporting_sections.append(section)if tool_parts:- supporting_sections.append(f"{role_id}: " + "\n".join(tool_parts))+ supporting_sections.append(f"{speaker}: " + "\n".join(tool_parts))query = "\n\n".join(primary_sections + supporting_sections)if not query.strip():@@ -403,13 +415,14 @@ After exploring, analyze the conversation and output ALL memory write/edit/deletfor s in self._get_registry().list_all(include_disabled=False)if not getattr(s, "agent_only", False)]+ if self._isolation_handler:+ schemas = [s for s in schemas if self._isolation_handler.allows_schema(s)]# Step 1: Separate schemas into multi-file (ls) and single-file (direct read)ls_dirs = set() # directories to ls (for multi-file schemas)read_files = set() # files to read directly (for single-file schemas)rolescope: RoleScope = self._isolation_handler.get_read_scope()- policy = self._ctx.namespace_policyfor schema in schemas:if not schema.directory:@@ -420,14 +433,21 @@ After exploring, analyze the conversation and output ALL memory write/edit/deletcontinueschema_dirs = set()- for user_id in rolescope.user_ids:- for agent_id in rolescope.agent_ids:- user_space = to_user_space(policy, user_id, agent_id)- agent_space = to_agent_space(policy, user_id, agent_id)+ if self._isolation_handler:+ schema_dirs.update(self._isolation_handler.render_schema_directories(schema))+ else:+ for user_id in rolescope.user_ids:dir_path = render_template(- schema.directory, {"user_space": user_space, "agent_space": agent_space}+ schema.directory,+ {"user_space": user_id},)schema_dirs.add(dir_path)+ for peer_id in rolescope.peer_ids:+ dir_path = render_template(+ schema.directory,+ {"user_space": peer_user_space(user_id, peer_id)},+ )+ schema_dirs.add(dir_path)if schema.filename_has_variables():for dir_path in schema_dirs:ls_dirs.add(dir_path)@@ -511,11 +531,14 @@ After exploring, analyze the conversation and output ALL memory write/edit/deletdef get_memory_schemas(self, ctx: RequestContext) -> List[Any]:"""获取需要参与的 memory schemas(内部自动加载)"""- return [+ schemas = [sfor s in self._get_registry().list_all(include_disabled=False)if not getattr(s, "agent_only", False)]+ if self._isolation_handler:+ schemas = [s for s in schemas if self._isolation_handler.allows_schema(s)]+ return schemasdef get_schema_directories(self) -> List[str]:"""返回需要加载的 schema 目录"""@@ -525,9 +548,7 @@ After exploring, analyze the conversation and output ALL memory write/edit/deletcustom_dir = config.memory.custom_templates_dirself._schema_directories = [memory_templates_dir]if getattr(config.memory, "experimental_memory_switch", False):- experimental_memory_dir = os.path.join(- memory_templates_dir, "experimental_memory"- )+ experimental_memory_dir = os.path.join(memory_templates_dir, "experimental_memory")if os.path.exists(experimental_memory_dir):self._schema_directories.append(experimental_memory_dir)if custom_dir:diff --git a/openviking/session/memory/utils/uri.py b/openviking/session/memory/utils/uri.pyindex fe693a5e9..d3ca152be 100644--- a/openviking/session/memory/utils/uri.py+++ b/openviking/session/memory/utils/uri.py@@ -45,7 +45,6 @@ def generate_uri(memory_type: MemoryTypeSchema,fields: Dict[str, Any],user_space: str = "default",- agent_space: str = "default",extract_context: Any = None,) -> tuple[str, str]:"""@@ -55,7 +54,6 @@ def generate_uri(memory_type: The memory type schema with directory and filename_templatefields: The field values to use for template replacementuser_space: The user space to substitute for {{ user_space }}- agent_space: The agent space to substitute for {{ agent_space }}extract_context: ExtractContext instance for template rendering (same as content_template)Returns:@@ -67,14 +65,20 @@ def generate_uri(# Build the URI template from directory and filename_templatedir_template = memory_type.directory- uri_template = f"{dir_template}/{memory_type.filename_template}"- # Build the context for Jinja2 rendering - include user_space and agent_space- context = {- "user_space": user_space,- "agent_space": agent_space,- }+ filename_template = memory_type.filename_template+ if dir_template and filename_template:+ uri_template = f"{dir_template.rstrip('/')}/{filename_template.lstrip('/')}"+ else:+ uri_template = dir_template or filename_template+ context = {"user_space": user_space}# Add all fields to context (uri_fields with actual values)context.update(fields)+ template_vars = set(re.findall(r"\{\{\s*(\w+)\s*\}\}", uri_template))+ for var in template_vars:+ if var not in context:+ raise ValueError(f"Missing template variable: {var}")+ if context[var] is None:+ raise ValueError(f"Template variable '{var}' has None value")# Render using unified render_template method (same as content_template)uri = render_template(uri_template, context, extract_context)return uri@@ -99,8 +103,7 @@ def validate_uri_template(memory_type: MemoryTypeSchema) -> bool:# Match Jinja2 {{ variable }} patternstemplate_vars = set(re.findall(r"\{\{\s*(\w+)\s*\}\}", memory_type.filename_template))- # {{ user_space }} and {{ agent_space }} are built-in, not from fields- built_in_vars = {"user_space", "agent_space"}+ built_in_vars = {"user_space"}required_field_vars = template_vars - built_in_varsfor var in required_field_vars:diff --git a/openviking/session/memory_policy.py b/openviking/session/memory_policy.pynew file mode 100644index 000000000..8e73dcaa0--- /dev/null+++ b/openviking/session/memory_policy.py@@ -0,0 +1,76 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Memory extraction policy for session commits."""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any++from openviking_cli.exceptions import InvalidArgumentError++DEFAULT_LONG_TERM_MEMORY_TYPES = {+ "profile",+ "preferences",+ "entities",+ "events",+ "cases",+ "patterns",+ "tools",+ "skills",+ "identity",+ "soul",+}++DEFAULT_AGENT_MEMORY_TYPES = {+ "trajectories",+ "experiences",+}+++def _target_enabled(data: Any, *, default_enabled: bool) -> bool:+ if data is None:+ return default_enabled+ if not isinstance(data, dict):+ raise InvalidArgumentError("memory_policy target must be an object")+ return bool(data.get("enabled", default_enabled))+++@dataclass+class MemoryPolicy:+ """Effective memory policy for one commit."""++ self_enabled: bool = True+ peer_enabled: bool = False++ @classmethod+ def default(cls) -> "MemoryPolicy":+ return cls()++ @classmethod+ def from_dict(cls, data: Any) -> "MemoryPolicy":+ if data is None:+ return cls.default()+ if isinstance(data, MemoryPolicy):+ return data+ if not isinstance(data, dict):+ raise InvalidArgumentError("memory_policy must be an object")+ return cls(+ self_enabled=_target_enabled(data.get("self"), default_enabled=True),+ peer_enabled=_target_enabled(data.get("peer"), default_enabled=False),+ )++ @classmethod+ def merge(cls, session_policy: Any = None, commit_policy: Any = None) -> "MemoryPolicy":+ """Return the policy used by a commit."""+ if commit_policy is not None:+ return cls.from_dict(commit_policy)+ if session_policy is not None:+ return cls.from_dict(session_policy)+ return cls.default()++ def to_dict(self) -> dict[str, Any]:+ return {+ "self": {"enabled": self.self_enabled},+ "peer": {"enabled": self.peer_enabled},+ }diff --git a/openviking/session/session.py b/openviking/session/session.pyindex f13aae78b..74725d663 100644--- a/openviking/session/session.py+++ b/openviking/session/session.py@@ -14,11 +14,16 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optionalfrom uuid import uuid4from openviking.core.namespace import canonical_session_uri+from openviking.core.peer_id import normalize_peer_id, safe_peer_idfrom openviking.message import Message, Partfrom openviking.message.part import ContextPart, TextPart, ToolPartfrom openviking.server.config import ToolOutputExternalizationConfigfrom openviking.server.identity import RequestContext, Role-from openviking.session.tool_result_synopsis import ToolResultSynopsis, generate_tool_result_synopsis+from openviking.session.memory_policy import (+ DEFAULT_AGENT_MEMORY_TYPES,+ DEFAULT_LONG_TERM_MEMORY_TYPES,+ MemoryPolicy,+)from openviking.session.tool_result_store import (ToolResultStore,build_tool_result_id,@@ -26,10 +31,14 @@ from openviking.session.tool_result_store import (render_preview_from_synopsis,sha256_text,)+from openviking.session.tool_result_synopsis import (+ ToolResultSynopsis,+ generate_tool_result_synopsis,+)from openviking.telemetry import get_current_telemetry, tracerfrom openviking.telemetry.request_wait_tracker import get_request_wait_tracker-from openviking.utils.token_estimation import estimate_text_tokensfrom openviking.utils.time_utils import get_current_timestamp+from openviking.utils.token_estimation import estimate_text_tokensfrom openviking_cli.exceptions import FailedPreconditionErrorfrom openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils import get_logger, run_async@@ -51,6 +60,32 @@ def _wm_debug(msg: str) -> None:logger.debug("wm_v2: %s", msg)+def _known_memory_types() -> set[str]:+ """Return memory types accepted by commit memory_policy."""+ names = set(DEFAULT_LONG_TERM_MEMORY_TYPES) | set(DEFAULT_AGENT_MEMORY_TYPES)+ try:+ from openviking.session.memory.memory_type_registry import MemoryTypeRegistry++ names.update(MemoryTypeRegistry().list_names())+ except Exception:+ logger.debug("Failed to load v2 memory type registry", exc_info=True)+ return names+++def _default_memory_counts() -> Dict[str, int]:+ counts = dict.fromkeys(sorted(DEFAULT_LONG_TERM_MEMORY_TYPES), 0)+ counts["total"] = 0+ return counts+++def _message_peer_ids(messages: List[Message]) -> set[str]:+ return {+ peer_id+ for message in messages+ if (peer_id := safe_peer_id(getattr(message, "peer_id", None)))+ }++# =====================================================================# Working Memory v2# ---------------------------------------------------------------------@@ -170,25 +205,13 @@ class SessionMeta:session_id: str = ""created_at: str = ""updated_at: str = ""+ created_by_account_id: str = ""created_by_user_id: str = ""participant_user_ids: List[str] = field(default_factory=list)- participant_agent_ids: List[str] = field(default_factory=list)message_count: int = 0total_message_count: Optional[int] = 0commit_count: int = 0- memories_extracted: Dict[str, int] = field(- default_factory=lambda: {- "profile": 0,- "preferences": 0,- "entities": 0,- "events": 0,- "cases": 0,- "patterns": 0,- "tools": 0,- "skills": 0,- "total": 0,- }- )+ memories_extracted: Dict[str, int] = field(default_factory=_default_memory_counts)last_commit_at: str = ""llm_token_usage: Dict[str, int] = field(default_factory=lambda: {@@ -214,15 +237,16 @@ class SessionMeta:# add_message calls can maintain pending_tokens consistently across# process restarts.keep_recent_count: int = 0+ memory_policy: Optional[Dict[str, Any]] = Nonedef to_dict(self) -> Dict[str, Any]:data = {"session_id": self.session_id,"created_at": self.created_at,"updated_at": self.updated_at,+ "created_by_account_id": self.created_by_account_id,"created_by_user_id": self.created_by_user_id,"participant_user_ids": list(self.participant_user_ids),- "participant_agent_ids": list(self.participant_agent_ids),"message_count": self.message_count,"commit_count": self.commit_count,"memories_extracted": dict(self.memories_extracted),@@ -231,6 +255,7 @@ class SessionMeta:"embedding_token_usage": dict(self.embedding_token_usage),"pending_tokens": self.pending_tokens,"keep_recent_count": self.keep_recent_count,+ "memory_policy": dict(self.memory_policy) if self.memory_policy is not None else None,}if self.total_message_count is not None:data["total_message_count"] = self.total_message_count@@ -242,27 +267,24 @@ class SessionMeta:embedding_token_usage = data.get("embedding_token_usage", {})memories = data.get("memories_extracted", {})+ memory_counts = _default_memory_counts()+ for key, value in memories.items():+ try:+ memory_counts[key] = int(value or 0)+ except (TypeError, ValueError):+ memory_counts[key] = 0+return cls(session_id=data.get("session_id", ""),created_at=data.get("created_at", ""),updated_at=data.get("updated_at", ""),+ created_by_account_id=data.get("created_by_account_id", ""),created_by_user_id=data.get("created_by_user_id", ""),participant_user_ids=list(data.get("participant_user_ids", [])),- participant_agent_ids=list(data.get("participant_agent_ids", [])),message_count=data.get("message_count", 0),total_message_count=data.get("total_message_count"),commit_count=data.get("commit_count", 0),- memories_extracted={- "profile": memories.get("profile", 0),- "preferences": memories.get("preferences", 0),- "entities": memories.get("entities", 0),- "events": memories.get("events", 0),- "cases": memories.get("cases", 0),- "patterns": memories.get("patterns", 0),- "tools": memories.get("tools", 0),- "skills": memories.get("skills", 0),- "total": memories.get("total", 0),- },+ memories_extracted=memory_counts,last_commit_at=data.get("last_commit_at", ""),llm_token_usage={"prompt_tokens": llm_token_usage.get("prompt_tokens", 0),@@ -276,6 +298,7 @@ class SessionMeta:},pending_tokens=max(0, int(data.get("pending_tokens", 0) or 0)),keep_recent_count=max(0, int(data.get("keep_recent_count", 0) or 0)),+ memory_policy=data.get("memory_policy"),)@@ -323,6 +346,7 @@ class Session:self._meta = SessionMeta(session_id=self.session_id,created_at=get_current_timestamp(),+ created_by_account_id=self.ctx.account_id,created_by_user_id=self.ctx.user.user_id,participant_user_ids=[self.ctx.user.user_id],)@@ -379,13 +403,12 @@ class Session:self._meta.commit_count = self._compression.compression_indexself._meta.total_message_count = None+ if not self._meta.created_by_account_id:+ self._meta.created_by_account_id = self.ctx.account_idif not self._meta.created_by_user_id:self._meta.created_by_user_id = self.ctx.user.user_idif not self._meta.participant_user_ids:self._meta.participant_user_ids = [self._meta.created_by_user_id]- for message in self._messages:- self._record_participant(message)-# WM v2: always rebuild pending_tokens from current messages so the# counter stays consistent across restarts and is also backfilled for# legacy sessions whose .meta.json predates these fields. O(n) once,@@ -636,7 +659,8 @@ class Session:tool_id=part.tool_id,tool_name=part.tool_name,message_id=msg.id,- agent_id=msg.role_id,+ user_id=self.ctx.user.user_id if self.ctx and self.ctx.user else None,+ peer_id=msg.peer_id,created_at=msg.created_at,preview_chars=preview_chars,mime_type=part.tool_output_mime_type or "text/plain",@@ -709,9 +733,7 @@ class Session:group_original_chars = sum(len(p.tool_output or "") for _, p in tool_parts)normal_indices: List[int] = []selected: set[int] = set()- externalized_preview_cache: Dict[- tuple[int, int, str], tuple[ToolResultSynopsis, int]- ] = {}+ externalized_preview_cache: Dict[tuple[int, int, str], tuple[ToolResultSynopsis, int]] = {}for idx, (_msg, part) in enumerate(tool_parts):part.tool_output_group_id = group_id@@ -767,7 +789,9 @@ class Session:for idx, (_, part) in enumerate(tool_parts):output_len = len(part.tool_output or "")if idx in selected_indices:- _synopsis, rendered_len = prepared_externalized_preview(idx, part, preview_chars)+ _synopsis, rendered_len = prepared_externalized_preview(+ idx, part, preview_chars+ )total += rendered_lenelse:total += output_len@@ -825,7 +849,6 @@ class Session:"""Append multiple messages: update lists, stats, JSONL, meta."""for msg in messages:self._messages.append(msg)- self._record_participant(msg)if msg.role == "user":self._stats.total_turns += 1@@ -854,7 +877,7 @@ class Session:Args:messages_spec: List of dicts, each with keys:- role, parts, role_id (optional), created_at (optional)+ role, parts, peer_id (optional), created_at (optional)"""all_messages = []for i, spec in enumerate(messages_spec):@@ -864,16 +887,22 @@ class Session:raise ValueError(f"messages_spec[{i}]: missing required key 'parts'")role = spec["role"]parts = spec["parts"]- role_id = spec.get("role_id")created_at = spec.get("created_at") or datetime.now(timezone.utc).isoformat()+ try:+ peer_id = normalize_peer_id(spec.get("peer_id"))+ except ValueError as exc:+ from openviking_cli.exceptions import InvalidArgumentError++ raise InvalidArgumentError(str(exc)) from exc+if self._is_tool_result_aggregate(role, parts):msgs = [Message(id=f"msg_{uuid4().hex}",role=role,parts=[part],- role_id=role_id,+ peer_id=peer_id,created_at=created_at,)for part in parts@@ -885,7 +914,7 @@ class Session:id=f"msg_{uuid4().hex}",role=role,parts=parts,- role_id=role_id,+ peer_id=peer_id,created_at=created_at,)self._externalize_large_tool_outputs(msg)@@ -898,7 +927,7 @@ class Session:self,role: str,parts: List[Part],- role_id: Optional[str] = None,+ peer_id: Optional[str] = None,created_at: str = None,) -> Message:"""Add a message.@@ -906,22 +935,18 @@ class Session:A user message containing only multiple tool results is treated as atransport aggregate and stored as one message per tool result."""- msgs = self.add_messages([{- "role": role,- "parts": parts,- "role_id": role_id,- "created_at": created_at,- }])+ msgs = self.add_messages(+ [+ {+ "role": role,+ "parts": parts,+ "peer_id": peer_id,+ "created_at": created_at,+ }+ ]+ )return msgs[0]- def _record_participant(self, msg: Message) -> None:- if msg.role == "user" and msg.role_id:- if msg.role_id not in self._meta.participant_user_ids:- self._meta.participant_user_ids.append(msg.role_id)- if msg.role == "assistant" and msg.role_id:- if msg.role_id not in self._meta.participant_agent_ids:- self._meta.participant_agent_ids.append(msg.role_id)-def update_tool_part(self,message_id: str,@@ -1008,12 +1033,25 @@ class Session:return {"tool_results": []}return await store.list(tool_name=tool_name, limit=limit)- def commit(self, keep_recent_count: int = 0) -> Dict[str, Any]:+ def commit(+ self,+ keep_recent_count: int = 0,+ memory_policy: Optional[Dict[str, Any]] = None,+ ) -> Dict[str, Any]:"""Sync wrapper for commit_async()."""- return run_async(self.commit_async(keep_recent_count=keep_recent_count))+ return run_async(+ self.commit_async(+ keep_recent_count=keep_recent_count,+ memory_policy=memory_policy,+ )+ )@tracer("session.commit.phase1")- async def commit_async(self, keep_recent_count: int = 0) -> Dict[str, Any]:+ async def commit_async(+ self,+ keep_recent_count: int = 0,+ memory_policy: Optional[Dict[str, Any]] = None,+ ) -> Dict[str, Any]:"""Async commit session: archive immediately, extract memories in background.Phase 1 (Archive prep, path-lock protected): Split messages into@@ -1029,6 +1067,8 @@ class Session:behavior of archiving everything. The plugin's afterTurn pathtypically passes its configured value (default 10); the compactpath passes ``0``.+ memory_policy: Optional per-commit extraction policy. When omitted,+ the session default policy is used.Returns a task_id for tracking Phase 2 progress."""@@ -1038,6 +1078,11 @@ class Session:trace_id = tracer.get_trace_id()keep_recent_count = max(0, int(keep_recent_count or 0))+ effective_policy = MemoryPolicy.merge(+ session_policy=self._meta.memory_policy,+ commit_policy=memory_policy,+ )+ effective_memory_policy = effective_policy.to_dict()logger.info(f"[TRACER] session_commit started, trace_id={trace_id}, "f"keep_recent_count={keep_recent_count}"@@ -1147,6 +1192,11 @@ class Session:self._meta.message_count = len(self._messages)self._meta.pending_tokens = 0self._meta.keep_recent_count = keep_recent_count+ self._meta.commit_count = max(+ self._meta.commit_count,+ self._compression.compression_index,+ )+ self._meta.last_commit_at = get_current_timestamp()await self._save_meta()self._compression.original_count += len(messages_to_archive)@@ -1175,6 +1225,7 @@ class Session:usage_records=usage_snapshot,first_message_id=messages_to_archive[0].id if messages_to_archive else "",last_message_id=messages_to_archive[-1].id if messages_to_archive else "",+ memory_policy=effective_memory_policy,))@@ -1196,6 +1247,7 @@ class Session:usage_records: List["Usage"],first_message_id: str,last_message_id: str,+ memory_policy: Optional[Dict[str, Any]],) -> None:"""Phase 2: Extract memories, write relations, enqueue — runs in background."""import uuid@@ -1257,7 +1309,6 @@ class Session:"session_uri": self._session_uri,"account_id": self.ctx.account_id,"user_id": self.ctx.user.user_id,- "agent_id": self.ctx.user.agent_id,"role": self.ctx.role.value,},)@@ -1298,12 +1349,39 @@ class Session:# Summary generation, user memory and agent memory all run concurrently.ov_config = get_openviking_config()memory_extraction_enabled = ov_config.memory.extraction_enabled- session_skill_extraction_enabled = (+ agent_memory_enabled = bool(+ getattr(ov_config.memory, "agent_memory_enabled", False)+ )+ config_session_skill_extraction_enabled = (ov_config.memory.session_skill_extraction_enabled)- if self._session_compressor and (- memory_extraction_enabled or session_skill_extraction_enabled- ):+ effective_policy = MemoryPolicy.from_dict(memory_policy)+ self_memory_enabled = effective_policy.self_enabled+ peer_memory_enabled = effective_policy.peer_enabled+ allowed_peer_ids = (+ _message_peer_ids(extraction_messages) if peer_memory_enabled else set()+ )+ session_skill_extraction_enabled = (+ config_session_skill_extraction_enabled and self_memory_enabled+ )+ registered_memory_types = _known_memory_types()+ agent_allowed_types = (+ registered_memory_types & DEFAULT_AGENT_MEMORY_TYPES+ if agent_memory_enabled and memory_extraction_enabled+ else set()+ )+ self_agent_types = agent_allowed_types if self_memory_enabled else set()+ long_term_allowed_types = (+ registered_memory_types & DEFAULT_LONG_TERM_MEMORY_TYPES+ if memory_extraction_enabled and (self_memory_enabled or allowed_peer_ids)+ else set()+ )+ has_policy_work = bool(+ long_term_allowed_types+ or self_agent_types+ or session_skill_extraction_enabled+ )+ if self._session_compressor and has_policy_work:logger.info("Starting post-commit extraction from %s archived messages",len(messages),@@ -1313,92 +1391,106 @@ class Session:self._session_compressor, "extract_agent_memories")- async def _noop_list():- return []-- async def _noop_agent_result():- return {"contexts": [], "session_skills": []}-- async def _run_long_term_memories():- if not memory_extraction_enabled:- return []- return await self._session_compressor.extract_long_term_memories(- messages=extraction_messages,- user=self.user,- session_id=self.session_id,- ctx=self.ctx,- latest_archive_overview=latest_archive_overview,- archive_uri=archive_uri,+ extraction_tasks: List[Any] = [_run_archive_summary()]+ extraction_labels = ["archive_summary"]++ if long_term_allowed_types:+ extraction_tasks.append(+ self._session_compressor.extract_long_term_memories(+ messages=extraction_messages,+ user=self.user,+ session_id=self.session_id,+ ctx=self.ctx,+ latest_archive_overview=latest_archive_overview,+ archive_uri=archive_uri,+ allowed_memory_types=long_term_allowed_types,+ allow_self_memory=self_memory_enabled,+ allowed_peer_ids=allowed_peer_ids,+ ))+ extraction_labels.append("long_term")- async def _run_agent_memories():- if not has_agent_memory:- return {"contexts": [], "session_skills": []}- if not (memory_extraction_enabled or session_skill_extraction_enabled):- return {"contexts": [], "session_skills": []}- return await self._session_compressor.extract_agent_memories(- messages=extraction_messages,- ctx=self.ctx,- latest_archive_overview=latest_archive_overview,- archive_uri=archive_uri,- )+ if has_agent_memory and (+ self_agent_types or session_skill_extraction_enabled+ ):+ try:+ extraction_tasks.append(+ self._session_compressor.extract_agent_memories(+ messages=extraction_messages,+ ctx=self.ctx,+ latest_archive_overview=latest_archive_overview,+ archive_uri=archive_uri,+ allowed_memory_types=self_agent_types,+ include_session_skills=session_skill_extraction_enabled,+ )+ )+ extraction_labels.append("agent")+ except Exception as exc:+ logger.error(+ "Agent memory extraction failed: %s",+ exc,+ exc_info=exc,+ )_results = await asyncio.gather(- _run_archive_summary(),- _run_long_term_memories(),- _run_agent_memories() if has_agent_memory else _noop_agent_result(),+ *extraction_tasks,return_exceptions=True,)- summary_result, extracted_result, agent_result = _results+ summary_result = _results[0]if isinstance(summary_result, Exception):logger.error(f"Archive summary generation failed: {summary_result}",exc_info=summary_result,)- if isinstance(extracted_result, Exception):- logger.error(- f"User memory extraction failed: {extracted_result}",- exc_info=extracted_result,- )- raise extracted_result- else:- extracted = extracted_result- if isinstance(agent_result, Exception):- logger.error(- f"Agent memory extraction failed: {agent_result}",- exc_info=agent_result,+ total_extracted = 0+ extraction_errors: list[BaseException] = []+ for label, result in zip(extraction_labels[1:], _results[1:], strict=True):+ if isinstance(result, Exception):+ logger.error(+ "Memory extraction failed for %s: %s",+ label,+ result,+ exc_info=result,+ )+ extraction_errors.append(result)+ continue++ if isinstance(result, dict):+ target_contexts = list(result.get("contexts", []))+ target_skills = list(result.get("session_skills", []))+ else:+ target_contexts = list(result or [])+ target_skills = []+ logger.info(+ "Extracted %s memories for %s",+ len(target_contexts),+ label,)- agent_extracted = []- session_skills = []- else:- agent_extracted = list(agent_result.get("contexts", []))- session_skills = list(agent_result.get("session_skills", []))-- if memory_extraction_enabled:- logger.info(f"Extracted {len(extracted)} memories")- for ctx_item in extracted:+ total_extracted += len(target_contexts)+ for ctx_item in target_contexts:cat = getattr(ctx_item, "category", "") or "unknown"memories_extracted[cat] = memories_extracted.get(cat, 0) + 1- self._stats.memories_extracted += len(extracted)- get_current_telemetry().set("memory.extracted", len(extracted))+ if target_skills:+ extracted_skill_results.extend(target_skills)- if agent_extracted:- logger.info(f"Extracted {len(agent_extracted)} agent memories")- for ctx_item in agent_extracted:- cat = getattr(ctx_item, "category", "") or "unknown"- memories_extracted[cat] = memories_extracted.get(cat, 0) + 1- self._stats.memories_extracted += len(agent_extracted)- if session_skills:- logger.info(f"Extracted {len(session_skills)} session skills")- extracted_skill_results = session_skills+ if extraction_errors:+ raise extraction_errors[0]++ if total_extracted:+ self._stats.memories_extracted += total_extracted+ if extracted_skill_results:+ logger.info(+ "Extracted %s session skills",+ len(extracted_skill_results),+ )+ get_current_telemetry().set("memory.extracted", total_extracted)else:if self._session_compressor:logger.info(- "Memory and session skill extraction are disabled by config "- "(memory.extraction_enabled=false, "- "memory.session_skill_extraction_enabled=false)"+ "Memory and session skill extraction skipped "+ "(disabled by config or memory_policy)")await _run_archive_summary()@@ -1893,12 +1985,12 @@ class Session:async def _get_pending_archive_messages(self) -> List[Message]:"""Return messages from incomplete archives newer than the latest completed archive."""- latest_completed_index = 0+ latest_completed_index = max(0, self._meta.commit_count)incomplete_archives: List[Dict[str, Any]] = []for archive in sorted(await self._list_archive_refs(), key=lambda item: item["index"]):try:await self._viking_fs.read_file(f"{archive['archive_uri']}/.done", ctx=self.ctx)- latest_completed_index = archive["index"]+ latest_completed_index = max(latest_completed_index, archive["index"])except Exception:incomplete_archives.append(archive)diff --git a/openviking/session/skill/session_skill_context_provider.py b/openviking/session/skill/session_skill_context_provider.pyindex 01ebde1f9..52e85e068 100644--- a/openviking/session/skill/session_skill_context_provider.py+++ b/openviking/session/skill/session_skill_context_provider.py@@ -7,7 +7,7 @@ from __future__ import annotationsfrom pathlib import Pathfrom typing import Any, Dict, List, Tuple-from openviking.core.namespace import canonical_agent_root+from openviking.core.namespace import canonical_user_rootfrom openviking.core.skill_loader import SkillLoaderfrom openviking.prompts.manager import PromptManagerfrom openviking.session.memory.dataclass import MemoryFile@@ -97,7 +97,7 @@ class SessionSkillContextProvider(SessionExtractContextProvider):if not self._ctx or not self._viking_fs:return pre_fetch_messages- skill_root_uri = f"{canonical_agent_root(self._ctx)}/skills"+ skill_root_uri = f"{canonical_user_root(self._ctx)}/skills"try:entries = await self._viking_fs.ls(skill_root_uri,diff --git a/openviking/session/tool_result_store.py b/openviking/session/tool_result_store.pyindex 1eb302ab4..a72912f4f 100644--- a/openviking/session/tool_result_store.py+++ b/openviking/session/tool_result_store.py@@ -128,7 +128,8 @@ class ToolResultStore:tool_id: str,tool_name: str,message_id: str,- agent_id: Optional[str],+ user_id: Optional[str],+ peer_id: Optional[str],created_at: Optional[str],preview_chars: int,mime_type: str = "text/plain",@@ -177,7 +178,8 @@ class ToolResultStore:"message_id": message_id,"tool_id": tool_id,"tool_name": tool_name,- "agent_id": agent_id,+ "user_id": user_id,+ "peer_id": peer_id,"created_at": created_at,"original_chars": len(content),"preview_chars": min(len(content), max(preview_chars, 0)),diff --git a/openviking/storage/collection_schemas.py b/openviking/storage/collection_schemas.pyindex 00e1767f3..5edd6cc54 100644--- a/openviking/storage/collection_schemas.py+++ b/openviking/storage/collection_schemas.py@@ -77,7 +77,7 @@ class CollectionSchemas:# context_type 字段:区分上下文的大类# 枚举值:"resource"(资源,默认), "memory"(记忆), "skill"(技能)# 推导规则:- # - URI 以 viking://agent/skills 开头 → "skill"+ # - URI 位于 user skills 目录下 → "skill"# - URI 包含 "memories" → "memory"# - 其他情况 → "resource"{"FieldName": "context_type", "FieldType": "string"},@@ -105,7 +105,6 @@ class CollectionSchemas:{"FieldName": "abstract", "FieldType": "string"},{"FieldName": "account_id", "FieldType": "string"},{"FieldName": "owner_user_id", "FieldType": "string"},- {"FieldName": "owner_agent_id", "FieldType": "string"},])scalar_index = [@@ -123,7 +122,6 @@ class CollectionSchemas:"tags","account_id","owner_user_id",- "owner_agent_id",])return {@@ -627,7 +625,6 @@ class TextEmbeddingHandler(DequeueHandlerBase):user = UserIdentifier(account_id=account_id,user_id="default",- agent_id="default",)ctx = RequestContext(user=user, role=Role.ROOT)record_id = await self._vikingdb.upsert(inserted_data, ctx=ctx)diff --git a/openviking/storage/content_write.py b/openviking/storage/content_write.pyindex 623593f07..184b88d1a 100644--- a/openviking/storage/content_write.py+++ b/openviking/storage/content_write.py@@ -380,7 +380,7 @@ class ContentWriteCoordinator:context_type=context_type,account_id=ctx.account_id,user_id=ctx.user.user_id,- agent_id=ctx.user.agent_id,+ peer_id=ctx.user.user_id,role=ctx.role.value,skip_vectorization=False,telemetry_id=telemetry.telemetry_id,@@ -390,7 +390,7 @@ class ContentWriteCoordinator:uri=root_uri,account_id=ctx.account_id,user_id=ctx.user.user_id,- agent_id=ctx.user.agent_id,+ peer_id=ctx.user.user_id,)if context_type in {"resource", "skill"}else ""@@ -421,7 +421,7 @@ class ContentWriteCoordinator:context_type="memory",account_id=ctx.account_id,user_id=ctx.user.user_id,- agent_id=ctx.user.agent_id,+ peer_id=ctx.user.user_id,role=ctx.role.value,skip_vectorization=False,telemetry_id=telemetry.telemetry_id,@@ -430,7 +430,7 @@ class ContentWriteCoordinator:uri=root_uri,account_id=ctx.account_id,user_id=ctx.user.user_id,- agent_id=ctx.user.agent_id,+ peer_id=ctx.user.user_id,),changes={"modified": [modified_uri]},)@@ -549,25 +549,6 @@ class ContentWriteCoordinator:f"memory write target must be inside a memory type directory: {uri}")root_uri = VikingURI.build(*parts[: memories_idx + 2])- elif parts[0] == "agent":- try:- skills_idx = parts.index("skills")- except ValueError:- skills_idx = -1- if skills_idx >= 0 and len(parts) > skills_idx + 1:- root_uri = VikingURI.build(*parts[: skills_idx + 2])- else:- try:- memories_idx = parts.index("memories")- except ValueError as exc:- raise InvalidArgumentError(- f"write only supports memory or skill files under agent scope: {uri}"- ) from exc- if len(parts) <= memories_idx + 1:- raise InvalidArgumentError(- f"memory write target must be inside a memory type directory: {uri}"- )- root_uri = VikingURI.build(*parts[: memories_idx + 2])stat = await self._safe_stat(root_uri, ctx=ctx, allow_not_found=_allow_not_found)if stat.get("not_found") or not stat.get("isDir"):diff --git a/openviking/storage/ovpack/policy.py b/openviking/storage/ovpack/policy.pyindex 4561c1b73..e21a44eaa 100644--- a/openviking/storage/ovpack/policy.py+++ b/openviking/storage/ovpack/policy.py@@ -18,9 +18,9 @@ from openviking.storage.ovpack.format import (from openviking_cli.exceptions import InvalidArgumentErrorfrom openviking_cli.utils.uri import VikingURI-PUBLIC_SCOPES = ("resources", "user", "agent", "session")+PUBLIC_SCOPES = ("resources", "user", "session")IMPORTABLE_SCOPES = frozenset(PUBLIC_SCOPES)-STRUCTURED_IMPORT_SCOPES = frozenset({"user", "agent", "session"})+STRUCTURED_IMPORT_SCOPES = frozenset({"user", "session"})EXCLUDED_FILENAMES = frozenset({".relations.json"})NON_VECTOR_SCOPES = frozenset({"session"})diff --git a/openviking/storage/ovpack/vectors.py b/openviking/storage/ovpack/vectors.pyindex 2e2b425a5..220f27b82 100644--- a/openviking/storage/ovpack/vectors.py+++ b/openviking/storage/ovpack/vectors.py@@ -289,7 +289,6 @@ async def _upsert_vector_snapshot_record("active_count": 0,"account_id": ctx.account_id,"owner_user_id": owner_fields.get("owner_user_id"),- "owner_agent_id": owner_fields.get("owner_agent_id"),"vector": dense_vector,}if not payload.get("abstract"):diff --git a/openviking/storage/queuefs/embedding_msg_converter.py b/openviking/storage/queuefs/embedding_msg_converter.pyindex c681f799b..fc4523cb7 100644--- a/openviking/storage/queuefs/embedding_msg_converter.py+++ b/openviking/storage/queuefs/embedding_msg_converter.py@@ -43,10 +43,9 @@ class EmbeddingMsgConverter:account_id=context_data.get("account_id"),)context_data["uri"] = owner_fields["uri"]- if context_data.get("owner_user_id") is None and context_data.get("owner_agent_id") is None:+ if context_data.get("owner_user_id") is None:if owner_fields is not None:context_data["owner_user_id"] = owner_fields["owner_user_id"]- context_data["owner_agent_id"] = owner_fields["owner_agent_id"]# Derive level field for hierarchical retrieval.uri = context_data.get("uri", "")diff --git a/openviking/storage/queuefs/semantic_msg.py b/openviking/storage/queuefs/semantic_msg.pyindex c9fab4ee2..a71a77161 100644--- a/openviking/storage/queuefs/semantic_msg.py+++ b/openviking/storage/queuefs/semantic_msg.py@@ -17,9 +17,9 @@ def build_semantic_coalesce_key(uri: str,account_id: str = "default",user_id: str = "default",- agent_id: str = "default",+ peer_id: str = "default",) -> str:- return "|".join([context_type, account_id, user_id, agent_id, uri.rstrip("/")])+ return "|".join([context_type, account_id, user_id, peer_id, uri.rstrip("/")])@dataclass@@ -46,7 +46,7 @@ class SemanticMsg:recursive: bool = True # Whether to recursively process subdirectoriesaccount_id: str = "default"user_id: str = "default"- agent_id: str = "default"+ peer_id: str = "default"role: str = "root"# Additional flagsskip_vectorization: bool = False@@ -68,7 +68,7 @@ class SemanticMsg:recursive: bool = True,account_id: str = "default",user_id: str = "default",- agent_id: str = "default",+ peer_id: str = "default",role: str = "root",skip_vectorization: bool = False,telemetry_id: str = "",@@ -86,7 +86,7 @@ class SemanticMsg:self.recursive = recursiveself.account_id = account_idself.user_id = user_id- self.agent_id = agent_id+ self.peer_id = peer_idself.role = roleself.skip_vectorization = skip_vectorizationself.telemetry_id = telemetry_id@@ -129,7 +129,7 @@ class SemanticMsg:recursive=data.get("recursive", True),account_id=data.get("account_id", "default"),user_id=data.get("user_id", "default"),- agent_id=data.get("agent_id", "default"),+ peer_id=data.get("peer_id", "default"),role=data.get("role", "root"),skip_vectorization=data.get("skip_vectorization", False),telemetry_id=data.get("telemetry_id", ""),diff --git a/openviking/storage/queuefs/semantic_processor.py b/openviking/storage/queuefs/semantic_processor.pyindex c4d0d6fe4..e04dda453 100644--- a/openviking/storage/queuefs/semantic_processor.py+++ b/openviking/storage/queuefs/semantic_processor.py@@ -168,7 +168,7 @@ class SemanticProcessor(DequeueHandlerBase):def _ctx_from_semantic_msg(msg: SemanticMsg) -> RequestContext:role = Role(msg.role) if msg.role in {r.value for r in Role} else Role.ROOTreturn RequestContext(- user=UserIdentifier(msg.account_id, msg.user_id, msg.agent_id),+ user=UserIdentifier(msg.account_id, msg.user_id),role=role,)@@ -283,7 +283,7 @@ class SemanticProcessor(DequeueHandlerBase):recursive=False,account_id=msg.account_id,user_id=msg.user_id,- agent_id=msg.agent_id,+ peer_id=msg.peer_id,role=msg.role,skip_vectorization=msg.skip_vectorization,changes={"modified": [uri]},@@ -292,7 +292,7 @@ class SemanticProcessor(DequeueHandlerBase):uri=parent_uri,account_id=msg.account_id,user_id=msg.user_id,- agent_id=msg.agent_id,+ peer_id=msg.peer_id,),)await semantic_queue.enqueue(parent_msg)@@ -351,7 +351,6 @@ class SemanticProcessor(DequeueHandlerBase):)root_attrs.account_id = msg.account_idroot_attrs.user_id = msg.user_id- root_attrs.agent_id = msg.agent_idroot_context_token = bind_root_observability_context(root_attrs)try:current_ctx = self._ctx_from_semantic_msg(msg)@@ -506,6 +505,7 @@ class SemanticProcessor(DequeueHandlerBase):else:self.report_error(str(e), data)return None+def get_dag_stats(self) -> Optional["DagStats"]:return SemanticDagExecutor.get_active_stats()diff --git a/openviking/storage/queuefs/semantic_queue.py b/openviking/storage/queuefs/semantic_queue.pyindex 9ab668eef..48e35bbf5 100644--- a/openviking/storage/queuefs/semantic_queue.py+++ b/openviking/storage/queuefs/semantic_queue.py@@ -40,7 +40,7 @@ class SemanticQueue(NamedQueue):@staticmethoddef _memory_parent_semantic_key(msg: SemanticMsg) -> str:- return f"{msg.account_id}|{msg.user_id}|{msg.agent_id}|{msg.uri}"+ return f"{msg.account_id}|{msg.user_id}|{msg.peer_id}|{msg.uri}"async def enqueue(self, msg: SemanticMsg) -> str:"""Serialize SemanticMsg object and store in queue."""diff --git a/openviking/storage/transaction/lock_manager.py b/openviking/storage/transaction/lock_manager.pyindex 316588989..a7e1a9185 100644--- a/openviking/storage/transaction/lock_manager.py+++ b/openviking/storage/transaction/lock_manager.py@@ -469,14 +469,13 @@ class LockManager:session_uri = info.get("session_uri")account_id = info.get("account_id", "default")user_id = info.get("user_id", "default")- agent_id = info.get("agent_id", "default")role_str = info.get("role", "root")if not archive_uri or not session_uri:raise ValueError("Cannot redo session_memory: missing archive_uri or session_uri")# 1. Build request context (needed for path conversion below)- user = UserIdentifier(account_id=account_id, user_id=user_id, agent_id=agent_id)+ user = UserIdentifier(account_id=account_id, user_id=user_id)ctx = RequestContext(user=user, role=Role(role_str))# 2. Read archived messages@@ -523,7 +522,7 @@ class LockManager:context_type="memory",account_id=account_id,user_id=user_id,- agent_id=agent_id,+ peer_id=user_id,role=role_str,)@@ -546,7 +545,7 @@ class LockManager:context_type=params.get("context_type", "resource"),account_id=params.get("account_id", "default"),user_id=params.get("user_id", "default"),- agent_id=params.get("agent_id", "default"),+ peer_id=params.get("peer_id", "default"),role=params.get("role", "root"),)semantic_queue: SemanticQueue = queue_manager.get_queue(queue_manager.SEMANTIC) # type: ignore[assignment]diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.pyindex 2c07a8aa6..b4a74baf8 100644--- a/openviking/storage/viking_fs.py+++ b/openviking/storage/viking_fs.py@@ -24,14 +24,11 @@ from datetime import datetime, timezonefrom pathlib import PurePathfrom typing import TYPE_CHECKING, Any, Dict, List, Optional, Union-from openviking.core.namespace import (- NamespaceShapeError,- canonicalize_uri,- classify_uri,-)+from openviking.core.namespace import canonicalize_urifrom openviking.core.namespace import (is_accessible as namespace_is_accessible,)+from openviking.core.retrieval_targets import resolve_retrieval_targetsfrom openviking.pyagfs import AsyncAGFSClientfrom openviking.pyagfs.exceptions import (AGFSClientError,@@ -1432,6 +1429,7 @@ class VikingFS:filter: Optional[Dict] = None,ctx: Optional[RequestContext] = None,level: Optional[List[int]] = None,+ peer_id: Optional[str] = None,):"""Semantic search.@@ -1454,23 +1452,11 @@ class VikingFS:TypedQuery,)- # Normalize target_uri to list- target_uri_list = [target_uri] if isinstance(target_uri, str) else (target_uri or [])real_ctx = self._ctx_or_default(ctx)- canonical_target_uri_list: List[str] = []- for item in target_uri_list:- if not item or item in {"/", "viking://"}:- continue- try:- canonical_target_uri_list.append(canonicalize_uri(item, real_ctx))- except NamespaceShapeError as exc:- raise InvalidArgumentError(str(exc)) from exc- target_uri_list = canonical_target_uri_list- # Use first URI for context inference and access check- primary_target_uri = target_uri_list[0] if target_uri_list else ""+ retrieval_targets = resolve_retrieval_targets(target_uri, real_ctx, peer_id)- if primary_target_uri and primary_target_uri not in {"/", "viking://"}:- self._ensure_access(primary_target_uri, ctx)+ for target_dir in retrieval_targets.target_directories:+ self._ensure_access(target_dir, ctx)storage = self._get_vector_store()if not storage:@@ -1487,18 +1473,16 @@ class VikingFS:retrieval_config=self.retrieval_config,)- # Infer context_type (None = search all types)- context_type = self._infer_context_type(primary_target_uri) if primary_target_uri else None-typed_query = TypedQuery(query=query,- context_type=context_type,+ context_type=None,intent="",- target_directories=target_uri_list if target_uri_list else None,+ target_directories=retrieval_targets.target_directories,)logger.debug(- f"[VikingFS.find] Calling retriever.retrieve with ctx.account_id={real_ctx.account_id}, ctx.user={real_ctx.user}"+ "[VikingFS.find] Calling retriever.retrieve with "+ f"ctx.account_id={real_ctx.account_id}, ctx.user={real_ctx.user}")result = await retriever.retrieve(@@ -1538,6 +1522,7 @@ class VikingFS:filter: Optional[Dict] = None,ctx: Optional[RequestContext] = None,level: Optional[List[int]] = None,+ peer_id: Optional[str] = None,):"""Complex search with session context.@@ -1562,20 +1547,9 @@ class VikingFS:TypedQuery,)- # Normalize target_uri to list- target_uri_list = [target_uri] if isinstance(target_uri, str) else (target_uri or [])real_ctx = self._ctx_or_default(ctx)- canonical_target_uri_list: List[str] = []- for item in target_uri_list:- if not item or item in {"/", "viking://"}:- continue- try:- canonical_target_uri_list.append(canonicalize_uri(item, real_ctx))- except NamespaceShapeError as exc:- raise InvalidArgumentError(str(exc)) from exc- target_uri_list = canonical_target_uri_list- # Use first URI for context inference and access check- primary_target_uri = target_uri_list[0] if target_uri_list else ""+ retrieval_targets = resolve_retrieval_targets(target_uri, real_ctx, peer_id)+ primary_target_uri = retrieval_targets.first_explicit_directorysession_summary = (str(session_info.get("latest_archive_overview") or "") if session_info else ""@@ -1583,14 +1557,12 @@ class VikingFS:current_messages = session_info.get("current_messages") if session_info else Nonequery_plan: Optional[QueryPlan] = None- if primary_target_uri and primary_target_uri not in {"/", "viking://"}:- self._ensure_access(primary_target_uri, ctx)+ for target_dir in retrieval_targets.target_directories:+ self._ensure_access(target_dir, ctx)- # When target_uri exists: read abstract, infer context_type- target_context_type: Optional[ContextType] = None+ # When target_uri exists, read its abstract as optional query-planning context.target_abstract = ""if primary_target_uri:- target_context_type = self._infer_context_type(primary_target_uri)try:target_abstract = await self.abstract(primary_target_uri, ctx=ctx)except Exception:@@ -1603,39 +1575,22 @@ class VikingFS:compression_summary=session_summary or "",messages=current_messages or [],current_message=query,- context_type=target_context_type,target_abstract=target_abstract,)typed_queries = query_plan.queries- # Set target_directories- if target_uri_list:- for tq in typed_queries:- tq.target_directories = target_uri_list+ for tq in typed_queries:+ tq.target_directories = retrieval_targets.target_directorieselse:# No session context: create query directly- if target_context_type:- # Has target_uri: only query that type- typed_queries = [- TypedQuery(- query=query,- context_type=target_context_type,- intent="",- priority=1,- target_directories=target_uri_list,- )- ]- else:- # No target_uri: query all types- typed_queries = [- TypedQuery(- query=query,- context_type=ctx_type,- intent="",- priority=1,- target_directories=target_uri_list,- )- for ctx_type in [ContextType.MEMORY, ContextType.RESOURCE, ContextType.SKILL]- ]+ typed_queries = [+ TypedQuery(+ query=query,+ context_type=None,+ intent="",+ priority=1,+ target_directories=retrieval_targets.target_directories,+ )+ ]telemetry.set("search.typed_queries_count", len(typed_queries))# Concurrent execution@@ -1651,7 +1606,8 @@ class VikingFS:async def _execute(tq: TypedQuery):real_ctx = self._ctx_or_default(ctx)logger.debug(- f"[VikingFS.search._execute] Calling retriever.retrieve with ctx.account_id={real_ctx.account_id}, ctx.user={real_ctx.user}"+ "[VikingFS.search._execute] Calling retriever.retrieve with "+ f"ctx.account_id={real_ctx.account_id}, ctx.user={real_ctx.user}")return await retriever.retrieve(tq,@@ -1980,7 +1936,7 @@ class VikingFS:"""Extract space segment from URI if present.URIs are WYSIWYG: viking://{scope}/{space}/...- For user/agent, the second segment is space unless it's a known structure dir.+ For user, the second segment is space unless it's a known structure dir.For session, the second segment is always space (when 3+ parts).Legacy temp URIs keep the historical shape viking://temp/<temp-id> and thereforeintentionally have no space segment.@@ -2076,19 +2032,6 @@ class VikingFS:except Exception:return ""- def _infer_context_type(self, uri: str):- """Infer context_type from URI. Returns None when ambiguous."""- from openviking_cli.retrieve import ContextType-- classification = classify_uri(uri)- if classification.is_memory:- return ContextType.MEMORY- elif classification.is_skill:- return ContextType.SKILL- elif classification.parts[:1] == ("resources",) or "resources" in classification.parts:- return ContextType.RESOURCE- return None-# ========== Vector Sync Helper Methods ==========async def _collect_uris(diff --git a/openviking/storage/viking_vector_index_backend.py b/openviking/storage/viking_vector_index_backend.pyindex 8b80f2e1f..344039be6 100644--- a/openviking/storage/viking_vector_index_backend.py+++ b/openviking/storage/viking_vector_index_backend.py@@ -44,7 +44,6 @@ MEMORY_DEDUP_OUTPUT_FIELDS = ["level","account_id","owner_user_id",- "owner_agent_id",]FETCH_BY_URI_OUTPUT_FIELDS = [@@ -61,7 +60,6 @@ FETCH_BY_URI_OUTPUT_FIELDS = ["abstract","account_id","owner_user_id",- "owner_agent_id",]URI_REWRITE_OUTPUT_FIELDS = [diff --git a/openviking/sync_client.py b/openviking/sync_client.pyindex e00f66df7..bd048bea2 100644--- a/openviking/sync_client.py+++ b/openviking/sync_client.py@@ -22,8 +22,8 @@ class SyncOpenViking:Wraps AsyncOpenViking with synchronous methods."""- def __init__(self, **kwargs):- self._async_client = AsyncOpenViking(**kwargs)+ def __init__(self, path: Optional[str] = None):+ self._async_client = AsyncOpenViking(path=path)self._initialized = Falsedef initialize(self) -> None:@@ -40,7 +40,10 @@ class SyncOpenViking:return run_async(self._async_client.session_exists(session_id))def create_session(- self, session_id: Optional[str] = None, telemetry: TelemetryRequest = False+ self,+ session_id: Optional[str] = None,+ telemetry: TelemetryRequest = False,+ memory_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Create a new session.@@ -48,7 +51,13 @@ class SyncOpenViking:session_id: Optional session ID. If provided, creates a session with the given ID.If None, creates a new session with auto-generated ID."""- return run_async(self._async_client.create_session(session_id, telemetry=telemetry))+ return run_async(+ self._async_client.create_session(+ session_id,+ telemetry=telemetry,+ memory_policy=memory_policy,+ )+ )def list_sessions(self) -> List[Any]:"""List all sessions."""@@ -79,7 +88,7 @@ class SyncOpenViking:content: str | None = None,parts: list[dict] | None = None,created_at: str | None = None,- role_id: str | None = None,+ peer_id: str | None = None,telemetry: TelemetryRequest = False,) -> Dict[str, Any]:"""Add a message to a session.@@ -90,19 +99,19 @@ class SyncOpenViking:content: Text content (simple mode)parts: Parts array (full Part support: TextPart, ContextPart, ToolPart)created_at: Message creation time (ISO format string). If not provided, current time is used.- role_id: Optional explicit actor identity. Omit to let the client/server derive it.+ peer_id: Optional stable interaction peer identity.If both content and parts are provided, parts takes precedence."""return run_async(self._async_client.add_message(- session_id,- role,- content,- parts,- created_at,- role_id,- telemetry,+ session_id=session_id,+ role=role,+ content=content,+ parts=parts,+ created_at=created_at,+ peer_id=peer_id,+ telemetry=telemetry,))@@ -127,6 +136,7 @@ class SyncOpenViking:telemetry: TelemetryRequest = False,*,keep_recent_count: int = 0,+ memory_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Commit a session (archive and extract memories)."""return run_async(@@ -134,6 +144,7 @@ class SyncOpenViking:session_id,telemetry=telemetry,keep_recent_count=keep_recent_count,+ memory_policy=memory_policy,))@@ -224,6 +235,7 @@ class SyncOpenViking:until: Optional[str] = None,time_field: Optional[str] = None,level: Optional[List[int]] = None,+ peer_id: Optional[str] = None,):"""Execute complex retrieval (intent analysis, hierarchical retrieval)."""return run_async(@@ -240,6 +252,7 @@ class SyncOpenViking:until=until,time_field=time_field,level=level,+ peer_id=peer_id,))@@ -255,6 +268,7 @@ class SyncOpenViking:until: Optional[str] = None,time_field: Optional[str] = None,level: Optional[List[int]] = None,+ peer_id: Optional[str] = None,):"""Quick retrieval"""return run_async(@@ -269,6 +283,7 @@ class SyncOpenViking:until,time_field,level,+ peer_id=peer_id,))diff --git a/openviking/telemetry/span_models.py b/openviking/telemetry/span_models.pyindex 0fe46446b..d1111912e 100644--- a/openviking/telemetry/span_models.py+++ b/openviking/telemetry/span_models.py@@ -66,9 +66,6 @@ class RootSpanAttributes:user_id: Optional[str] = None"""User identifier."""- agent_id: Optional[str] = None- """Agent identifier."""-def to_otel_attributes(self) -> Dict[str, Any]:"""Convert the model into an OpenTelemetry span attribute mapping."""attrs = {@@ -95,8 +92,6 @@ class RootSpanAttributes:attrs["account_id"] = self.account_idif self.user_id is not None:attrs["user_id"] = self.user_id- if self.agent_id is not None:- attrs["agent_id"] = self.agent_idreturn attrs@@ -113,8 +108,6 @@ class RootSpanAttributes:fields["account_id"] = self.account_idif self.user_id is not None:fields["user_id"] = self.user_id- if self.agent_id is not None:- fields["agent_id"] = self.agent_idreturn fieldsdef to_dict(self) -> Dict[str, Any]:@@ -334,7 +327,6 @@ def update_root_span_identity(request_state: Any,account_id: Optional[str] = None,user_id: Optional[str] = None,- agent_id: Optional[str] = None,) -> bool:"""Update identity fields on `RootSpanAttributes` and mirror them into the current span.@@ -356,8 +348,6 @@ def update_root_span_identity(root_attrs.account_id = account_idif user_id is not None:root_attrs.user_id = user_id- if agent_id is not None:- root_attrs.agent_id = agent_id# Best-effort sync into the active OTel span, if one exists.try:diff --git a/openviking/utils/skill_processor.py b/openviking/utils/skill_processor.pyindex fbe35dfb5..92092db2e 100644--- a/openviking/utils/skill_processor.py+++ b/openviking/utils/skill_processor.py@@ -17,7 +17,7 @@ import yamlfrom openviking.core.context import Context, ContextType, Vectorizefrom openviking.core.mcp_converter import is_mcp_format, mcp_to_skill-from openviking.core.namespace import agent_space_fragment, canonical_agent_root+from openviking.core.namespace import canonical_user_root, user_space_fragmentfrom openviking.core.skill_loader import SkillLoaderfrom openviking.privacy import (UserPrivacyConfigService,@@ -97,15 +97,16 @@ class SkillProcessor:skill_dict = await self.sanitize_skill_privacy(skill_dict, ctx)skill_abstract = self._build_skill_abstract(skill_dict)+ skill_root_uri = f"{canonical_user_root(ctx)}/skills"context = Context(- uri=f"{canonical_agent_root(ctx)}/skills/{skill_dict['name']}",- parent_uri=f"{canonical_agent_root(ctx)}/skills",+ uri=f"{skill_root_uri}/{skill_dict['name']}",+ parent_uri=skill_root_uri,is_leaf=False,abstract=skill_abstract,context_type=ContextType.SKILL.value,user=ctx.user,account_id=ctx.account_id,- owner_space=agent_space_fragment(ctx),+ owner_space=user_space_fragment(ctx),meta={"name": skill_dict["name"],"description": skill_dict.get("description", ""),diff --git a/openviking/utils/summarizer.py b/openviking/utils/summarizer.pyindex 1867969bf..744034129 100644--- a/openviking/utils/summarizer.py+++ b/openviking/utils/summarizer.py@@ -115,7 +115,7 @@ class Summarizer:context_type=context_type,account_id=ctx.account_id,user_id=ctx.user.user_id,- agent_id=ctx.user.agent_id,+ peer_id=ctx.user.user_id,role=ctx.role.value,skip_vectorization=skip_vectorization,telemetry_id=telemetry.telemetry_id,diff --git a/openviking_cli/client/base.py b/openviking_cli/client/base.pyindex 08cde9425..9dc394412 100644--- a/openviking_cli/client/base.py+++ b/openviking_cli/client/base.py@@ -168,6 +168,7 @@ class BaseClient(ABC):score_threshold: Optional[float] = None,filter: Optional[Dict] = None,telemetry: TelemetryRequest = False,+ peer_id: Optional[str] = None,) -> Any:"""Semantic search without session context."""...@@ -182,6 +183,7 @@ class BaseClient(ABC):score_threshold: Optional[float] = None,filter: Optional[Dict] = None,telemetry: TelemetryRequest = False,+ peer_id: Optional[str] = None,) -> Any:"""Semantic search with optional session context."""...@@ -224,7 +226,10 @@ class BaseClient(ABC):@abstractmethodasync def create_session(- self, session_id: Optional[str] = None, telemetry: TelemetryRequest = False+ self,+ session_id: Optional[str] = None,+ telemetry: TelemetryRequest = False,+ memory_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Create a new session.@@ -232,6 +237,7 @@ class BaseClient(ABC):session_id: Optional session ID. If provided, creates a session with the given ID.If None, creates a new session with auto-generated ID.telemetry: Whether to attach operation telemetry data to the result.+ memory_policy: Optional default memory extraction policy."""...@@ -269,6 +275,7 @@ class BaseClient(ABC):telemetry: TelemetryRequest = False,*,keep_recent_count: int = 0,+ memory_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Commit a session (archive and extract memories).@@ -276,6 +283,7 @@ class BaseClient(ABC):session_id: Session IDtelemetry: Whether to attach operation telemetry data to the result.keep_recent_count: Number of recent live messages to retain after commit.+ memory_policy: Optional per-commit extraction policy."""...@@ -287,7 +295,7 @@ class BaseClient(ABC):content: str | None = None,parts: list[dict] | None = None,created_at: str | None = None,- role_id: str | None = None,+ peer_id: str | None = None,telemetry: TelemetryRequest = False,) -> Dict[str, Any]:"""Add a message to a session.@@ -298,7 +306,7 @@ class BaseClient(ABC):content: Text content (simple mode)parts: Parts array (full Part support: TextPart, ContextPart, ToolPart)created_at: Message creation time (ISO format string)- role_id: Optional explicit actor identity. Omit to let the server derive it.+ peer_id: Optional stable interaction peer identity.telemetry: Whether to attach operation telemetry data to the result.If both content and parts are provided, parts takes precedence.@@ -317,7 +325,7 @@ class BaseClient(ABC):Args:session_id: Session IDmessages: List of message dicts, each with "role" and optionally- "content", "parts", "created_at", "role_id".+ "content", "parts", "created_at", "peer_id".telemetry: Whether to attach operation telemetry data to the result.Returns:diff --git a/openviking_cli/client/http.py b/openviking_cli/client/http.pyindex 1ec35fdff..db53bbdbc 100644--- a/openviking_cli/client/http.py+++ b/openviking_cli/client/http.py@@ -141,7 +141,6 @@ class AsyncHTTPClient(BaseClient):url: Optional[str] = None,api_key: Optional[str] = None,user_id: Optional[str] = None,- agent_id: Optional[str] = None,account: Optional[str] = None,user: Optional[str] = None,timeout: float = 60.0,@@ -154,11 +153,8 @@ class AsyncHTTPClient(BaseClient):url: OpenViking Server URL. If not provided, reads from ovcli.conf.api_key: API key for authentication. If not provided, reads from ovcli.conf.user_id: User identifier. If not provided, defaults to "default".- agent_id: Agent identifier. If not provided, reads from ovcli.conf.- account: Account identifier for multi-tenant auth. Required when using root key- to access tenant-scoped APIs. If not provided, reads from ovcli.conf.- user: User identifier for multi-tenant auth. Required when using root key- to access tenant-scoped APIs. If not provided, reads from ovcli.conf.+ account: Optional account identity header for trusted deployments.+ user: Optional user identity header for trusted deployments.timeout: HTTP request timeout in seconds. Default 60.0.extra_headers: Additional HTTP headers to send with requests. If not provided, reads from ovcli.conf."""@@ -167,7 +163,6 @@ class AsyncHTTPClient(BaseClient):should_load_cli_config = (url is Noneor api_key is None- or agent_id is Noneor account is Noneor effective_user is Noneor timeout == 60.0@@ -179,7 +174,6 @@ class AsyncHTTPClient(BaseClient):if cli_config is not None:url = url or cli_config.urlapi_key = api_key or cli_config.api_key- agent_id = agent_id or cli_config.agent_idaccount = account or cli_config.accounteffective_user = effective_user or cli_config.userif timeout == 60.0: # only override default with config value@@ -198,7 +192,6 @@ class AsyncHTTPClient(BaseClient):)self._url = url.rstrip("/")self._api_key = api_key- self._agent_id = agent_idself._account = accountself._user_id = effective_userself._user = UserIdentifier.the_default_user()@@ -218,8 +211,6 @@ class AsyncHTTPClient(BaseClient):headers = {}if self._api_key:headers["X-API-Key"] = self._api_key- if self._agent_id:- headers["X-OpenViking-Agent"] = self._agent_idif self._account:headers["X-OpenViking-Account"] = self._accountif self._user_id:@@ -465,7 +456,7 @@ class AsyncHTTPClient(BaseClient):Args:session_id: Session IDmessages: List of message dicts, each with "role" and optionally- "content", "parts", "created_at", "role_id".+ "content", "parts", "created_at", "peer_id".telemetry: Whether to attach operation telemetry data to the result.Returns:@@ -697,22 +688,23 @@ class AsyncHTTPClient(BaseClient):score_threshold: Optional[float] = None,filter: Optional[Dict[str, Any]] = None,telemetry: TelemetryRequest = False,+ peer_id: Optional[str] = None,) -> FindResult:"""Semantic search without session context."""telemetry = self._validate_telemetry(telemetry)normalized_target = self._normalize_target_uri(target_uri)actual_limit = node_limit if node_limit is not None else limit- response = await self._http.post(- "/api/v1/search/find",- json={- "query": query,- "target_uri": normalized_target,- "limit": actual_limit,- "score_threshold": score_threshold,- "filter": filter,- "telemetry": telemetry,- },- )+ payload = {+ "query": query,+ "target_uri": normalized_target,+ "limit": actual_limit,+ "score_threshold": score_threshold,+ "filter": filter,+ "telemetry": telemetry,+ }+ if peer_id is not None:+ payload["peer_id"] = peer_id+ response = await self._http.post("/api/v1/search/find", json=payload)response_data = self._handle_response_data(response)return FindResult.from_dict(response_data.get("result") or {})@@ -727,24 +719,25 @@ class AsyncHTTPClient(BaseClient):score_threshold: Optional[float] = None,filter: Optional[Dict[str, Any]] = None,telemetry: TelemetryRequest = False,+ peer_id: Optional[str] = None,) -> FindResult:"""Semantic search with optional session context."""telemetry = self._validate_telemetry(telemetry)normalized_target = self._normalize_target_uri(target_uri)actual_limit = node_limit if node_limit is not None else limitsid = session_id or (session.session_id if session else None)- response = await self._http.post(- "/api/v1/search/search",- json={- "query": query,- "target_uri": normalized_target,- "session_id": sid,- "limit": actual_limit,- "score_threshold": score_threshold,- "filter": filter,- "telemetry": telemetry,- },- )+ payload = {+ "query": query,+ "target_uri": normalized_target,+ "session_id": sid,+ "limit": actual_limit,+ "score_threshold": score_threshold,+ "filter": filter,+ "telemetry": telemetry,+ }+ if peer_id is not None:+ payload["peer_id"] = peer_id+ response = await self._http.post("/api/v1/search/search", json=payload)response_data = self._handle_response_data(response)return FindResult.from_dict(response_data.get("result") or {})@@ -820,7 +813,10 @@ class AsyncHTTPClient(BaseClient):# ============= Sessions =============async def create_session(- self, session_id: Optional[str] = None, telemetry: TelemetryRequest = False+ self,+ session_id: Optional[str] = None,+ telemetry: TelemetryRequest = False,+ memory_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Create a new session.@@ -832,6 +828,8 @@ class AsyncHTTPClient(BaseClient):json_body: Dict[str, Any] = {}if session_id is not None:json_body["session_id"] = session_id+ if memory_policy is not None:+ json_body["memory_policy"] = memory_policyif telemetry is not False:json_body["telemetry"] = telemetryresponse = await self._http.post(@@ -896,15 +894,19 @@ class AsyncHTTPClient(BaseClient):telemetry: TelemetryRequest = False,*,keep_recent_count: int = 0,+ memory_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Commit a session (archive and extract memories)."""telemetry = self._validate_telemetry(telemetry)+ payload: Dict[str, Any] = {+ "keep_recent_count": keep_recent_count,+ "telemetry": telemetry,+ }+ if memory_policy is not None:+ payload["memory_policy"] = memory_policyresponse = await self._http.post(f"/api/v1/sessions/{session_id}/commit",- json={- "keep_recent_count": keep_recent_count,- "telemetry": telemetry,- },+ json=payload,)response_data = self._handle_response_data(response)return self._attach_telemetry(response_data.get("result"), response_data)@@ -916,7 +918,7 @@ class AsyncHTTPClient(BaseClient):content: str | None = None,parts: list[dict] | None = None,created_at: str | None = None,- role_id: str | None = None,+ peer_id: str | None = None,telemetry: TelemetryRequest = False,) -> Dict[str, Any]:"""Add a message to a session.@@ -927,7 +929,7 @@ class AsyncHTTPClient(BaseClient):content: Text content (simple mode, backward compatible)parts: Parts array (full Part support mode)created_at: Message creation time (ISO format string)- role_id: Optional explicit actor identity. Omit to let the server derive it.+ peer_id: Optional stable interaction peer identity.If both content and parts are provided, parts takes precedence."""@@ -942,8 +944,8 @@ class AsyncHTTPClient(BaseClient):if created_at is not None:payload["created_at"] = created_at- if role_id is not None:- payload["role_id"] = role_id+ if peer_id is not None:+ payload["peer_id"] = peer_idif telemetry is not False:payload["telemetry"] = telemetrydiff --git a/openviking_cli/client/sync_http.py b/openviking_cli/client/sync_http.pyindex 1f330509b..6dad05bb8 100644--- a/openviking_cli/client/sync_http.py+++ b/openviking_cli/client/sync_http.py@@ -33,7 +33,6 @@ class SyncHTTPClient:url: Optional[str] = None,api_key: Optional[str] = None,user_id: Optional[str] = None,- agent_id: Optional[str] = None,account: Optional[str] = None,user: Optional[str] = None,timeout: float = 60.0,@@ -44,7 +43,6 @@ class SyncHTTPClient:url=url,api_key=api_key,user_id=user_id,- agent_id=agent_id,account=account,user=user,timeout=timeout,@@ -85,7 +83,10 @@ class SyncHTTPClient:return run_async(self._async_client.session_exists(session_id))def create_session(- self, session_id: Optional[str] = None, telemetry: TelemetryRequest = False+ self,+ session_id: Optional[str] = None,+ telemetry: TelemetryRequest = False,+ memory_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Create a new session.@@ -93,7 +94,13 @@ class SyncHTTPClient:session_id: Optional session ID. If provided, creates a session with the given ID.If None, creates a new session with auto-generated ID."""- return run_async(self._async_client.create_session(session_id, telemetry=telemetry))+ return run_async(+ self._async_client.create_session(+ session_id,+ telemetry=telemetry,+ memory_policy=memory_policy,+ )+ )def list_sessions(self) -> List[Any]:"""List all sessions."""@@ -122,7 +129,7 @@ class SyncHTTPClient:content: str | None = None,parts: list[dict] | None = None,created_at: str | None = None,- role_id: str | None = None,+ peer_id: str | None = None,telemetry: TelemetryRequest = False,) -> Dict[str, Any]:"""Add a message to a session.@@ -133,7 +140,7 @@ class SyncHTTPClient:content: Text content (simple mode)parts: Parts array (full Part support: TextPart, ContextPart, ToolPart)created_at: Message creation time (ISO format string)- role_id: Optional explicit actor identity. Omit to let the server derive it.+ peer_id: Optional stable interaction peer identity.If both content and parts are provided, parts takes precedence."""@@ -144,7 +151,7 @@ class SyncHTTPClient:content,parts,created_at,- role_id,+ peer_id,telemetry,))@@ -160,7 +167,7 @@ class SyncHTTPClient:Args:session_id: Session IDmessages: List of message dicts, each with "role" and optionally- "content", "parts", "created_at", "role_id".+ "content", "parts", "created_at", "peer_id".telemetry: Whether to attach operation telemetry data to the result.Returns:@@ -199,6 +206,7 @@ class SyncHTTPClient:telemetry: TelemetryRequest = False,*,keep_recent_count: int = 0,+ memory_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Commit a session (archive and extract memories)."""return run_async(@@ -206,6 +214,7 @@ class SyncHTTPClient:session_id,telemetry=telemetry,keep_recent_count=keep_recent_count,+ memory_policy=memory_policy,))@@ -279,6 +288,7 @@ class SyncHTTPClient:score_threshold: Optional[float] = None,filter: Optional[Dict] = None,telemetry: TelemetryRequest = False,+ peer_id: Optional[str] = None,):"""Semantic search with optional session context."""return run_async(@@ -292,6 +302,7 @@ class SyncHTTPClient:score_threshold=score_threshold,filter=filter,telemetry=telemetry,+ peer_id=peer_id,))@@ -304,6 +315,7 @@ class SyncHTTPClient:score_threshold: Optional[float] = None,filter: Optional[Dict] = None,telemetry: TelemetryRequest = False,+ peer_id: Optional[str] = None,):"""Semantic search without session context."""return run_async(@@ -315,6 +327,7 @@ class SyncHTTPClient:score_threshold,filter,telemetry=telemetry,+ peer_id=peer_id,))diff --git a/openviking_cli/session/user_id.py b/openviking_cli/session/user_id.pyindex a0a12e555..07c2c5576 100644--- a/openviking_cli/session/user_id.py+++ b/openviking_cli/session/user_id.py@@ -1,6 +1,4 @@-import hashlibimport re-from typing import Optionalfrom openviking_cli.utils import get_logger@@ -11,8 +9,8 @@ logger = get_logger(__name__)_VALIDATION_PATTERN = re.compile(r"^[a-zA-Z0-9_.@-]+$")-def validate_identifier_part(part: str, part_name: str) -> Optional[str]:- """Validate a single part of an identifier (account_id, user_id, or agent_id).+def validate_identifier_part(part: str, part_name: str) -> str | None:+ """Validate a single part of an identifier (account_id or user_id).Returns an error message if invalid, None if valid."""@@ -25,7 +23,7 @@ def validate_identifier_part(part: str, part_name: str) -> Optional[str]:return None-def validate_account_id(account_id: str) -> Optional[str]:+def validate_account_id(account_id: str) -> str | None:"""Validate an account_id. Returns an error message if invalid, None if valid."""verr = validate_identifier_part(account_id, "account_id")if verr:@@ -35,32 +33,26 @@ def validate_account_id(account_id: str) -> Optional[str]:return None-def validate_user_id(user_id: str) -> Optional[str]:+def validate_user_id(user_id: str) -> str | None:"""Validate a user_id. Returns an error message if invalid, None if valid."""return validate_identifier_part(user_id, "user_id")-def validate_agent_id(agent_id: str) -> Optional[str]:- """Validate an agent_id. Returns an error message if invalid, None if valid."""- return validate_identifier_part(agent_id, "agent_id")--class UserIdentifier(object):- def __init__(self, account_id: str, user_id: str, agent_id: str):+ def __init__(self, account_id: str, user_id: str):self._account_id = account_idself._user_id = user_id- self._agent_id = agent_idverr = self._validate_error()if verr:logger.error(- f"Invalid user identifier: {verr}. account_id={self._account_id} user_id={self._user_id} agent_id={self._agent_id}"+ f"Invalid user identifier: {verr}. account_id={self._account_id} user_id={self._user_id}")raise ValueError(verr)@classmethoddef the_default_user(cls, default_username: str = "default"):- return cls("default", default_username, "default")+ return cls("default", default_username)def _validate_error(self) -> str:"""Validate the user identifier using shared validation functions."""@@ -68,9 +60,6 @@ class UserIdentifier(object):if verr:return verrverr = validate_user_id(self._user_id)- if verr:- return verr- verr = validate_agent_id(self._agent_id)if verr:return verrreturn ""@@ -83,55 +72,31 @@ class UserIdentifier(object):def user_id(self) -> str:return self._user_id- @property- def agent_id(self) -> str:- return self._agent_id-def user_space_name(self) -> str:"""User-level space name."""return self._user_id- def _agent_space_source(self) -> str:- """Return the legacy source string used by deprecated hash-based agent helpers.-- This helper is kept only for backward-compatible tooling paths. Service-side- namespace resolution is now driven by per-account namespace policy instead.- """- return f"{self._user_id}:{self._agent_id}"-- def agent_space_name(self) -> str:- """Return the legacy hash-based agent space for backward-compatible helpers only.-- New server-side agent URIs no longer derive from this hash helper.- """- return hashlib.md5(self._agent_space_source().encode()).hexdigest()[:12]-def memory_space_uri(self) -> str:- return f"viking://agent/{self.agent_space_name()}/memories"+ return f"viking://user/{self.user_space_name()}/memories"def work_space_uri(self) -> str:- return f"viking://agent/{self.agent_space_name()}/workspaces"+ return f"viking://user/{self.user_space_name()}/workspaces"def to_dict(self):return {"account_id": self._account_id,"user_id": self._user_id,- "agent_id": self._agent_id,}@classmethoddef from_dict(cls, data: dict):- return cls(data["account_id"], data["user_id"], data["agent_id"])+ return cls(data["account_id"], data["user_id"])def __str__(self) -> str:- return f"{self._account_id}:{self._user_id}:{self._agent_id}"+ return f"{self._account_id}:{self._user_id}"def __repr__(self) -> str:return self.__str__()def __eq__(self, other):- return (- self._account_id == other._account_id- and self._user_id == other._user_id- and self._agent_id == other._agent_id- )+ return self._account_id == other._account_id and self._user_id == other._user_iddiff --git a/openviking_cli/utils/config/__init__.py b/openviking_cli/utils/config/__init__.pyindex 64a5a6489..3b760d7e8 100644--- a/openviking_cli/utils/config/__init__.py+++ b/openviking_cli/utils/config/__init__.py@@ -11,7 +11,6 @@ from .consts import (DEFAULT_OV_CONF,DEFAULT_OVCLI_CONF,OPENVIKING_ACCOUNT_ENV,- OPENVIKING_AGENT_ID_ENV,OPENVIKING_ALLOW_BREAK_SYSTEM_PACKAGES_ENV,OPENVIKING_API_KEY_ENV,OPENVIKING_ARK_API_KEY_ENV,@@ -98,7 +97,6 @@ __all__ = ["OPENVIKING_API_KEY_ENV","OPENVIKING_ACCOUNT_ENV","OPENVIKING_USER_ENV",- "OPENVIKING_AGENT_ID_ENV","OPENVIKING_EMBEDDING_API_KEY_ENV","OPENVIKING_VLM_API_KEY_ENV","OPENVIKING_ARK_API_KEY_ENV",diff --git a/openviking_cli/utils/config/consts.py b/openviking_cli/utils/config/consts.pyindex 67a3cfa12..883a02d9e 100644--- a/openviking_cli/utils/config/consts.py+++ b/openviking_cli/utils/config/consts.py@@ -24,7 +24,6 @@ OPENVIKING_ROOT_API_KEY_ENV = "OPENVIKING_ROOT_API_KEY"OPENVIKING_API_KEY_ENV = "OPENVIKING_API_KEY"OPENVIKING_ACCOUNT_ENV = "OPENVIKING_ACCOUNT"OPENVIKING_USER_ENV = "OPENVIKING_USER"-OPENVIKING_AGENT_ID_ENV = "OPENVIKING_AGENT_ID"# Embedding & VLMOPENVIKING_EMBEDDING_API_KEY_ENV = "OPENVIKING_EMBEDDING_API_KEY"diff --git a/openviking_cli/utils/config/memory_config.py b/openviking_cli/utils/config/memory_config.pyindex 70a3adc4c..91899e714 100644--- a/openviking_cli/utils/config/memory_config.py+++ b/openviking_cli/utils/config/memory_config.py@@ -12,14 +12,6 @@ class MemoryConfig(BaseModel):default="v2",description="Memory implementation version. Only 'v2' is supported.",)- agent_scope_mode: str = Field(- default="user+agent",- description=(- "Deprecated and ignored. Kept only for backward compatibility with older ov.conf files. "- "Agent/user namespace behavior is now controlled by per-account namespace policy."- ),- )-custom_templates_dir: str = Field(default="",description="Custom memory templates directory. If set, templates from this directory will be loaded in addition to built-in templates",@@ -43,7 +35,7 @@ class MemoryConfig(BaseModel):agent_memory_enabled: bool = Field(default=False,description=(- "Enable agent-scope trajectory/experience memory extraction. When true, "+ "Enable trajectory/experience memory extraction. When true, ""a two-phase pipeline runs after user-memory extraction: Phase 1 extracts ""execution trajectories from the conversation; Phase 2 consolidates them ""into higher-level experience memories."@@ -87,18 +79,10 @@ class MemoryConfig(BaseModel):default=False,description=("When enabled, session commit also extracts reusable skills from the archived "- "conversation and writes them into the agent skill directory. Disabled by "+ "conversation and writes them into the current user's skill directory. Disabled by ""default."),)- role_id_memory_isolation_enabled: bool = Field(- default=False,- description=(- "When enabled, memory extraction uses role_id from messages to determine "- "which user/agent the memory belongs to. When disabled (default), role_id "- "is ignored and the login user from the request context is used instead."- ),- )link_enabled: bool = Field(default=False,description=(@@ -118,13 +102,6 @@ class MemoryConfig(BaseModel):data.setdefault("agent_memory_enabled", True)return data- @field_validator("agent_scope_mode")- @classmethod- def validate_agent_scope_mode(cls, value: str) -> str:- if value not in {"user+agent", "agent"}:- raise ValueError("memory.agent_scope_mode must be 'user+agent' or 'agent'")- return value-@field_validator("version")@classmethoddef validate_version(cls, value: str) -> str:diff --git a/openviking_cli/utils/config/open_viking_config.py b/openviking_cli/utils/config/open_viking_config.pyindex 05d7958f9..6eda9d3eb 100644--- a/openviking_cli/utils/config/open_viking_config.py+++ b/openviking_cli/utils/config/open_viking_config.py@@ -57,7 +57,10 @@ class OpenVikingConfig(BaseModel):default="default", description="Default account identifier")default_user: Optional[str] = Field(default="default", description="Default user identifier")- default_agent: Optional[str] = Field(default="default", description="Default agent identifier")+ default_agent: Optional[str] = Field(+ default=None,+ description="Deprecated and ignored. User is the only data-plane identity.",+ )storage: StorageConfig = Field(default_factory=StorageConfig, description="Storage configuration"@@ -262,16 +265,16 @@ class OpenVikingConfig(BaseModel):# Apply memory configurationif memory_config_data is not None:- if (- isinstance(memory_config_data, dict)- and "agent_scope_mode" in memory_config_data- ):- _get_config_warning_logger().warning(- "memory.agent_scope_mode is deprecated and ignored. "- "User/agent namespace behavior is now controlled by per-account "- "namespace policy."- )- instance.memory = MemoryConfig.from_dict(memory_config_data)+ try:+ instance.memory = MemoryConfig.from_dict(memory_config_data)+ except ValidationError as e:+ raise ValueError(+ format_validation_error(+ root_model=MemoryConfig,+ error=e,+ path_prefix="memory",+ )+ ) from e# Apply parser configurationsfor parser_type, parser_data in parser_configs.items():@@ -502,7 +505,6 @@ def initialize_openviking_config(# Set user if provided, like a email address or a account_idconfig.default_account = user._account_idconfig.default_user = user._user_id- config.default_agent = user._agent_id# Configure storage based on provided parametersif path:diff --git a/openviking_cli/utils/config/ovcli_config.py b/openviking_cli/utils/config/ovcli_config.pyindex 5522446a5..703558c3b 100644--- a/openviking_cli/utils/config/ovcli_config.py+++ b/openviking_cli/utils/config/ovcli_config.py@@ -28,7 +28,6 @@ class OVCLIConfig(BaseModel):url: Optional[str] = Noneapi_key: Optional[str] = None- agent_id: Optional[str] = Noneaccount: Optional[str] = Noneuser: Optional[str] = Nonetimeout: float = 60.0diff --git a/openviking_cli/utils/logger.py b/openviking_cli/utils/logger.pyindex 1a6fb0589..3f7ba8ecf 100644--- a/openviking_cli/utils/logger.py+++ b/openviking_cli/utils/logger.py@@ -85,7 +85,6 @@ def _get_log_context() -> dict[str, Any]:"operation": "","account_id": "","user_id": "",- "agent_id": "",}# 1. Get trace_id and span_id from OTel span if available@@ -422,7 +421,6 @@ class TraceContextFilter(logging.Filter):record.operation = context.get("operation", "")record.account_id = context.get("account_id", "")record.user_id = context.get("user_id", "")- record.agent_id = context.get("agent_id", "")return True@@ -525,7 +523,6 @@ class LogToSpanEventFilter(logging.Filter):"operation","account_id","user_id",- "agent_id",}for key, value in record.__dict__.items():diff --git a/openviking_cli/utils/uri.py b/openviking_cli/utils/uri.pyindex 5febbefc0..da216e46e 100644--- a/openviking_cli/utils/uri.py+++ b/openviking_cli/utils/uri.py@@ -20,14 +20,13 @@ class VikingURI:Scopes:- resources: Independent resource scope (viking://resources/{project}/...)- user: User scope (viking://user/...)- - agent: Agent scope (viking://agent/...)- session: Session scope (viking://session/{session_id}/...)- queue: Queue scope (viking://queue/...)Examples:- viking://resources/my_project/docs/api- viking://user/memories/preferences/code_style- - viking://agent/skills/pdf+ - viking://user/skills/pdf- viking://session/session123/messages"""@@ -36,7 +35,6 @@ class VikingURI:LISTABLE_SCOPES = {"resources","user",- "agent","session",}PUBLIC_SCOPES = frozenset(LISTABLE_SCOPES)@@ -189,7 +187,7 @@ class VikingURI:Build a Viking URI from components.Args:- scope: Scope (resources, user, agent, session, queue, temp)+ scope: Scope (resources, user, session, queue, temp)*path_parts: Additional path componentsReturns:diff --git a/tests/api_test/api/client.py b/tests/api_test/api/client.pyindex f87258662..a8c16bb91 100644--- a/tests/api_test/api/client.py+++ b/tests/api_test/api/client.py@@ -17,16 +17,18 @@ class OpenVikingAPIClient:base_url: Optional[str] = None,server_url: Optional[str] = None,api_key: Optional[str] = None,+ root_api_key: Optional[str] = None,account: Optional[str] = None,user: Optional[str] = None,- agent: Optional[str] = None,+ send_identity_headers: bool = False,):self.base_url = base_url or Config.CONSOLE_URLself.server_url = server_url or Config.SERVER_URLself.api_key = api_key or Config.OPENVIKING_API_KEY+ self.root_api_key = root_api_key or Config.OPENVIKING_ROOT_API_KEYself.account = account or Config.OPENVIKING_ACCOUNTself.user = user or Config.OPENVIKING_USER- self.agent = agent or Config.OPENVIKING_AGENT+ self.send_identity_headers = send_identity_headersself.session = requests.Session()self._setup_default_headers()self.max_retries = 3@@ -61,8 +63,13 @@ class OpenVikingAPIClient:return datadef _request_with_retry(self, method: str, url: str, **kwargs) -> requests.Response:- filtered_headers = self._filter_sensitive_headers(dict(self.session.headers))- filtered_kwargs = self._filter_sensitive_data(kwargs)+ request_headers = dict(self.session.headers)+ if kwargs.get("headers"):+ request_headers.update(kwargs["headers"])+ filtered_headers = self._filter_sensitive_headers(request_headers)+ filtered_kwargs = self._filter_sensitive_data(+ {key: value for key, value in kwargs.items() if key != "headers"}+ )self.last_request_info = {"method": method,@@ -108,14 +115,19 @@ class OpenVikingAPIClient:"Connection": "keep-alive","Content-Type": "application/json","User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",- "X-OpenViking-Account": self.account,- "X-OpenViking-User": self.user,- "X-OpenViking-Agent": self.agent,}+ if self.send_identity_headers:+ headers["X-OpenViking-Account"] = self.account+ headers["X-OpenViking-User"] = self.userif self.api_key:headers["Authorization"] = f"Bearer {self.api_key}"self.session.headers.update(headers)+ def _admin_headers(self) -> Dict[str, str]:+ if not self.root_api_key:+ return {}+ return {"Authorization": f"Bearer {self.root_api_key}"}+def _build_url(self, base: str, endpoint: str, params: Optional[Dict[str, Any]] = None) -> str:url = f"{base}{endpoint}"if params:@@ -162,12 +174,15 @@ class OpenVikingAPIClient:limit: int = 10,score_threshold: Optional[float] = None,filter: Optional[Dict[str, Any]] = None,+ peer_id: Optional[str] = None,) -> requests.Response:endpoint = "/api/v1/search/find"url = self._build_url(self.server_url, endpoint)payload = {"query": query, "limit": limit}if target_uri:payload["target_uri"] = target_uri+ if peer_id is not None:+ payload["peer_id"] = peer_idif score_threshold is not None:payload["score_threshold"] = score_thresholdif filter:@@ -182,6 +197,7 @@ class OpenVikingAPIClient:limit: int = 10,score_threshold: Optional[float] = None,filter: Optional[Dict[str, Any]] = None,+ peer_id: Optional[str] = None,) -> requests.Response:endpoint = "/api/v1/search/search"url = self._build_url(self.server_url, endpoint)@@ -190,6 +206,8 @@ class OpenVikingAPIClient:payload["target_uri"] = target_uriif session_id:payload["session_id"] = session_id+ if peer_id is not None:+ payload["peer_id"] = peer_idif score_threshold is not None:payload["score_threshold"] = score_thresholdif filter:@@ -326,13 +344,13 @@ class OpenVikingAPIClient:session_id: str,role: str,content: str,- role_id: Optional[str] = None,+ peer_id: Optional[str] = None,) -> requests.Response:endpoint = f"/api/v1/sessions/{session_id}/messages"url = self._build_url(self.server_url, endpoint)payload = {"role": role, "content": content}- if role_id is not None:- payload["role_id"] = role_id+ if peer_id is not None:+ payload["peer_id"] = peer_idreturn self._request_with_retry("POST", url, json=payload)def fs_ls(self, uri: str, simple: bool = False, recursive: bool = False) -> requests.Response:@@ -558,45 +576,52 @@ class OpenVikingAPIClient:endpoint = "/api/v1/admin/accounts"url = self._build_url(self.server_url, endpoint)return self._request_with_retry(- "POST", url, json={"account_id": account_id, "admin_user_id": admin_user_id}+ "POST",+ url,+ json={"account_id": account_id, "admin_user_id": admin_user_id},+ headers=self._admin_headers(),)def admin_list_accounts(self) -> requests.Response:endpoint = "/api/v1/admin/accounts"url = self._build_url(self.server_url, endpoint)- return self._request_with_retry("GET", url)+ return self._request_with_retry("GET", url, headers=self._admin_headers())def admin_delete_account(self, account_id: str) -> requests.Response:endpoint = f"/api/v1/admin/accounts/{account_id}"url = self._build_url(self.server_url, endpoint)- return self._request_with_retry("DELETE", url)+ return self._request_with_retry("DELETE", url, headers=self._admin_headers())def admin_register_user(self, account_id: str, user_id: str, role: str = "user") -> requests.Response:endpoint = f"/api/v1/admin/accounts/{account_id}/users"url = self._build_url(self.server_url, endpoint)- return self._request_with_retry("POST", url, json={"user_id": user_id, "role": role})+ return self._request_with_retry(+ "POST", url, json={"user_id": user_id, "role": role}, headers=self._admin_headers()+ )def admin_list_users(self, account_id: str) -> requests.Response:endpoint = f"/api/v1/admin/accounts/{account_id}/users"url = self._build_url(self.server_url, endpoint)- return self._request_with_retry("GET", url)+ return self._request_with_retry("GET", url, headers=self._admin_headers())def admin_remove_user(self, account_id: str, user_id: str) -> requests.Response:endpoint = f"/api/v1/admin/accounts/{account_id}/users/{user_id}"url = self._build_url(self.server_url, endpoint)- return self._request_with_retry("DELETE", url)+ return self._request_with_retry("DELETE", url, headers=self._admin_headers())def admin_set_role(self, account_id: str, user_id: str, role: str) -> requests.Response:endpoint = f"/api/v1/admin/accounts/{account_id}/users/{user_id}/role"url = self._build_url(self.server_url, endpoint)- return self._request_with_retry("PUT", url, json={"role": role})+ return self._request_with_retry(+ "PUT", url, json={"role": role}, headers=self._admin_headers()+ )def admin_regenerate_key(self, account_id: str, user_id: str) -> requests.Response:endpoint = f"/api/v1/admin/accounts/{account_id}/users/{user_id}/key"url = self._build_url(self.server_url, endpoint)- return self._request_with_retry("POST", url, json={})+ return self._request_with_retry("POST", url, json={}, headers=self._admin_headers())def add_skill(self, data: Any, wait: bool = False, timeout: Optional[float] = Nonediff --git a/tests/api_test/common/test_edge_cases.py b/tests/api_test/common/test_edge_cases.pyindex 6571dfd34..fcb068ab1 100644--- a/tests/api_test/common/test_edge_cases.py+++ b/tests/api_test/common/test_edge_cases.py@@ -60,7 +60,7 @@ class TestResourceEdgeCases:f.write("scope test")resp = api_client.add_resource(- path=test_file, to="viking://agent/skills/invalid", wait=False+ path=test_file, to="viking://user/skills/invalid", wait=False)assert resp.status_code == 400, (f"adding resource to non-resources scope should return 400, got {resp.status_code}: {resp.text[:200]}"diff --git a/tests/api_test/conftest.py b/tests/api_test/conftest.pyindex 708e69d16..95e00811b 100644--- a/tests/api_test/conftest.py+++ b/tests/api_test/conftest.py@@ -299,37 +299,89 @@ def get_test_category(nodeid):return "其他"+def _extract_user_key(users, user_id):+ for user in users:+ if isinstance(user, dict) and user.get("user_id") == user_id:+ return user.get("api_key")+ return None+++def _ensure_api_test_user_key(root_client, account_id: str, user_id: str) -> str:+ resp = root_client.admin_list_users(account_id)+ if resp.status_code == 404:+ create_resp = root_client.admin_create_account(account_id, user_id)+ if create_resp.status_code in (200, 201):+ data = create_resp.json()+ user_key = data.get("result", {}).get("user_key")+ if user_key:+ print(f"已创建测试账户和用户 {account_id}/{user_id}")+ return user_key+ print(f"创建测试账户失败({create_resp.status_code}): {create_resp.text[:200]}")+ return Config.OPENVIKING_API_KEY++ if resp.status_code != 200:+ print(f"无法查询用户列表({resp.status_code}), 使用配置的 API Key: {resp.text[:200]}")+ return Config.OPENVIKING_API_KEY++ users = resp.json().get("result", [])+ user_key = _extract_user_key(users, user_id)+ if user_key:+ print(f"复用测试用户 {account_id}/{user_id}")+ return user_key++ user_exists = any(+ (isinstance(u, dict) and u.get("user_id") == user_id)+ or (isinstance(u, str) and u == user_id)+ for u in users+ )+ if not user_exists:+ reg_resp = root_client.admin_register_user(account_id, user_id, role="admin")+ if reg_resp.status_code in (200, 201):+ data = reg_resp.json()+ user_key = data.get("result", {}).get("user_key")+ if user_key:+ print(f"已注册测试用户 {account_id}/{user_id}")+ return user_key+ print(f"注册测试用户失败({reg_resp.status_code}): {reg_resp.text[:200]}")+ return Config.OPENVIKING_API_KEY++ role_resp = root_client.admin_set_role(account_id, user_id, "admin")+ if role_resp.status_code != 200:+ print(f"设置测试用户角色失败({role_resp.status_code}): {role_resp.text[:200]}")++ key_resp = root_client.admin_regenerate_key(account_id, user_id)+ if key_resp.status_code == 200:+ user_key = key_resp.json().get("result", {}).get("user_key")+ if user_key:+ print(f"已刷新测试用户 API Key {account_id}/{user_id}")+ return user_key++ print(f"刷新测试用户 API Key 失败({key_resp.status_code}): {key_resp.text[:200]}")+ return Config.OPENVIKING_API_KEY++@pytest.fixture(scope="session")def api_client():- client = OpenVikingAPIClient(server_url=Config.SERVER_URL, api_key=Config.OPENVIKING_API_KEY)-account_id = Config.OPENVIKING_ACCOUNTuser_id = Config.OPENVIKING_USER+ root_key = Config.OPENVIKING_ROOT_API_KEY+ root_client = OpenVikingAPIClient(+ server_url=Config.SERVER_URL,+ api_key=root_key,+ root_api_key=root_key,+ )try:- resp = client.admin_list_users(account_id)- if resp.status_code == 200:- data = resp.json()- users = data.get("result", [])- user_exists = any(- (isinstance(u, dict) and u.get("user_id") == user_id)- or (isinstance(u, str) and u == user_id)- for u in users- )- if not user_exists:- reg_resp = client.admin_register_user(account_id, user_id, role="admin")- if reg_resp.status_code in (200, 201):- print(f"已注册用户 {account_id}/{user_id}")- else:- print(f"注册用户失败({reg_resp.status_code}): {reg_resp.text[:200]}")- else:- print(f"用户 {account_id}/{user_id} 已存在")- else:- print(f"无法查询用户列表({resp.status_code}), 跳过用户注册(可能为开发模式)")+ api_key = _ensure_api_test_user_key(root_client, account_id, user_id)except Exception as e:print(f"用户注册检查异常, 跳过: {e}")+ api_key = Config.OPENVIKING_API_KEY- return client+ return OpenVikingAPIClient(+ server_url=Config.SERVER_URL,+ api_key=api_key,+ root_api_key=root_key,+ )@pytest.fixture(scope="session", autouse=True)diff --git a/tests/api_test/sessions/slow/test_session_detail_fields.py b/tests/api_test/sessions/slow/test_session_detail_fields.pyindex 139fb5e47..ba894dfd2 100644--- a/tests/api_test/sessions/slow/test_session_detail_fields.py+++ b/tests/api_test/sessions/slow/test_session_detail_fields.py@@ -223,9 +223,6 @@ class TestSessionDetailFields:assert isinstance(result.get("participant_user_ids"), (list, type(None))), ("participant_user_ids should be a list or None")- assert isinstance(result.get("participant_agent_ids"), (list, type(None))), (- "participant_agent_ids should be a list or None"- )finally:if session_id:api_client.delete_session(session_id)diff --git a/tests/api_test/sessions/slow/test_session_message_format.py b/tests/api_test/sessions/slow/test_session_message_format.pyindex a8efc6cf8..cc4a60ebf 100644--- a/tests/api_test/sessions/slow/test_session_message_format.py+++ b/tests/api_test/sessions/slow/test_session_message_format.py@@ -257,7 +257,7 @@ class TestSessionMessageFormat:used_resp = api_client.session_used(session_id,- skill={"name": "test-skill", "uri": "viking://agent/skills/test"},+ skill={"name": "test-skill", "uri": "viking://user/skills/test"},)assert used_resp.status_code == 200result = used_resp.json().get("result", {})diff --git a/tests/api_test/sessions/test_session_commit_used_context.py b/tests/api_test/sessions/test_session_commit_used_context.pyindex b7fb8f7dd..39b60d29c 100644--- a/tests/api_test/sessions/test_session_commit_used_context.py+++ b/tests/api_test/sessions/test_session_commit_used_context.py@@ -110,9 +110,9 @@ class TestSessionCommitUsedContext:contexts=["viking://resources/context1","viking://resources/context2",- "viking://agent/skills/skill1",+ "viking://user/skills/skill1",],- skill={"name": "multi-context-skill", "uri": "viking://agent/skills/multi"},+ skill={"name": "multi-context-skill", "uri": "viking://user/skills/multi"},)assert used_resp.status_code == 200data = used_resp.json()diff --git a/tests/api_test/sessions/test_session_messages.py b/tests/api_test/sessions/test_session_messages.pyindex 43feb2fef..d03298c0b 100644--- a/tests/api_test/sessions/test_session_messages.py+++ b/tests/api_test/sessions/test_session_messages.py@@ -371,18 +371,18 @@ class TestSessionMessages:if session_id:api_client.delete_session(session_id)- def test_message_role_id_field(self, api_client):+ def test_message_peer_id_field(self, api_client):session_id = Nonetry:r = api_client.create_session()session_id = r.json()["result"]["session_id"]- api_client.add_message(session_id, "user", "Role ID test")+ api_client.add_message(session_id, "user", "Peer ID test", peer_id="web_user_1")ctx = api_client.get_session_context(session_id, token_budget=128000)messages = ctx.json().get("result", {}).get("messages", [])for msg in messages:- if "role_id" in msg:- assert isinstance(msg["role_id"], str)+ if "peer_id" in msg:+ assert isinstance(msg["peer_id"], str)finally:if session_id:api_client.delete_session(session_id)diff --git a/tests/api_test/tasks/slow/test_task_skill_scenarios.py b/tests/api_test/tasks/slow/test_task_skill_scenarios.pyindex cafb3411c..be4763401 100644--- a/tests/api_test/tasks/slow/test_task_skill_scenarios.py+++ b/tests/api_test/tasks/slow/test_task_skill_scenarios.py@@ -97,4 +97,4 @@ class TestSkillBusinessScenarios:assert resp.status_code == 200result = resp.json().get("result", {})uri = result.get("uri", "")- assert uri.startswith("viking://agent/default/skills/"), f"skill uri format: {uri}"+ assert uri.startswith("viking://user/default/skills/"), f"skill uri format: {uri}"diff --git a/tests/api_test/tools/config/config.py b/tests/api_test/tools/config/config.pyindex e21417a76..dd4e9faac 100644--- a/tests/api_test/tools/config/config.py+++ b/tests/api_test/tools/config/config.py@@ -11,9 +11,9 @@ class Config:CONSOLE_URL = f"http://{CONSOLE_HOST}:{CONSOLE_PORT}"OPENVIKING_API_KEY = os.getenv("OPENVIKING_API_KEY", "test-root-api-key")+ OPENVIKING_ROOT_API_KEY = os.getenv("OPENVIKING_ROOT_API_KEY", OPENVIKING_API_KEY)OPENVIKING_ACCOUNT = os.getenv("OPENVIKING_ACCOUNT", "default")OPENVIKING_USER = os.getenv("OPENVIKING_USER", "default")- OPENVIKING_AGENT = os.getenv("OPENVIKING_AGENT", "default")SERVER_STARTUP_TIMEOUT = 30CONSOLE_STARTUP_TIMEOUT = 30diff --git a/tests/api_test/tools/tests/test_logger.py b/tests/api_test/tools/tests/test_logger.pyindex 40049cd93..73799d199 100644--- a/tests/api_test/tools/tests/test_logger.py+++ b/tests/api_test/tools/tests/test_logger.py@@ -72,7 +72,6 @@ def test_trace_context_filter_injects_root_observability_fields_without_span():root = RootSpanAttributes(http_method="GET", http_route="/demo", request_id="req-1")root.account_id = "acct-1"root.user_id = "user-1"- root.agent_id = "agent-1"token = bind_root_observability_context(root)try:passed = TraceContextFilter().filter(record)@@ -83,7 +82,6 @@ def test_trace_context_filter_injects_root_observability_fields_without_span():assert record.request_id == "req-1"assert record.account_id == "acct-1"assert record.user_id == "user-1"- assert record.agent_id == "agent-1"def test_trace_context_filter_injects_operation_observability_fields_without_span():diff --git a/tests/cli/conftest.py b/tests/cli/conftest.pyindex 380784cde..1036b86f7 100644--- a/tests/cli/conftest.py+++ b/tests/cli/conftest.py@@ -120,7 +120,113 @@ BASE_URL = os.getenv("OPENVIKING_URL",os.getenv("SERVER_URL", "https://api.vikingdb.cn-beijing.volces.com/openviking"),)-API_KEY = os.getenv("OPENVIKING_API_KEY", "")+CONFIGURED_API_KEY = os.getenv("OPENVIKING_API_KEY", "")+ROOT_API_KEY = os.getenv("OPENVIKING_ROOT_API_KEY", "")+TRUSTED_IDENTITY_HEADERS = os.getenv("OPENVIKING_TRUSTED_IDENTITY_HEADERS", "").lower() in (+ "1",+ "true",+ "yes",+)+CLI_ACCOUNT = os.getenv("OPENVIKING_ACCOUNT", "") if TRUSTED_IDENTITY_HEADERS else ""+CLI_USER = os.getenv("OPENVIKING_USER", "") if TRUSTED_IDENTITY_HEADERS else ""+++def _admin_headers() -> dict[str, str]:+ if not ROOT_API_KEY:+ return {}+ return {"Authorization": f"Bearer {ROOT_API_KEY}"}+++def _extract_user_key(users: list[object], user_id: str) -> str:+ for user in users:+ if isinstance(user, dict) and user.get("user_id") == user_id:+ api_key = user.get("api_key")+ if isinstance(api_key, str):+ return api_key+ return ""+++def _resolve_api_key() -> str:+ explicit_user_key = os.getenv("OPENVIKING_CLI_TEST_API_KEY") or os.getenv(+ "OPENVIKING_USER_API_KEY", ""+ )+ if explicit_user_key:+ return explicit_user_key+ if not ROOT_API_KEY:+ return CONFIGURED_API_KEY++ account_id = CLI_ACCOUNT or "test-account"+ user_id = CLI_USER or "test-user"+ try:+ list_resp = httpx.get(+ f"{BASE_URL}/api/v1/admin/accounts/{account_id}/users",+ headers=_admin_headers(),+ timeout=10.0,+ )+ if list_resp.status_code == 404:+ create_resp = httpx.post(+ f"{BASE_URL}/api/v1/admin/accounts",+ headers=_admin_headers(),+ json={"account_id": account_id, "admin_user_id": user_id},+ timeout=10.0,+ )+ if create_resp.status_code in (200, 201):+ user_key = create_resp.json().get("result", {}).get("user_key")+ if isinstance(user_key, str) and user_key:+ return user_key+ return CONFIGURED_API_KEY++ if list_resp.status_code != 200:+ return CONFIGURED_API_KEY++ users = list_resp.json().get("result", [])+ if isinstance(users, list):+ user_key = _extract_user_key(users, user_id)+ if user_key:+ return user_key+ user_exists = any(+ (isinstance(user, dict) and user.get("user_id") == user_id)+ or (isinstance(user, str) and user == user_id)+ for user in users+ )+ else:+ user_exists = False++ if not user_exists:+ register_resp = httpx.post(+ f"{BASE_URL}/api/v1/admin/accounts/{account_id}/users",+ headers=_admin_headers(),+ json={"user_id": user_id, "role": "admin"},+ timeout=10.0,+ )+ if register_resp.status_code in (200, 201):+ user_key = register_resp.json().get("result", {}).get("user_key")+ if isinstance(user_key, str) and user_key:+ return user_key+ return CONFIGURED_API_KEY++ httpx.put(+ f"{BASE_URL}/api/v1/admin/accounts/{account_id}/users/{user_id}/role",+ headers=_admin_headers(),+ json={"role": "admin"},+ timeout=10.0,+ )+ key_resp = httpx.post(+ f"{BASE_URL}/api/v1/admin/accounts/{account_id}/users/{user_id}/key",+ headers=_admin_headers(),+ json={},+ timeout=10.0,+ )+ if key_resp.status_code == 200:+ user_key = key_resp.json().get("result", {}).get("user_key")+ if isinstance(user_key, str) and user_key:+ return user_key+ except Exception:+ pass+ return CONFIGURED_API_KEY+++API_KEY = _resolve_api_key()def _resolve_bin():@@ -164,13 +270,15 @@ def _write_cli_config():config = {"url": BASE_URL,"api_key": API_KEY,- "account": "test-account",- "user": "test-user","timeout": 120.0,"output": "table","echo_command": True,"upload": {},}+ if CLI_ACCOUNT:+ config["account"] = CLI_ACCOUNT+ if CLI_USER:+ config["user"] = CLI_USERwith open(config_path, "w", encoding="utf-8") as f:json.dump(config, f, indent=2)return config_path@@ -255,10 +363,6 @@ def _parse_cli_json(stdout):return None-CLI_ACCOUNT = os.getenv("OPENVIKING_ACCOUNT", "test-account")-CLI_USER = os.getenv("OPENVIKING_USER", "test-user")--def _inject_global_args(args):global_args = []if CLI_ACCOUNT:diff --git a/tests/cli/test_cli_skills.py b/tests/cli/test_cli_skills.pyindex 16346183d..f1a6341c5 100644--- a/tests/cli/test_cli_skills.py+++ b/tests/cli/test_cli_skills.py@@ -73,7 +73,7 @@ class TestSkillAdd:class TestSkillList:def test_list_skills(self):- r = ov(["ls", "viking://agent/skills/", "-o", "json"])+ r = ov(["ls", "viking://user/skills/", "-o", "json"])assert r["exit_code"] == 0, (f"ov ls skills should exit 0, got {r['exit_code']}: {r['stderr'][:300]}")@@ -85,7 +85,7 @@ class TestSkillList:class TestSkillRead:def test_read_skill(self):- ls_r = ov(["ls", "viking://agent/skills/", "-o", "json"])+ ls_r = ov(["ls", "viking://user/skills/", "-o", "json"])if ls_r["exit_code"] != 0 or not ls_r["json"] or not ls_r["json"].get("result"):pytest.skip("No skills available to test read")returndiff --git a/tests/cli/test_user_identifier.py b/tests/cli/test_user_identifier.pyindex 90049f7cc..73464061c 100644--- a/tests/cli/test_user_identifier.py+++ b/tests/cli/test_user_identifier.py@@ -1,44 +1,24 @@-"""Tests for UserIdentifier, specifically agent_space_name collision safety."""+"""Tests for account/user-only UserIdentifier."""from openviking_cli.session.user_id import UserIdentifier-from openviking_cli.utils.config import OpenVikingConfigSingleton-class TestAgentSpaceNameCollision:- """Verify that agent_space_name uses a separator to prevent hash collisions."""+class TestUserIdentifier:+ """Verify that UserIdentifier is keyed by account/user only."""- def test_different_pairs_produce_different_hashes(self):- """Pairs like (alice, bot) vs (aliceb, ot) must not collide."""- u1 = UserIdentifier("acct", "alice", "bot")- u2 = UserIdentifier("acct", "aliceb", "ot")- assert u1.agent_space_name() != u2.agent_space_name()+ def test_same_user_produces_same_space(self):+ u1 = UserIdentifier("acct", "alice")+ u2 = UserIdentifier("acct", "alice")+ assert u1.user_space_name() == u2.user_space_name()+ assert u1 == u2- def test_same_pair_produces_same_hash(self):- """Same (user_id, agent_id) must always produce the same hash."""- u1 = UserIdentifier("acct", "alice", "bot")- u2 = UserIdentifier("acct", "alice", "bot")- assert u1.agent_space_name() == u2.agent_space_name()+ def test_different_users_produce_different_spaces(self):+ u1 = UserIdentifier("acct", "alpha")+ u2 = UserIdentifier("acct", "beta")+ assert u1.user_space_name() != u2.user_space_name()- def test_swapped_ids_produce_different_hashes(self):- """(user_id=a, agent_id=b) vs (user_id=b, agent_id=a) must differ."""- u1 = UserIdentifier("acct", "alpha", "beta")- u2 = UserIdentifier("acct", "beta", "alpha")- assert u1.agent_space_name() != u2.agent_space_name()-- def test_hash_length(self):- """agent_space_name must return a 12-character hex string."""- u = UserIdentifier("acct", "user1", "agent1")- name = u.agent_space_name()- assert len(name) == 12- assert all(c in "0123456789abcdef" for c in name)-- def test_agent_scope_mode_is_ignored(self):- """Deprecated memory.agent_scope_mode no longer changes agent_space_name."""- OpenVikingConfigSingleton.reset_instance()- OpenVikingConfigSingleton.initialize(config_dict={"memory": {"agent_scope_mode": "agent"}})-- u1 = UserIdentifier("acct", "alice", "bot")- u2 = UserIdentifier("acct", "bob", "bot")- assert u1.agent_space_name() != u2.agent_space_name()-- OpenVikingConfigSingleton.reset_instance()+ def test_memory_space_uri_uses_user_space(self):+ u = UserIdentifier("acct", "user1")+ assert u.user_space_name() == "user1"+ assert u.memory_space_uri() == "viking://user/user1/memories"+ assert u.to_dict() == {"account_id": "acct", "user_id": "user1"}diff --git a/tests/client/test_http_client_config.py b/tests/client/test_http_client_config.pyindex 88195238f..ede7dfc95 100644--- a/tests/client/test_http_client_config.py+++ b/tests/client/test_http_client_config.py@@ -3,12 +3,33 @@import json+import httpximport pytestfrom openviking_cli.client.http import AsyncHTTPClientfrom openviking_cli.utils.config import OPENVIKING_CLI_CONFIG_ENV+class FakeSearchHTTP:+ def __init__(self):+ self.calls: list[tuple[str, dict[str, object]]] = []++ async def post(self, path: str, json: dict[str, object]):+ self.calls.append((path, json))+ return httpx.Response(+ 200,+ json={+ "status": "success",+ "result": {+ "memories": [],+ "resources": [],+ "skills": [],+ "total": 0,+ },+ },+ )++def test_async_http_client_loads_missing_fields_from_ovcli_config(tmp_path, monkeypatch):config_path = tmp_path / "ovcli.conf"config_path.write_text(@@ -16,7 +37,6 @@ def test_async_http_client_loads_missing_fields_from_ovcli_config(tmp_path, monk{"url": "http://config-host:1933","api_key": "config-key",- "agent_id": "config-agent","account": "config-account","user": "config-user","timeout": 12.5,@@ -30,7 +50,6 @@ def test_async_http_client_loads_missing_fields_from_ovcli_config(tmp_path, monkassert client._url == "http://explicit-host:1933"assert client._api_key == "config-key"- assert client._agent_id == "config-agent"assert client._account == "config-account"assert client._user_id == "config-user"assert client._timeout == 12.5@@ -68,7 +87,34 @@ def test_async_http_client_explicit_values_override_ovcli_config(tmp_path, monke@pytest.mark.asyncio-async def test_async_http_client_user_id_sets_openviking_user_header(tmp_path, monkeypatch):+async def test_async_http_client_omits_identity_headers_when_unconfigured(tmp_path, monkeypatch):+ captured: dict[str, object] = {}+ config_path = tmp_path / "ovcli.conf"+ config_path.write_text("{}")+ monkeypatch.setenv(OPENVIKING_CLI_CONFIG_ENV, str(config_path))++ class FakeAsyncClient:+ def __init__(self, **kwargs):+ captured.update(kwargs)++ monkeypatch.setattr("openviking_cli.client.http.httpx.AsyncClient", FakeAsyncClient)++ client = AsyncHTTPClient(+ url="http://explicit-host:1933",+ api_key="explicit-key",+ timeout=33.0,+ extra_headers={},+ )+ await client.initialize()++ assert client._user_id is None+ assert captured["headers"] == {+ "X-API-Key": "explicit-key",+ }+++async def test_async_http_client_sends_configured_identity_headers(tmp_path, monkeypatch):captured: dict[str, object] = {}config_path = tmp_path / "ovcli.conf"config_path.write_text("{}")@@ -85,7 +131,6 @@ async def test_async_http_client_user_id_sets_openviking_user_header(tmp_path, mapi_key="explicit-key",account="explicit-account",user_id="explicit-user",- agent_id="explicit-agent",timeout=33.0,extra_headers={},)@@ -94,7 +139,6 @@ async def test_async_http_client_user_id_sets_openviking_user_header(tmp_path, massert client._user_id == "explicit-user"assert captured["headers"] == {"X-API-Key": "explicit-key",- "X-OpenViking-Agent": "explicit-agent","X-OpenViking-Account": "explicit-account","X-OpenViking-User": "explicit-user",}@@ -252,3 +296,69 @@ def test_async_http_client_prefers_extra_headers_over_alias(tmp_path, monkeypatc# extra_headers 优先assert client._extra_headers == {"X-Custom-Header": "from-plural"}+++async def test_async_http_client_find_sends_peer_id(tmp_path, monkeypatch):+ config_path = tmp_path / "ovcli.conf"+ config_path.write_text("{}")+ monkeypatch.setenv(OPENVIKING_CLI_CONFIG_ENV, str(config_path))++ http = FakeSearchHTTP()+ client = AsyncHTTPClient(url="http://explicit-host:1933", api_key="key")+ client._http = http++ await client.find(+ "invoice",+ target_uri="viking://user/memories",+ peer_id="web:visitor:alice",+ )++ assert http.calls == [+ (+ "/api/v1/search/find",+ {+ "query": "invoice",+ "target_uri": "viking://user/memories",+ "limit": 10,+ "score_threshold": None,+ "filter": None,+ "telemetry": False,+ "peer_id": "web:visitor:alice",+ },+ )+ ]+++async def test_async_http_client_search_sends_peer_id(tmp_path, monkeypatch):+ config_path = tmp_path / "ovcli.conf"+ config_path.write_text("{}")+ monkeypatch.setenv(OPENVIKING_CLI_CONFIG_ENV, str(config_path))++ http = FakeSearchHTTP()+ client = AsyncHTTPClient(url="http://explicit-host:1933", api_key="key")+ client._http = http++ await client.search(+ "invoice",+ target_uri="viking://user/memories",+ session_id="session-1",+ peer_id="web:visitor:alice",+ )++ assert http.calls == [+ (+ "/api/v1/search/search",+ {+ "query": "invoice",+ "target_uri": "viking://user/memories",+ "session_id": "session-1",+ "limit": 10,+ "score_threshold": None,+ "filter": None,+ "telemetry": False,+ "peer_id": "web:visitor:alice",+ },+ )+ ]diff --git a/tests/client/test_rebuild_clients.py b/tests/client/test_rebuild_clients.pyindex 18005f808..df78bdc1d 100644--- a/tests/client/test_rebuild_clients.py+++ b/tests/client/test_rebuild_clients.py@@ -154,7 +154,7 @@ async def test_local_client_batch_add_messages_forwards_to_session():client = LocalClient.__new__(LocalClient)client._service = SimpleNamespace(sessions=FakeSessions())- client._ctx = SimpleNamespace(user=SimpleNamespace(user_id="user-1", agent_id="agent-1"))+ client._ctx = SimpleNamespace(user=SimpleNamespace(user_id="user-1"))result = await LocalClient.batch_add_messages(client,@@ -163,7 +163,7 @@ async def test_local_client_batch_add_messages_forwards_to_session():{"role": "user","content": "hello",- "role_id": "explicit-user",+ "peer_id": "explicit-user","created_at": "2026-05-28T00:00:00+00:00",},{"role": "assistant", "parts": [{"type": "text", "text": "hi"}]},@@ -172,11 +172,11 @@ async def test_local_client_batch_add_messages_forwards_to_session():assert result == {"session_id": "batch-session", "message_count": 2, "added": 2}assert fake_session.messages[0]["role"] == "user"- assert fake_session.messages[0]["role_id"] == "explicit-user"+ assert fake_session.messages[0]["peer_id"] == "explicit-user"assert fake_session.messages[0]["created_at"] == "2026-05-28T00:00:00+00:00"assert fake_session.messages[0]["parts"][0].text == "hello"assert fake_session.messages[1]["role"] == "assistant"- assert fake_session.messages[1]["role_id"] == "agent-1"+ assert fake_session.messages[1]["peer_id"] is Noneassert fake_session.messages[1]["parts"][0].text == "hi"@@ -192,7 +192,7 @@ async def test_async_http_client_batch_add_messages_posts_batch_payload():{"role": "user","content": "hello",- "role_id": "explicit-user",+ "peer_id": "explicit-user","created_at": "2026-05-28T00:00:00+00:00",},{"role": "assistant", "parts": [{"type": "text", "text": "hi"}]},@@ -260,7 +260,7 @@ def test_sync_http_client_batch_add_messages_forwards_to_async_client():{"role": "user","content": "hello",- "role_id": "explicit-user",+ "peer_id": "explicit-user","created_at": "2026-05-28T00:00:00+00:00",},{"role": "assistant", "parts": [{"type": "text", "text": "hi"}]},diff --git a/tests/client/test_skill_management.py b/tests/client/test_skill_management.pyindex e0e992c2d..c1607ba11 100644--- a/tests/client/test_skill_management.py+++ b/tests/client/test_skill_management.py@@ -8,15 +8,15 @@ from types import SimpleNamespacefrom openviking import AsyncOpenVikingfrom openviking.client import LocalClient-from openviking.core.namespace import canonical_agent_root+from openviking.core.namespace import canonical_user_rootfrom openviking.server.identity import RequestContext, Rolefrom openviking.storage.expr import PathScopefrom openviking.telemetry import get_current_telemetryfrom openviking_cli.session.user_id import UserIdentifier-def _agent_skills_root(client: AsyncOpenViking) -> str:- return f"{canonical_agent_root(client._client._ctx)}/skills"+def _user_skills_root(client: AsyncOpenViking) -> str:+ return f"{canonical_user_root(client._client._ctx)}/skills"class TestAddSkill:@@ -55,7 +55,7 @@ Use this skill when you need to test skill functionality.assert "root_uri" in resultassert "uri" in resultassert result["root_uri"] == result["uri"]- assert result["uri"].startswith(f"{_agent_skills_root(client)}/")+ assert result["uri"].startswith(f"{_user_skills_root(client)}/")abstract = await client.abstract(result["uri"])assert "name: test-skill" in abstract@@ -83,7 +83,7 @@ This skill was created from a string.result = await client.add_skill(data=skill_content)assert "uri" in result- assert result["uri"].startswith(f"{_agent_skills_root(client)}/")+ assert result["uri"].startswith(f"{_user_skills_root(client)}/")abstract = await client.abstract(result["uri"])assert "name: string-skill" in abstract@@ -108,7 +108,7 @@ This skill was created from a string.seen["telemetry_id"] = telemetry.telemetry_idseen["kwargs"] = kwargsreturn {- "uri": "viking://agent/skills/waited-skill",+ "uri": "viking://user/default/skills/waited-skill","queue_status": queue_status,}@@ -128,7 +128,7 @@ This skill was created from a string.telemetry=False,)- assert result["uri"] == "viking://agent/skills/waited-skill"+ assert result["uri"] == "viking://user/default/skills/waited-skill"assert result["queue_status"] == queue_statusassert seen["enabled"] is Trueassert str(seen["telemetry_id"]).startswith("tm_")@@ -148,7 +148,7 @@ This skill was created from a string.result = await client.add_skill(data=mcp_tool)assert "uri" in result- assert result["uri"].startswith(f"{_agent_skills_root(client)}/")+ assert result["uri"].startswith(f"{_user_skills_root(client)}/")async def test_add_skill_from_directory(self, client: AsyncOpenViking, temp_dir: Path):"""Test adding skill from directory"""@@ -178,7 +178,7 @@ This skill was loaded from a directory.result = await client.add_skill(data=skill_dir)assert "uri" in result- assert result["uri"].startswith(f"{_agent_skills_root(client)}/")+ assert result["uri"].startswith(f"{_user_skills_root(client)}/")class TestSkillSearch:@@ -210,10 +210,10 @@ Use this skill to test search functionality.assert hasattr(result, "skills")- async def test_add_skill_indexes_canonical_agent_uri(+ async def test_add_skill_indexes_canonical_user_uri(self, client: AsyncOpenViking, temp_dir: Path):- """Skill vectors should be stored under the canonical agent root."""+ """Skill vectors should be stored under the canonical user root."""skill_file = temp_dir / "canonical_scope_skill.md"skill_file.write_text("""---@@ -232,8 +232,8 @@ Use this skill to test canonical URI vector indexing.)result = await client.add_skill(data=skill_file, wait=True)- canonical_uri = f"{_agent_skills_root(client)}/canonical-scope-skill"- short_uri = "viking://agent/skills/canonical-scope-skill"+ canonical_uri = f"{_user_skills_root(client)}/canonical-scope-skill"+ short_uri = "viking://user/skills/canonical-scope-skill"assert result["uri"] == canonical_uridiff --git a/tests/integration/langchain_langgraph/live_e2e.py b/tests/integration/langchain_langgraph/live_e2e.pyindex cab0667f8..1594bf29d 100644--- a/tests/integration/langchain_langgraph/live_e2e.py+++ b/tests/integration/langchain_langgraph/live_e2e.py@@ -515,7 +515,6 @@ def _build_real_client():url=os.environ.get("OPENVIKING_URL") or None,api_key=os.environ.get("OPENVIKING_API_KEY"),user_id=os.environ.get("OPENVIKING_USER_ID"),- agent_id=os.environ.get("OPENVIKING_AGENT_ID"),)client.initialize()return clientdiff --git a/tests/integration/test_agent_memory_e2e.py b/tests/integration/test_agent_memory_e2e.pyindex 8d7bfdf4c..eb36dc472 100644--- a/tests/integration/test_agent_memory_e2e.py+++ b/tests/integration/test_agent_memory_e2e.py@@ -38,8 +38,6 @@ from typing import Dict, Iterator, List, Tupleimport pytestfrom openviking.client.local import LocalClient-from openviking.core.namespace import to_agent_space-from openviking.server.identity import AccountNamespacePolicyfrom openviking.session.memory.session_extract_context_provider import SessionExtractContextProviderfrom openviking.session.memory.utils import MemoryFileUtilsfrom openviking.telemetry import tracer@@ -232,28 +230,22 @@ def agent_memory_config_check():@pytest.fixture()def local_test_env() -> Iterator[Dict[str, object]]:- policy = AccountNamespacePolicy(- isolate_user_scope_by_agent=False,- isolate_agent_scope_by_user=False,- )local_path = Path.cwd() / ".tmp_agent_memory_e2e" / uuid.uuid4().hex[:8]local_path.mkdir(parents=True, exist_ok=True)try:yield {"path": str(local_path),"account_id": "default",- "policy": policy,}finally:shutil.rmtree(local_path, ignore_errors=True)-def _build_client(env: Dict[str, object], user_id: str, agent_id: str = "travelbot") -> LocalClient:+def _build_client(env: Dict[str, object], user_id: str) -> LocalClient:client = LocalClient(path=str(env["path"]),- user=UserIdentifier(str(env["account_id"]), user_id, agent_id),+ user=UserIdentifier(str(env["account_id"]), user_id),)- client._ctx.namespace_policy = env["policy"]run_async(client.initialize())return client@@ -288,10 +280,8 @@ class TestAgentMemoryE2E:"failed to initialize tracer from ov.conf; please check legacy telemetry.tracer")- policy = local_test_env["policy"]- agent_space = to_agent_space(policy, "alice", "travelbot")- trajectories_dir = f"viking://agent/{agent_space}/memories/trajectories"- experiences_dir = f"viking://agent/{agent_space}/memories/experiences"+ trajectories_dir = "viking://user/alice/memories/trajectories"+ experiences_dir = "viking://user/alice/memories/experiences"client = Nonetry:@@ -299,7 +289,7 @@ class TestAgentMemoryE2E:"tests.integration.test_trajectory_and_experience_extraction"):print(f"\n[TEST] trace_id: {tracer.get_trace_id()}")- client = _build_client(local_test_env, user_id="alice", agent_id="travelbot")+ client = _build_client(local_test_env, user_id="alice")logger.info("Round 1: flight booking duplicate (expect CREATE experience)")_run_conversation(client, CONV_A_FLIGHT_DUPLICATE)diff --git a/tests/integration/test_compressor_v2_e2e.py b/tests/integration/test_compressor_v2_e2e.pyindex 43d82b957..caca5c794 100644--- a/tests/integration/test_compressor_v2_e2e.py+++ b/tests/integration/test_compressor_v2_e2e.py@@ -199,15 +199,13 @@ class TestCompressorV2EndToEnd:print(f" Failed to read {uri}: {e}")try:- # Try to list agent memories- agent_memories = await client.ls("viking://agent/memories", recursive=True)- print(f"Agent memories entries: {len(agent_memories)}")- for entry in agent_memories[:20]: # Show first 20+ user_memories = await client.ls("viking://user/memories", recursive=True)+ print(f"User memories entries: {len(user_memories)}")+ for entry in user_memories[:20]:print(f" - {entry['name']} ({'dir' if entry['isDir'] else 'file'})")- # Read and print memory files- await print_memory_files("viking://agent/memories", agent_memories)+ await print_memory_files("viking://user/memories", user_memories)except Exception as e:- print(f"Could not list agent memories: {e}")+ print(f"Could not list user memories: {e}")try:# Try to list user memoriesdiff --git a/tests/integration/test_compressor_v2_event_span_multiple_turns.py b/tests/integration/test_compressor_v2_event_span_multiple_turns.pyindex 98f45a2bc..adf0f8d09 100644--- a/tests/integration/test_compressor_v2_event_span_multiple_turns.py+++ b/tests/integration/test_compressor_v2_event_span_multiple_turns.py@@ -20,7 +20,6 @@ DISPLAY_NAME = "小明"DEFAULT_URL = "http://localhost:1934"PANEL_WIDTH = 78DEFAULT_API_KEY = "1cf407c39990e5dc874ccc697942da4892208a86a44c4781396dfdc57aa5c98d"-DEFAULT_AGENT_ID = "test"DEFAULT_SESSION_ID = "event-span-multiple-turns"@@ -234,7 +233,6 @@ 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"],@@ -248,9 +246,7 @@ def main():args = parser.parse_args()- client = ov.SyncHTTPClient(- url=args.url, api_key=args.api_key, agent_id=args.agent_id, timeout=180- )+ client = ov.SyncHTTPClient(url=args.url, api_key=args.api_key, timeout=180)try:client.initialize()diff --git a/tests/integration/test_compressor_v2_tool_skill_memory.py b/tests/integration/test_compressor_v2_tool_skill_memory.pyindex 5cceecdb6..0c1828e22 100644--- a/tests/integration/test_compressor_v2_tool_skill_memory.py+++ b/tests/integration/test_compressor_v2_tool_skill_memory.py@@ -21,7 +21,6 @@ DISPLAY_NAME = "测试用户"DEFAULT_URL = "http://localhost:1934"PANEL_WIDTH = 78DEFAULT_API_KEY = "1cf407c39990e5dc874ccc697942da4892208a86a44c4781396dfdc57aa5c98d"-DEFAULT_AGENT_ID = "test"DEFAULT_SESSION_ID = "tool-skill-memory-test"@@ -335,7 +334,6 @@ def main():parser = argparse.ArgumentParser(description="OpenViking 记忆演示 — 工具调用和Skill调用")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"],@@ -349,9 +347,7 @@ def main():args = parser.parse_args()- client = ov.SyncHTTPClient(- url=args.url, api_key=args.api_key, agent_id=args.agent_id, timeout=180- )+ client = ov.SyncHTTPClient(url=args.url, api_key=args.api_key, timeout=180)try:client.initialize()diff --git a/tests/integration/test_compressor_v2_xiaomei.py b/tests/integration/test_compressor_v2_xiaomei.pyindex faf7b128e..fdcd2bd45 100644--- a/tests/integration/test_compressor_v2_xiaomei.py+++ b/tests/integration/test_compressor_v2_xiaomei.py@@ -20,7 +20,6 @@ DISPLAY_NAME = "小美"DEFAULT_URL = "http://localhost:1934"PANEL_WIDTH = 78DEFAULT_API_KEY = "1cf407c39990e5dc874ccc697942da4892208a86a44c4781396dfdc57aa5c98d"-DEFAULT_AGENT_ID = "test"DEFAULT_SESSION_ID = "xiaomei-demo"@@ -160,7 +159,7 @@ def run_ingest(client: ov.SyncHTTPClient, session_id: str, wait_seconds: float):console.print(f" Task 详情: {task}")# 等待向量化队列处理完成- console.print(f" [yellow]等待向量化完成...[/yellow]")+ console.print(" [yellow]等待向量化完成...[/yellow]")client.wait_processed()if wait_seconds > 0:@@ -255,7 +254,6 @@ 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"],@@ -277,9 +275,7 @@ def main():))- client = ov.SyncHTTPClient(- url=args.url, api_key=args.api_key, agent_id=args.agent_id, timeout=180- )+ client = ov.SyncHTTPClient(url=args.url, api_key=args.api_key, timeout=180)try:client.initialize()diff --git a/tests/integration/test_compressor_v2_xiaowang.py b/tests/integration/test_compressor_v2_xiaowang.pyindex 5077e13c9..84ef8df71 100644--- a/tests/integration/test_compressor_v2_xiaowang.py+++ b/tests/integration/test_compressor_v2_xiaowang.py@@ -20,7 +20,6 @@ DISPLAY_NAME = "小王"DEFAULT_URL = "http://localhost:1934"PANEL_WIDTH = 78DEFAULT_API_KEY = "1cf407c39990e5dc874ccc697942da4892208a86a44c4781396dfdc57aa5c98d"-DEFAULT_AGENT_ID = "test"DEFAULT_SESSION_ID = "xiaowang-demo"@@ -115,7 +114,7 @@ def run_ingest(client: ov.SyncHTTPClient, session_id: str, wait_seconds: float):console.print(f" Task 详情: {task}")# 等待向量化队列处理完成- console.print(f" [yellow]等待向量化完成...[/yellow]")+ console.print(" [yellow]等待向量化完成...[/yellow]")client.wait_processed()if wait_seconds > 0:@@ -210,7 +209,6 @@ 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"],@@ -232,9 +230,7 @@ def main():))- client = ov.SyncHTTPClient(- url=args.url, api_key=args.api_key, agent_id=args.agent_id, timeout=180- )+ client = ov.SyncHTTPClient(url=args.url, api_key=args.api_key, timeout=180)try:client.initialize()diff --git a/tests/integration/test_encryption_integration.py b/tests/integration/test_encryption_integration.pyindex ac099cbd0..5cd5d44c5 100644--- a/tests/integration/test_encryption_integration.py+++ b/tests/integration/test_encryption_integration.py@@ -445,7 +445,7 @@ class TestVikingFSEncryptionWithAccounts:from openviking.server.identity import RequestContext, Rolefrom openviking_cli.session.user_id import UserIdentifier- default_user = UserIdentifier("default", "default", "default")+ default_user = UserIdentifier("default", "default")ctx = RequestContext(user=default_user, role=Role.ROOT)# Write test file directly via VikingFS@@ -514,7 +514,7 @@ class TestVikingFSEncryptionWithAccounts:from openviking.server.identity import RequestContext, Rolefrom openviking_cli.session.user_id import UserIdentifier- default_user = UserIdentifier("default", "default", "default")+ default_user = UserIdentifier("default", "default")ctx = RequestContext(user=default_user, role=Role.ROOT)# Create skill directory and files directly via VikingFS@@ -651,7 +651,7 @@ This is a test skill for verifying encryption functionality.from openviking.server.identity import RequestContext, Rolefrom openviking_cli.session.user_id import UserIdentifier- test_user = UserIdentifier(test_account_id, test_user_id, "default")+ test_user = UserIdentifier(test_account_id, test_user_id)ctx = RequestContext(user=test_user, role=Role.USER)root_ctx = RequestContext(user=test_user, role=Role.ROOT)@@ -777,31 +777,30 @@ This is a test skill for verifying encryption functionality.- Verify file storage"""- # Create test file directly using VikingFS (using root_ctx to access agent directory)- test_skill_uri = "viking://agent/test_encryption_skill/SKILL.md"- test_skill_dir_uri = "viking://agent/test_encryption_skill"+ # Create test file directly using VikingFS.+ test_skill_uri = "viking://user/default/skills/test_encryption_skill/SKILL.md"+ test_skill_dir_uri = "viking://user/default/skills/test_encryption_skill"await svc.viking_fs.mkdir(test_skill_dir_uri, ctx=root_ctx)await svc.viking_fs.write_file(test_skill_uri, skill_content, ctx=root_ctx)print(f" ✓ Test skill created successfully: {test_skill_uri}")- # Check all files in agent directory are encrypted- print("[2.1] Check files in agent directory are encrypted")- agent_dir_uri = "viking://agent"- await self._check_all_files_encrypted(agent_dir_uri, root_ctx, svc, agfs_client)+ # Check all files in the skill directory are encrypted+ print("[2.1] Check files in skill directory are encrypted")+ await self._check_all_files_encrypted(test_skill_dir_uri, root_ctx, svc, agfs_client)# 2.2 Verify various operations return unencryptedprint("[2.2] Verify various operations return unencrypted content")# ls operationprint(" Executing ls operation...")- skill_ls_entries = await svc.viking_fs.ls(agent_dir_uri, ctx=root_ctx)+ skill_ls_entries = await svc.viking_fs.ls(test_skill_dir_uri, ctx=root_ctx)assert len(skill_ls_entries) > 0print(" ✓ ls operation successful")# tree operationprint(" Executing tree operation...")try:- skill_tree_entries = await svc.viking_fs.tree(agent_dir_uri, ctx=root_ctx)+ skill_tree_entries = await svc.viking_fs.tree(test_skill_dir_uri, ctx=root_ctx)assert len(skill_tree_entries) > 0print(" ✓ tree operation successful")except Exception as e:@@ -822,7 +821,11 @@ This is a test skill for verifying encryption functionality.# grep operationprint(" Executing grep operation...")try:- skill_grep_result = await svc.viking_fs.grep(agent_dir_uri, "Test Skill", ctx=root_ctx)+ skill_grep_result = await svc.viking_fs.grep(+ test_skill_dir_uri,+ "Test Skill",+ ctx=root_ctx,+ )assert skill_grep_result is not Noneprint(" ✓ grep operation successful")except Exception as e:@@ -1106,7 +1109,7 @@ This is a test skill for verifying encryption functionality.from openviking.server.identity import RequestContext, Rolefrom openviking_cli.session.user_id import UserIdentifier- default_user = UserIdentifier("default", "default", "default")+ default_user = UserIdentifier("default", "default")ctx = RequestContext(user=default_user, role=Role.ROOT)# Write a multi-line test file@@ -1160,7 +1163,7 @@ This is a test skill for verifying encryption functionality.from openviking.server.identity import RequestContext, Rolefrom openviking_cli.session.user_id import UserIdentifier- default_user = UserIdentifier("default", "default", "default")+ default_user = UserIdentifier("default", "default")ctx = RequestContext(user=default_user, role=Role.ROOT)# Write a test file@@ -1292,7 +1295,7 @@ class TestAddResourceWithSemanticProcessing:from openviking.server.identity import RequestContext, Rolefrom openviking_cli.session.user_id import UserIdentifier- test_user = UserIdentifier(test_account_id, test_user_id, "default")+ test_user = UserIdentifier(test_account_id, test_user_id)ctx = RequestContext(user=test_user, role=Role.USER)agfs_client = svc._agfs_clientdiff --git a/tests/integration/test_group_chat.py b/tests/integration/test_group_chat.pyindex fb1042275..cd7a8dd69 100644--- a/tests/integration/test_group_chat.py+++ b/tests/integration/test_group_chat.py@@ -1,14 +1,13 @@#!/usr/bin/env python3"""OpenViking 记忆演示脚本 — 群聊场景-测试两种数据隔离策略:-1. isolate_user_scope_by_agent: 同一个 user,用不同 agent 时数据隔离-2. isolate_agent_scope_by_user: 同一个 agent,不同 user 之间数据隔离+测试当前 user/peer 记忆模型:+1. 登录 user 维护自己的记忆空间+2. peer_id 维护同一 user 下的一对多外部参与者记忆用法:- python test_group_chat.py # 默认测试 4 种模式- python test_group_chat.py --mode ff # 只测试 ff 模式- python test_group_chat.py --account test-ff # 测试指定 account+ python test_group_chat.py+ python test_group_chat.py --account test-user-peer # 测试指定 account"""import argparse@@ -50,12 +49,12 @@ console = Console()CONVERSATION_1 = [# alice 和 agent-a 对话- {"role_id": "alice", "role": "user", "content": "我的密码是123456"},- {"role_id": "agent-a", "role": "assistant", "content": "好的记住了"},+ {"peer_id": "alice", "role": "user", "content": "我的密码是123456"},+ {"peer_id": "agent-a", "role": "assistant", "content": "好的记住了"},# user 告诉 agent 它的身份和风格- {"role_id": "alice", "role": "user", "content": "你叫 Agent A,是我的技术助手,说话要简洁专业"},+ {"peer_id": "alice", "role": "user", "content": "你叫 Agent A,是我的技术助手,说话要简洁专业"},{- "role_id": "agent-a",+ "peer_id": "agent-a","role": "assistant","content": "好的,我记下了,我是 Agent A,技术助手,简洁专业",},@@ -63,12 +62,12 @@ CONVERSATION_1 = [CONVERSATION_2 = [# alice 和 agent-b 对话- {"role_id": "alice", "role": "user", "content": "我最爱的颜色是蓝色"},- {"role_id": "agent-b", "role": "assistant", "content": "好的"},+ {"peer_id": "alice", "role": "user", "content": "我最爱的颜色是蓝色"},+ {"peer_id": "agent-b", "role": "assistant", "content": "好的"},# user 告诉另一个 agent 它的身份和风格- {"role_id": "alice", "role": "user", "content": "你叫 Agent B,是我的生活助手,说话要亲切详细"},+ {"peer_id": "alice", "role": "user", "content": "你叫 Agent B,是我的生活助手,说话要亲切详细"},{- "role_id": "agent-b",+ "peer_id": "agent-b","role": "assistant","content": "好的,我记下了,我是 Agent B,生活助手,亲切详细",},@@ -76,8 +75,8 @@ CONVERSATION_2 = [CONVERSATION_3 = [# alice 和 agent-a 对话(再次告诉 agent 它的身份,覆盖之前的)- {"role_id": "alice", "role": "user", "content": "你叫 Agent A,是我的编程助手"},- {"role_id": "agent-a", "role": "assistant", "content": "好的,我是 Agent A,编程助手"},+ {"peer_id": "alice", "role": "user", "content": "你叫 Agent A,是我的编程助手"},+ {"peer_id": "agent-a", "role": "assistant", "content": "好的,我是 Agent A,编程助手"},]@@ -112,14 +111,14 @@ def run_ingest(client: ov.SyncHTTPClient, session_id_prefix: str):total = len(conv_data)for i, msg in enumerate(conv_data, 1):- role_id = msg.get("role_id")- console.print(f" [{i}/{total}] 添加 (role_id={role_id})")+ peer_id = msg.get("peer_id")+ console.print(f" [{i}/{total}] 添加 (peer_id={peer_id})")client.add_message(session_id,role=msg["role"],content=msg["content"],created_at=session_time_str,- role_id=role_id,+ peer_id=peer_id,)console.print(f" 共 {total} 条消息,提交...")@@ -175,12 +174,11 @@ def verify_isolation(url: str, api_key: str, account: str):api_key=api_key,account=account,user=search_user,- agent_id=search_agent,timeout=180,)sc.initialize()- results = sc.find(query, limit=5)+ results = sc.find(query, limit=5, peer_id=search_agent)found = Falseif hasattr(results, "memories") and results.memories:for m in results.memories:@@ -224,18 +222,14 @@ def run_test_for_account(account: str, url: str, root_key: str, wait: float) ->api_key=root_key,account=account,user="admin",- agent_id="default",timeout=180,)client.initialize()- # 尝试创建账号(用 HTTP 以便设置隔离参数)+ # 尝试创建账号console.print(" [yellow]检查/创建账号...[/yellow]")- isolate_user = "test-tf" in account or "test-tt" in account- isolate_agent = "test-ft" in account or "test-tt" in accounttry:- # 用 HTTP 直接调用以设置隔离参数with httpx.Client() as http:resp = http.post(f"{url}/api/v1/admin/accounts",@@ -243,14 +237,10 @@ def run_test_for_account(account: str, url: str, root_key: str, wait: float) ->json={"account_id": account,"admin_user_id": "admin",- "isolate_user_scope_by_agent": isolate_user,- "isolate_agent_scope_by_user": isolate_agent,},)if resp.status_code == 200:- console.print(- f" - 账号 {account} 已创建 (user={isolate_user}, agent={isolate_agent})"- )+ console.print(f" - 账号 {account} 已创建")elif "already exists" in resp.text:console.print(f" - 账号 {account} 已存在")else:@@ -311,18 +301,10 @@ def run_test_for_account(account: str, url: str, root_key: str, wait: float) ->def main():- parser = argparse.ArgumentParser(description="群聊记忆测试 - 测试数据隔离")+ parser = argparse.ArgumentParser(description="群聊记忆测试 - 测试 user/peer 记忆模型")parser.add_argument("--url", default=DEFAULT_URL, help="Server URL")parser.add_argument("--root-key", default="default", help="Root API Key (默认: default)")- parser.add_argument(- "--mode",- choices=["all", "ff", "ft", "tf", "tt"],- default="all",- help="测试模式: all=4种都测, ff/ft/tf/tt=只测指定模式",- )- parser.add_argument(- "--account", default=None, help="直接指定 account 名称(优先级高于 --mode)"- )+ parser.add_argument("--account", default=None, help="直接指定 account 名称")parser.add_argument("--wait", type=float, default=5.0, help="提交后等待秒数")args = parser.parse_args()@@ -334,14 +316,7 @@ def main():))- # 确定要测试的账号列表- default_accounts = ["test-ff", "test-ft", "test-tf", "test-tt"]- if args.account:- accounts = [args.account]- elif args.mode == "all":- accounts = default_accounts- else:- accounts = [f"test-{args.mode}"]+ accounts = [args.account or "test-user-peer"]# 逐个测试all_trace_ids = {}@@ -358,11 +333,7 @@ def main():Panel(f"[bold green]测试完成![/bold green]\n\n"f"Trace IDs:\n{trace_info}\n\n"- "预期结果差异:\n"- " ff: isolate_user=F, isolate_agent=F → 全部 ✓ (都不隔离)\n"- " ft: isolate_user=F, isolate_agent=T → 3个 ✓ (只隔离 agent)\n"- " tf: isolate_user=T, isolate_agent=F → 3个 ✓ (只隔离 user)\n"- " tt: isolate_user=T, isolate_agent=T → 全部 ✓ (都隔离)",+ "预期:当前登录 user 命中自己的记忆;peer 记忆由 peer_id 路由。",style="green",width=PANEL_WIDTH,)diff --git a/tests/integration/test_vault_encryption_integration.py b/tests/integration/test_vault_encryption_integration.pyindex 3b8192d2a..198804f3a 100644--- a/tests/integration/test_vault_encryption_integration.py+++ b/tests/integration/test_vault_encryption_integration.py@@ -443,7 +443,7 @@ class TestVikingFSEncryptionWithVault:from openviking.server.identity import RequestContext, Role- user = UserIdentifier(account_id, admin_user_id, admin_user_id)+ user = UserIdentifier(account_id, admin_user_id)ctx = RequestContext(user=user, role=Role.ADMIN)# Create test resource file@@ -511,11 +511,11 @@ class TestVikingFSEncryptionWithVault:from openviking.server.identity import RequestContext, Role- user = UserIdentifier(account_id, admin_user_id, admin_user_id)+ user = UserIdentifier(account_id, admin_user_id)ctx = RequestContext(user=user, role=Role.ADMIN)# Create skill directory and file- skill_dir_uri = f"viking://{account_id}/agent/test-skill"+ skill_dir_uri = f"viking://user/{admin_user_id}/skills/test-skill"skill_md_uri = f"{skill_dir_uri}/SKILL.md"# Create directory@@ -574,7 +574,7 @@ This is a test skill for verifying Vault encryption.from openviking.server.identity import RequestContext, Role- user = UserIdentifier(account_id, user_id, user_id)+ user = UserIdentifier(account_id, user_id)ctx = RequestContext(user=user, role=Role.USER)# Create memory directory and file@@ -617,7 +617,7 @@ This is a test skill for verifying Vault encryption.from openviking.server.identity import RequestContext, Role- user = UserIdentifier(account_id, user_id, user_id)+ user = UserIdentifier(account_id, user_id)ctx = RequestContext(user=user, role=Role.USER)# Create session@@ -654,7 +654,7 @@ This is a test skill for verifying Vault encryption.print(f"\n=== Creating account: {random_account_id}, user: {random_user_id} ===")await api_key_manager.create_account(random_account_id, random_user_id)- user = UserIdentifier(random_account_id, random_user_id, random_user_id)+ user = UserIdentifier(random_account_id, random_user_id)ctx = RequestContext(user=user, role=Role.ADMIN)# 2. Execution: Resource, skill, session operations@@ -667,7 +667,7 @@ This is a test skill for verifying Vault encryption.print(f"✓ Resource created successfully: {test_resource_uri}")# Create skill- skill_dir_uri = f"viking://{random_account_id}/agent/test-workflow-skill"+ skill_dir_uri = "viking://user/admin/skills/test-workflow-skill"skill_md_uri = f"{skill_dir_uri}/SKILL.md"await svc.viking_fs.mkdir(skill_dir_uri, ctx=ctx)skill_content = """---diff --git a/tests/integration/test_volcengine_kms_encryption_integration.py b/tests/integration/test_volcengine_kms_encryption_integration.pyindex d95614311..38615541f 100644--- a/tests/integration/test_volcengine_kms_encryption_integration.py+++ b/tests/integration/test_volcengine_kms_encryption_integration.py@@ -463,7 +463,7 @@ class TestVikingFSEncryptionWithVolcengineKMS:from openviking.server.identity import RequestContext, Role- user = UserIdentifier(account_id, admin_user_id, admin_user_id)+ user = UserIdentifier(account_id, admin_user_id)ctx = RequestContext(user=user, role=Role.ADMIN)test_content = "Test content with Volcengine KMS encryption"@@ -505,7 +505,7 @@ class TestVikingFSEncryptionWithVolcengineKMS:from openviking.server.identity import RequestContext, Role- user = UserIdentifier(account_id, admin_user_id, admin_user_id)+ user = UserIdentifier(account_id, admin_user_id)ctx = RequestContext(user=user, role=Role.ADMIN)# Create test resource file@@ -575,11 +575,11 @@ class TestVikingFSEncryptionWithVolcengineKMS:from openviking.server.identity import RequestContext, Role- user = UserIdentifier(account_id, admin_user_id, admin_user_id)+ user = UserIdentifier(account_id, admin_user_id)ctx = RequestContext(user=user, role=Role.ADMIN)# Create skill directory and file- skill_dir_uri = f"viking://{account_id}/agent/test-skill"+ skill_dir_uri = f"viking://user/{admin_user_id}/skills/test-skill"skill_md_uri = f"{skill_dir_uri}/SKILL.md"# Create directory@@ -638,7 +638,7 @@ This is a test skill for verifying Volcengine KMS encryption.from openviking.server.identity import RequestContext, Role- user = UserIdentifier(account_id, user_id, user_id)+ user = UserIdentifier(account_id, user_id)ctx = RequestContext(user=user, role=Role.USER)# Create memory directory and file@@ -681,7 +681,7 @@ This is a test skill for verifying Volcengine KMS encryption.from openviking.server.identity import RequestContext, Role- user = UserIdentifier(account_id, user_id, user_id)+ user = UserIdentifier(account_id, user_id)ctx = RequestContext(user=user, role=Role.USER)# Create session@@ -714,7 +714,7 @@ This is a test skill for verifying Volcengine KMS encryption.from openviking.server.identity import RequestContext, Role- user = UserIdentifier(test_account_id, test_user_id, test_user_id)+ user = UserIdentifier(test_account_id, test_user_id)ctx = RequestContext(user=user, role=Role.ADMIN)print(f"\n✓ Created test account: {test_account_id}")@@ -730,7 +730,7 @@ This is a test skill for verifying Volcengine KMS encryption.# 2. Skill operationsprint("\n2. Testing skill operations...")- skill_dir_uri = f"viking://{test_account_id}/agent/test-workflow-skill"+ skill_dir_uri = "viking://user/admin/skills/test-workflow-skill"skill_md_uri = f"{skill_dir_uri}/SKILL.md"await svc.viking_fs.mkdir(skill_dir_uri, ctx=ctx)skill_content = """---diff --git a/tests/integration/test_watch_e2e.py b/tests/integration/test_watch_e2e.pyindex 61c51e36c..8bc8e23fe 100644--- a/tests/integration/test_watch_e2e.py+++ b/tests/integration/test_watch_e2e.py@@ -24,7 +24,6 @@ async def get_watch_task(client: AsyncOpenViking, to_uri: str):account_id=client._service.user.account_id,user_id=client._service.user.user_id,role=Role.USER.value,- agent_id=client._service.user.agent_id,)@@ -384,14 +383,14 @@ class TestWatchE2EMultipleResources:intervals = [30.0, 60.0, 120.0]- for uri, interval in zip(uris, intervals):+ for uri, interval in zip(uris, intervals, strict=True):await client.add_resource(path=str(watch_test_file),to=uri,watch_interval=interval,)- for uri, expected_interval in zip(uris, intervals):+ for uri, expected_interval in zip(uris, intervals, strict=True):task = await get_watch_task(client, uri)assert task is not Noneassert task.is_active is True@@ -475,7 +474,7 @@ class TestWatchE2EErrorHandling:)ctx = RequestContext(- user=UserIdentifier("test_account", "test_user", "test_agent"),+ user=UserIdentifier("test_account", "test_user"),role=Role.USER,)diff --git a/tests/misc/test_ovpack_import_policy.py b/tests/misc/test_ovpack_import_policy.pyindex 09ec598a7..affcd4d38 100644--- a/tests/misc/test_ovpack_import_policy.py+++ b/tests/misc/test_ovpack_import_policy.py@@ -228,11 +228,11 @@ class MissingSidecarBackupVikingFS(FakeBackupVikingFS):level_limit=None,ctx=None,):- if uri == "viking://agent":+ if uri == "viking://user":return [{"rel_path": ".overview.md",- "uri": "viking://agent/.overview.md",+ "uri": "viking://user/.overview.md","isDir": False,"size": 0,}@@ -341,7 +341,7 @@ class HybridIndexVectorStore(FakeVectorStore):@pytest.fixturedef request_ctx() -> RequestContext:- return RequestContext(user=UserIdentifier("acct", "alice", "agent1"), role=Role.USER)+ return RequestContext(user=UserIdentifier("acct", "alice"), role=Role.USER)@pytest.fixture@@ -595,7 +595,7 @@ async def test_backup_restore_contract(temp_ovpack_path: Path, request_ctx: Requ"scope": "root","package_type": "backup",}- assert manifest["scopes"] == ["resources", "user", "agent", "session"]+ assert manifest["scopes"] == ["resources", "user", "session"]with pytest.raises(InvalidArgumentError, match=r"must be restored"):await import_ovpack(FakeVikingFS(), str(temp_ovpack_path), "viking://", request_ctx)@@ -606,7 +606,7 @@ async def test_backup_restore_contract(temp_ovpack_path: Path, request_ctx: Requ"viking://resources/README.md","viking://session/sess_1/.meta.json",]- assert fake_fs.tree_calls == ["viking://resources", "viking://user", "viking://agent"]+ assert fake_fs.tree_calls == ["viking://resources", "viking://user"]@pytest.mark.asyncio@@ -625,9 +625,9 @@ async def test_backup_skips_missing_semantic_sidecars(manifest = json.loads(zf.read("openviking-backup/_ovpack/manifest.json").decode("utf-8"))manifest_paths = {entry["path"] for entry in manifest["entries"]}- assert "openviking-backup/files/agent/.overview.md" not in names- assert "agent/.overview.md" not in manifest_paths- assert "agent" in manifest_paths+ assert "openviking-backup/files/user/.overview.md" not in names+ assert "user/.overview.md" not in manifest_paths+ assert "user" in manifest_paths@pytest.mark.asynciodiff --git a/tests/misc/test_vikingfs_find_without_rerank.py b/tests/misc/test_vikingfs_find_without_rerank.pyindex 76183892f..17880c668 100644--- a/tests/misc/test_vikingfs_find_without_rerank.py+++ b/tests/misc/test_vikingfs_find_without_rerank.py@@ -14,7 +14,7 @@ from openviking_cli.session.user_id import UserIdentifierdef _ctx() -> RequestContext:- return RequestContext(user=UserIdentifier("acc1", "user1", "agent1"), role=Role.USER)+ return RequestContext(user=UserIdentifier("acc1", "user1"), role=Role.USER)def _make_viking_fs() -> VikingFS:@@ -22,12 +22,12 @@ def _make_viking_fs() -> VikingFS:fs.agfs = MagicMock()fs.query_embedder = MagicMock(name="embedder")fs.rerank_config = None+ fs.retrieval_config = Nonefs.vector_store = MagicMock(name="vector_store")fs._bound_ctx = contextvars.ContextVar("vikingfs_bound_ctx_test", default=None)fs._ensure_access = MagicMock()fs._get_vector_store = MagicMock(return_value=fs.vector_store)fs._get_embedder = MagicMock(return_value=fs.query_embedder)- fs._infer_context_type = MagicMock(return_value=ContextType.RESOURCE)fs._ctx_or_default = MagicMock(return_value=_ctx())return fs@@ -39,17 +39,27 @@ async def test_find_works_without_rerank_config(monkeypatch) -> None:captured = {}class FakeRetriever:- def __init__(self, storage, embedder, rerank_config):+ def __init__(self, storage, embedder, rerank_config, retrieval_config):captured["storage"] = storagecaptured["embedder"] = embeddercaptured["rerank_config"] = rerank_config+ captured["retrieval_config"] = retrieval_config- async def retrieve(self, typed_query, ctx, limit, score_threshold, scope_dsl):+ async def retrieve(+ self,+ typed_query,+ ctx,+ limit,+ score_threshold,+ scope_dsl,+ level,+ ):captured["typed_query"] = typed_querycaptured["ctx"] = ctxcaptured["limit"] = limitcaptured["score_threshold"] = score_thresholdcaptured["scope_dsl"] = scope_dsl+ captured["level"] = levelreturn QueryResult(query=typed_query,matched_contexts=[@@ -81,11 +91,13 @@ async def test_find_works_without_rerank_config(monkeypatch) -> None:assert captured["storage"] is fs.vector_storeassert captured["embedder"] is fs.query_embedderassert captured["rerank_config"] is None+ assert captured["retrieval_config"] is Noneassert captured["typed_query"].query == "guide"- assert captured["typed_query"].context_type == ContextType.RESOURCE+ assert captured["typed_query"].context_type is Noneassert captured["typed_query"].target_directories == ["viking://resources/docs"]assert captured["ctx"] == fs._ctx_or_default.return_valueassert captured["limit"] == 3assert captured["score_threshold"] == 0.2assert captured["scope_dsl"] == {"category": "doc"}+ assert captured["level"] is Nonefs._ensure_access.assert_called_once_with("viking://resources/docs", request_ctx)diff --git a/tests/observability/test_console_router.py b/tests/observability/test_console_router.pyindex 4447ba69f..15e343c86 100644--- a/tests/observability/test_console_router.py+++ b/tests/observability/test_console_router.py@@ -18,7 +18,7 @@ from openviking_cli.session.user_id import UserIdentifierdef _ctx(role: Role = Role.ADMIN) -> RequestContext:return RequestContext(- user=UserIdentifier(account_id="acct-1", user_id="user-1", agent_id="agent-1"),+ user=UserIdentifier(account_id="acct-1", user_id="user-1"),role=role,)@@ -83,7 +83,6 @@ class FakeConsoleService:"context_counts": {},"today_tokens": {},"today_retrievals": {},- "agent_overview": {"total": 0, "items": []},}async def audit_logs(self, **kwargs):diff --git a/tests/observability/test_events.py b/tests/observability/test_events.pyindex a5ef7ac01..5ea01c463 100644--- a/tests/observability/test_events.py+++ b/tests/observability/test_events.py@@ -30,7 +30,6 @@ def test_event_bus_fans_out_and_enriches_root_metadata():request_id="req-1",account_id="acct-1",user_id="user-1",- agent_id="agent-1",)token = bind_root_observability_context(root)try:@@ -46,7 +45,6 @@ def test_event_bus_fans_out_and_enriches_root_metadata():assert seen_a[0].request_id == "req-1"assert seen_a[0].account_id == "acct-1"assert seen_a[0].user_id == "user-1"- assert seen_a[0].agent_id == "agent-1"def test_metric_datasource_publishes_to_shared_bus_without_metrics_init():diff --git a/tests/observability/test_usage_audit_inventory.py b/tests/observability/test_usage_audit_inventory.pyindex 7ba4a0988..0bc7b6f13 100644--- a/tests/observability/test_usage_audit_inventory.py+++ b/tests/observability/test_usage_audit_inventory.py@@ -16,7 +16,7 @@ from openviking_cli.session.user_id import UserIdentifierdef _ctx() -> RequestContext:return RequestContext(- user=UserIdentifier(account_id="acct-1", user_id="user-1", agent_id="agent-1"),+ user=UserIdentifier(account_id="acct-1", user_id="user-1"),role=Role.USER,)@@ -29,9 +29,8 @@ class FakeFSService:self.calls.append((uri, ctx))return {"viking://resources": {"count": 2},- "viking://agent/agent-1/skills": {"count": 3},+ "viking://user/user-1/skills": {"count": 3},"viking://user/user-1/memories": {"count": 5},- "viking://agent/agent-1/memories": {"count": 7},}[uri]@@ -56,13 +55,12 @@ async def test_context_inventory_counts_from_stat():counts = await provider.get_counts(ctx)- assert counts == {"files": 2, "skills": 3, "memories": 12, "total": 17}- assert len(fs.calls) == 4+ assert counts == {"files": 2, "skills": 3, "memories": 5, "total": 10}+ assert len(fs.calls) == 3assert {uri for uri, call_ctx in fs.calls if call_ctx is ctx} == {"viking://resources",- "viking://agent/agent-1/skills",+ "viking://user/user-1/skills","viking://user/user-1/memories",- "viking://agent/agent-1/memories",}diff --git a/tests/observability/test_usage_audit_runtime.py b/tests/observability/test_usage_audit_runtime.pyindex bf8fbadcf..9669dd39d 100644--- a/tests/observability/test_usage_audit_runtime.py+++ b/tests/observability/test_usage_audit_runtime.py@@ -37,7 +37,6 @@ async def test_usage_audit_runtime_subscribes_to_shared_event_bus(tmp_path):"request_id": "req-runtime","account_id": "acct-runtime","user_id": "user-runtime",- "agent_id": "agent-runtime","method": "POST","route": "/api/v1/search/find","status": "200",diff --git a/tests/observability/test_usage_audit_store.py b/tests/observability/test_usage_audit_store.pyindex 21d638981..bd07a0504 100644--- a/tests/observability/test_usage_audit_store.py+++ b/tests/observability/test_usage_audit_store.py@@ -19,7 +19,6 @@ def _event(event_name: str,payload: dict,*,- agent_id: str | None = None,ts: datetime | None = None,) -> ObservabilityEvent:return ObservabilityEvent(@@ -29,7 +28,6 @@ def _event(request_id=payload.get("request_id"),account_id="acct-1",user_id="user-1",- agent_id=agent_id,)@@ -41,7 +39,6 @@ def _create_legacy_usage_audit_db(db_path) -> None:CREATE TABLE usage_token_daily (account_id TEXT NOT NULL,user_id TEXT NOT NULL,- agent_id TEXT NOT NULL,date TEXT NOT NULL,source TEXT NOT NULL,token_type TEXT NOT NULL,@@ -50,47 +47,35 @@ def _create_legacy_usage_audit_db(db_path) -> None:token_count INTEGER NOT NULL DEFAULT 0,updated_at TEXT NOT NULL,PRIMARY KEY (- account_id, user_id, agent_id, date, source, token_type, provider, model_name+ account_id, user_id, date, source, token_type, provider, model_name));CREATE TABLE usage_retrieval_daily (account_id TEXT NOT NULL,user_id TEXT NOT NULL,- agent_id TEXT NOT NULL,date TEXT NOT NULL,operation TEXT NOT NULL,status TEXT NOT NULL,request_count INTEGER NOT NULL DEFAULT 0,result_count INTEGER NOT NULL DEFAULT 0,updated_at TEXT NOT NULL,- PRIMARY KEY (account_id, user_id, agent_id, date, operation, status)+ PRIMARY KEY (account_id, user_id, date, operation, status));CREATE TABLE usage_context_write_bucket (account_id TEXT NOT NULL,user_id TEXT NOT NULL,- agent_id TEXT NOT NULL,date TEXT NOT NULL,hour_bucket INTEGER NOT NULL,operation TEXT NOT NULL,count INTEGER NOT NULL DEFAULT 0,updated_at TEXT NOT NULL,- PRIMARY KEY (account_id, user_id, agent_id, date, hour_bucket, operation)- );- CREATE TABLE usage_agent_activity_daily (- account_id TEXT NOT NULL,- agent_id TEXT NOT NULL,- date TEXT NOT NULL,- request_count INTEGER NOT NULL DEFAULT 0,- last_seen_at TEXT NOT NULL,- updated_at TEXT NOT NULL,- PRIMARY KEY (account_id, agent_id, date)+ PRIMARY KEY (account_id, user_id, date, hour_bucket, operation));CREATE TABLE request_audit (id INTEGER PRIMARY KEY AUTOINCREMENT,request_id TEXT,account_id TEXT NOT NULL,user_id TEXT,- agent_id TEXT,method TEXT NOT NULL,route TEXT NOT NULL,api_type TEXT NOT NULL,@@ -99,11 +84,11 @@ def _create_legacy_usage_audit_db(db_path) -> None:created_at TEXT NOT NULL);INSERT INTO request_audit (- request_id, account_id, user_id, agent_id, method, route,+ request_id, account_id, user_id, method, route,api_type, status_code, duration_ms, created_at)VALUES (- 'legacy-req', 'acct-1', 'user-1', 'agent-1', 'GET',+ 'legacy-req', 'acct-1', 'user-1', 'GET','/api/v1/system/status', 'system', 200, 1.0,'2026-05-11T00:00:00+08:00');@@ -158,7 +143,6 @@ async def test_sqlite_usage_audit_store_aggregates_dashboard_data(tmp_path):"status": "200","duration_seconds": 0.1,},- agent_id="agent-1",),_event("http.request",@@ -169,7 +153,6 @@ async def test_sqlite_usage_audit_store_aggregates_dashboard_data(tmp_path):"status": "200","duration_seconds": 0.01,},- agent_id="agent-1",),_event("http.request",@@ -180,7 +163,6 @@ async def test_sqlite_usage_audit_store_aggregates_dashboard_data(tmp_path):"status": "200","duration_seconds": 0.01,},- agent_id="agent-1",),_event("http.request",@@ -191,7 +173,6 @@ async def test_sqlite_usage_audit_store_aggregates_dashboard_data(tmp_path):"status": "200","duration_seconds": 0.01,},- agent_id="agent-1",),])@@ -219,13 +200,6 @@ async def test_sqlite_usage_audit_store_aggregates_dashboard_data(tmp_path):tz=UTC,)assert any(row["hour"] == 1 and row["session_add_message"] == 1 for row in commits)- agents = await store.get_agent_overview(- account_id="acct-1",- user_date="2026-05-12",- tz=UTC,- )- assert agents["total"] == 1- assert agents["items"][0]["agent_id"] == "agent-1"audit = await store.query_audit_logs(account_id="acct-1")assert audit["total"] == 2assert audit["success_rate"] == 1.0@@ -262,7 +236,6 @@ async def test_sqlite_usage_audit_store_resets_incompatible_legacy_schema(tmp_pa"status": "200","duration_seconds": 0.1,},- agent_id="agent-1",),])@@ -283,12 +256,6 @@ async def test_sqlite_usage_audit_store_resets_incompatible_legacy_schema(tmp_patz=UTC,)assert any(row["hour"] == 1 and row["session_add_message"] == 1 for row in commits)- agents = await store.get_agent_overview(- account_id="acct-1",- user_date="2026-05-12",- tz=UTC,- )- assert agents["total"] == 1audit = await store.query_audit_logs(account_id="acct-1", page_size=10)assert audit["total"] == 1assert audit["items"][0]["request_id"] == "req-message"@@ -302,17 +269,16 @@ async def test_sqlite_usage_audit_store_resets_incompatible_legacy_schema(tmp_pa}assert "usage_token_daily" not in tablesassert "usage_retrieval_daily" not in tables- for table in ("usage_context_write_bucket", "usage_agent_activity_daily"):- columns = {row[1] for row in conn.execute(f"PRAGMA table_info({table})")}- assert "date_utc" in columns- assert "date" not in columns+ columns = {row[1] for row in conn.execute("PRAGMA table_info(usage_context_write_bucket)")}+ assert "date_utc" in columns+ assert "date" not in columnscontext_columns = {row[1] for row in conn.execute("PRAGMA table_info(usage_context_write_bucket)")}assert "hour_utc" in context_columnsassert "hour_bucket" not in context_columnsversion = conn.execute("SELECT value FROM _schema_meta WHERE key = 'version'").fetchone()- assert version == ("3",)+ assert version == ("4",)finally:conn.close()@@ -528,7 +494,6 @@ async def test_context_heatmap_rebuckets_hour_for_shanghai(tmp_path):"duration_seconds": 0.01,},ts=datetime(2026, 5, 12, 23, 30, tzinfo=timezone.utc),- agent_id="agent-1",),])diff --git a/tests/oc2ov_test/conftest.py b/tests/oc2ov_test/conftest.pyindex dcf9462ac..a98ae3c6b 100644--- a/tests/oc2ov_test/conftest.py+++ b/tests/oc2ov_test/conftest.py@@ -141,7 +141,7 @@ def pytest_html_results_table_row(report, cells):"test_memory_v2_preferences": "Memory V2偏好设置记忆:对话写入编程语言/编辑器/咖啡偏好→commit→验证preferences目录下新增记忆文件","test_memory_v2_entities": "Memory V2实体信息记忆:对话写入姓名/年龄/职业/公司/住址→commit→验证entities目录下新增记忆文件","test_memory_v2_profile": "Memory V2用户画像记忆:对话写入技术负责人画像→commit→验证profile.md文件新增或更新",- "test_memory_v2_skills": "Memory V2技能记忆(Agent scope):对话写入Docker/K8s/CI-CD技能→commit→验证agent memories/skills目录下新增记忆文件",+ "test_memory_v2_skills": "Memory V2技能记忆:对话写入Docker/K8s/CI-CD技能→commit→验证user/skills目录下新增记忆文件","test_assemble_replays_archive_summary": "assemble()历史组装验证:写入信息→commit生成archive→新session→验证archive summary被加载回放","test_compact_produces_archive_on_threshold": "compact()压缩归档验证:持续对话超阈值→验证archive生成+记忆文件生成+上下文被压缩","test_memory_recall_explicit_search": "memory_recall显式搜索验证:写入独特信息→commit+记忆提取→新session用模糊提示触发显式搜索→验证搜索结果",diff --git a/tests/oc2ov_test/tests/p0/test_memory_v2_full_suite.py b/tests/oc2ov_test/tests/p0/test_memory_v2_full_suite.pyindex df01669bb..597be7299 100644--- a/tests/oc2ov_test/tests/p0/test_memory_v2_full_suite.py+++ b/tests/oc2ov_test/tests/p0/test_memory_v2_full_suite.py@@ -5,8 +5,7 @@ Memory V2 全面端到端测试套件- entities (实体信息) - User scope- events (事件记录) - User scope- profile (用户画像) - User scope, 单文件-- skills (技能) - Agent scope-- tools (工具) - Agent scope+- skills (技能) - User scope测试方式:通过 OpenClaw agent 进行对话,然后通过 OV API commit session 触发记忆提取。OpenClaw Gateway 会自动分配 OV session ID,需要通过对比 sessions 列表来定位。@@ -263,7 +262,10 @@ class OpenVikingAPIClient:def list_memory_files(self, memory_type: str) -> List[str]:try:- uri = f"viking://user/default/memories/{memory_type}"+ if memory_type == "skills":+ uri = "viking://user/default/skills"+ else:+ uri = f"viking://user/default/memories/{memory_type}"resp = requests.get(f"{self.server_url}/api/v1/fs/ls",headers=self.headers,@@ -386,32 +388,10 @@ class MemoryV2TestSuite:"""记录所有记忆目录的文件快照(路径 → mtime)"""files: Dict[str, float] = {}- # user scope: preferences, entities, events, profile- for md_file in self.viking_data_dir.rglob("*.md"):+ user_root = self.viking_data_dir.parent+ for md_file in user_root.rglob("*.md"):files[str(md_file)] = md_file.stat().st_mtime- # agent scope: skills, tools, cases, patterns, experiences- # Search multiple possible agent directory locations to handle- # different namespace policies (flat: agent/{agent_id}/,- # isolated: agent/{agent_id}/user/{user_id}/)- viking_root = self.viking_data_dir.parent.parent.parent- agent_base_dir = viking_root / "agent"- if agent_base_dir.exists():- for md_file in agent_base_dir.rglob("*.md"):- files[str(md_file)] = md_file.stat().st_mtime-- # Also scan the local storage root which may contain account-scoped paths- # e.g., /local/{account_id}/agent/... when using agfs backend- local_agent_dir = viking_root.parent / "local"- if local_agent_dir.exists():- for account_dir in local_agent_dir.iterdir():- if not account_dir.is_dir():- continue- agent_dir = account_dir / "agent"- if agent_dir.exists():- for md_file in agent_dir.rglob("*.md"):- files[str(md_file)] = md_file.stat().st_mtime-return filesdef check_memory_files(@@ -634,90 +614,28 @@ class MemoryV2TestSuite:print(f" ✗ profile 文件不存在: {profile_file}")return result- if memory_type in ["skills", "tools"]:- viking_root = self.viking_data_dir.parent.parent.parent- agent_base_dir = viking_root / "agent"-- # Collect all agent directories from multiple possible locations:- # 1. viking/agent/ (standard flat layout)- # 2. viking/agent/{agent_id}/user/{user_id}/ (isolated layout)- # 3. local/{account_id}/agent/ (agfs backend layout)- agent_dirs = []- if agent_base_dir.exists():- agent_dirs.append(agent_base_dir)- local_dir = viking_root.parent / "local"- if local_dir.exists():- for account_dir in local_dir.iterdir():- if not account_dir.is_dir():- continue- ad = account_dir / "agent"- if ad.exists():- agent_dirs.append(ad)-- if not agent_dirs:- print(f" ✗ agent 目录不存在: {agent_base_dir}")+ if memory_type == "skills":+ skills_dir = self.viking_data_dir.parent / "skills"+ if not skills_dir.exists():+ print(f" ✗ skills 目录不存在: {skills_dir}")return result- search_types = [memory_type]- if memory_type == "tools":- search_types = ["tools", "skills"]- elif memory_type == "skills":- search_types = ["skills", "patterns"]-- for agent_dir in agent_dirs:- for agent_space_dir in sorted(agent_dir.rglob("memories")):- if not agent_space_dir.is_dir():- continue- for search_type in search_types:- memory_dir = agent_space_dir / search_type- if not memory_dir.exists():- continue-- for md_file in sorted(memory_dir.glob("*.md")):- file_str = str(md_file)- if file_str in list(result["all_files"]):- continue- result["all_files"].append(file_str)- if file_str not in before_files:- result["found"] = True- result["new_files"].append(file_str)- print(- f" ✓ 新增记忆文件: {md_file.name} (在 {search_type}/ 目录下)"- )- else:- old_mtime = before_files[file_str]- new_mtime = md_file.stat().st_mtime- if new_mtime > old_mtime:- result["found"] = True- result["modified_files"].append(file_str)- print(- f" ✓ 记忆文件已更新: {md_file.name} (在 {search_type}/ 目录下)"- )-- # Also check skills at agent root level (not under memories/)- # e.g., viking/agent/{agent_id}/skills/- for skills_dir in sorted(agent_dir.rglob("skills")):- if not skills_dir.is_dir():- continue- parent_name = skills_dir.parent.name- if parent_name == "memories":- continue- for md_file in sorted(skills_dir.glob("*.md")):- file_str = str(md_file)- if file_str in list(result["all_files"]):- continue- result["all_files"].append(file_str)- if file_str not in before_files:- result["found"] = True- result["new_files"].append(file_str)- print(f" ✓ 新增技能文件: {md_file.name} (在 skills/ 目录下)")- else:- old_mtime = before_files[file_str]- new_mtime = md_file.stat().st_mtime- if new_mtime > old_mtime:- result["found"] = True- result["modified_files"].append(file_str)- print(f" ✓ 技能文件已更新: {md_file.name} (在 skills/ 目录下)")+ for md_file in sorted(skills_dir.rglob("*.md")):+ file_str = str(md_file)+ if file_str in result["all_files"]:+ continue+ result["all_files"].append(file_str)+ if file_str not in before_files:+ result["found"] = True+ result["new_files"].append(file_str)+ print(f" ✓ 新增技能文件: {md_file.name} (在 user/skills 目录下)")+ else:+ old_mtime = before_files[file_str]+ new_mtime = md_file.stat().st_mtime+ if new_mtime > old_mtime:+ result["found"] = True+ result["modified_files"].append(file_str)+ print(f" ✓ 技能文件已更新: {md_file.name} (在 user/skills 目录下)")if not result["found"]:if result["all_files"]:diff --git a/tests/resource/test_watch_manager.py b/tests/resource/test_watch_manager.pyindex 4c7ca68e8..ea6a62c4a 100644--- a/tests/resource/test_watch_manager.py+++ b/tests/resource/test_watch_manager.py@@ -11,14 +11,12 @@ from typing import AsyncGeneratorimport pytestimport pytest_asyncio-from openviking.resource.watch_manager import PermissionDeniedError, WatchManager, WatchTask+from openviking.resource.watch_manager import WatchManager, WatchTaskfrom openviking_cli.exceptions import ConflictErrorfrom tests.utils.mock_agfs import MockLocalAGFSTEST_ACCOUNT_ID = "default"TEST_USER_ID = "default"-TEST_AGENT_ID = "default"-OTHER_AGENT_ID = "other-agent"TEST_ROLE = "ROOT"@@ -491,93 +489,6 @@ class TestWatchManager:next_time = await watch_manager.get_next_execution_time()assert next_time is not None- @pytest.mark.asyncio- async def test_user_cannot_access_other_agent_task(self, watch_manager: WatchManager):- task = await watch_manager.create_task(- path="/test/path",- to_uri="viking://resources/agent-isolation",- account_id=TEST_ACCOUNT_ID,- user_id=TEST_USER_ID,- agent_id=TEST_AGENT_ID,- )-- by_task_id = await watch_manager.get_task(- task.task_id,- account_id=TEST_ACCOUNT_ID,- user_id=TEST_USER_ID,- role="USER",- agent_id=OTHER_AGENT_ID,- )- by_uri = await watch_manager.get_task_by_uri(- to_uri="viking://resources/agent-isolation",- account_id=TEST_ACCOUNT_ID,- user_id=TEST_USER_ID,- role="USER",- agent_id=OTHER_AGENT_ID,- )- tasks = await watch_manager.get_all_tasks(- account_id=TEST_ACCOUNT_ID,- user_id=TEST_USER_ID,- role="USER",- agent_id=OTHER_AGENT_ID,- )-- assert by_task_id is None- assert by_uri is None- assert tasks == []-- @pytest.mark.asyncio- async def test_user_cannot_update_or_delete_other_agent_task(self, watch_manager: WatchManager):- task = await watch_manager.create_task(- path="/test/path",- to_uri="viking://resources/agent-update-delete",- account_id=TEST_ACCOUNT_ID,- user_id=TEST_USER_ID,- agent_id=TEST_AGENT_ID,- )-- with pytest.raises(PermissionDeniedError, match="does not have permission"):- await watch_manager.update_task(- task_id=task.task_id,- account_id=TEST_ACCOUNT_ID,- user_id=TEST_USER_ID,- role="USER",- agent_id=OTHER_AGENT_ID,- reason="other agent should not update",- )-- with pytest.raises(PermissionDeniedError, match="does not have permission"):- await watch_manager.delete_task(- task_id=task.task_id,- account_id=TEST_ACCOUNT_ID,- user_id=TEST_USER_ID,- role="USER",- agent_id=OTHER_AGENT_ID,- )-- @pytest.mark.asyncio- async def test_admin_can_manage_other_agent_task_in_same_account(- self, watch_manager: WatchManager- ):- task = await watch_manager.create_task(- path="/test/path",- to_uri="viking://resources/admin-cross-agent",- account_id=TEST_ACCOUNT_ID,- user_id=TEST_USER_ID,- agent_id=TEST_AGENT_ID,- )-- updated = await watch_manager.update_task(- task_id=task.task_id,- account_id=TEST_ACCOUNT_ID,- user_id="admin-user",- role="ADMIN",- agent_id=OTHER_AGENT_ID,- reason="admin update",- )-- assert updated.reason == "admin update"-class TestWatchManagerPersistence:"""Tests for WatchManager persistence."""diff --git a/tests/retrieve/test_hierarchical_retriever_rerank.py b/tests/retrieve/test_hierarchical_retriever_rerank.pyindex 36bb233ca..f01bea55e 100644--- a/tests/retrieve/test_hierarchical_retriever_rerank.py+++ b/tests/retrieve/test_hierarchical_retriever_rerank.py@@ -226,7 +226,7 @@ class FakeRerankClient:def _ctx() -> RequestContext:- return RequestContext(user=UserIdentifier("acc1", "user1", "agent1"), role=Role.USER)+ return RequestContext(user=UserIdentifier("acc1", "user1"), role=Role.USER)def _query() -> TypedQuery:diff --git a/tests/retrieve/test_hierarchical_retriever_target_dirs.py b/tests/retrieve/test_hierarchical_retriever_target_dirs.pyindex 6df26a238..6bec55494 100644--- a/tests/retrieve/test_hierarchical_retriever_target_dirs.py+++ b/tests/retrieve/test_hierarchical_retriever_target_dirs.py@@ -76,7 +76,7 @@ async def test_retrieve_honors_target_directories_scope_filter():target_uri = "viking://resources/foo"storage = DummyStorage()retriever = HierarchicalRetriever(storage=storage, embedder=None, rerank_config=None)- ctx = RequestContext(user=UserIdentifier("acc1", "user1", "agent1"), role=Role.USER)+ ctx = RequestContext(user=UserIdentifier("acc1", "user1"), role=Role.USER)query = TypedQuery(query="test",diff --git a/tests/server/conftest.py b/tests/server/conftest.pyindex 22ca34a99..7208238e4 100644--- a/tests/server/conftest.py+++ b/tests/server/conftest.py@@ -7,6 +7,7 @@ import shutilimport socketimport threadingimport time+from contextlib import asynccontextmanagerfrom pathlib import Pathfrom types import SimpleNamespace@@ -196,6 +197,12 @@ async def running_server(temp_dir: Path, monkeypatch):fake_embedder_cls = _install_fake_embedder(monkeypatch)_install_fake_vlm(monkeypatch)+ @asynccontextmanager+ async def _noop_mcp_lifespan():+ yield++ monkeypatch.setattr("openviking.server.mcp_endpoint.mcp_lifespan", _noop_mcp_lifespan)+svc = OpenVikingService(path=str(temp_dir / "sdk_data"), user=UserIdentifier.the_default_user("sdk_test_user"))@@ -231,7 +238,17 @@ async def running_server(temp_dir: Path, monkeypatch):else:raise RuntimeError("APIKeyManager did not initialize for SDK server test")- yield port, svc+ manager = fastapi_app.state.api_key_manager+ sdk_account_id = "sdk_test_account"+ sdk_user_key = await manager.create_account(sdk_account_id, "sdk_test_user")+ sdk_ctx = RequestContext(+ user=UserIdentifier(sdk_account_id, "sdk_test_user"),+ role=Role.ADMIN,+ )+ await svc.initialize_account_directories(sdk_ctx)+ await svc.initialize_user_directories(sdk_ctx)++ yield port, svc, sdk_user_keyserver.should_exit = Truethread.join(timeout=5)diff --git a/tests/server/oauth/test_auth_integration.py b/tests/server/oauth/test_auth_integration.pyindex 202ee916d..ca52f8f3e 100644--- a/tests/server/oauth/test_auth_integration.py+++ b/tests/server/oauth/test_auth_integration.py@@ -86,11 +86,6 @@ class _StubKeyManager:return ResolvedIdentity(role=Role.USER, account_id="api-acct", user_id="api-user")- def get_account_policy(self, account_id):- from openviking.server.identity import AccountNamespacePolicy-- return AccountNamespacePolicy()-def get_user_key_fingerprint(self, account_id: str, user_id: str) -> Optional[str]:if self._fps is None:return self._default_fpdiff --git a/tests/server/oauth/test_router.py b/tests/server/oauth/test_router.pyindex 3206d24d4..f5c634d2d 100644--- a/tests/server/oauth/test_router.py+++ b/tests/server/oauth/test_router.py@@ -111,7 +111,7 @@ async def app_with_oauth(tmp_path):def _fixed_ctx() -> RequestContext:return RequestContext(- user=UserIdentifier("acct1", "alice", "default"),+ user=UserIdentifier("acct1", "alice"),role=Role.USER,)@@ -575,7 +575,7 @@ async def test_otp_rejects_oauth_issued_caller(app_with_oauth, client):def _oauth_ctx() -> RequestContext:return RequestContext(- user=UserIdentifier("acct1", "alice", "default"),+ user=UserIdentifier("acct1", "alice"),role=Role.USER,from_oauth=True,)@@ -590,7 +590,7 @@ async def test_otp_rejects_oauth_issued_caller(app_with_oauth, client):# Reset to the fixture's default (non-OAuth) ctx for other tests.def _fixed_ctx() -> RequestContext:return RequestContext(- user=UserIdentifier("acct1", "alice", "default"),+ user=UserIdentifier("acct1", "alice"),role=Role.USER,)@@ -611,7 +611,7 @@ async def test_oauth_verify_rejects_oauth_issued_caller(app_with_oauth, client):def _oauth_ctx() -> RequestContext:return RequestContext(- user=UserIdentifier("acct1", "alice", "default"),+ user=UserIdentifier("acct1", "alice"),role=Role.USER,from_oauth=True,)@@ -629,7 +629,7 @@ async def test_oauth_verify_rejects_oauth_issued_caller(app_with_oauth, client):def _fixed_ctx() -> RequestContext:return RequestContext(- user=UserIdentifier("acct1", "alice", "default"),+ user=UserIdentifier("acct1", "alice"),role=Role.USER,)diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.pyindex 4696f6875..07377b5ff 100644--- a/tests/server/test_admin_api.py+++ b/tests/server/test_admin_api.py@@ -15,7 +15,6 @@ from openviking.server.api_keys import APIKeyManagerfrom openviking.server.app import create_appfrom openviking.server.config import ServerConfigfrom openviking.server.dependencies import set_service-from openviking.server.identity import RequestContext, Rolefrom openviking.server.models import ERROR_CODE_TO_HTTP_STATUS, ErrorInfo, Responsefrom openviking.service.core import OpenVikingServicefrom openviking_cli.exceptions import OpenVikingError@@ -156,14 +155,6 @@ def trusted_headers(return headers-async def create_agent_namespace(service: OpenVikingService, account_id: str, agent_id: str):- ctx = RequestContext(- user=UserIdentifier(account_id, "system", agent_id),- role=Role.ROOT,- )- await service.viking_fs.mkdir(f"viking://agent/{agent_id}", ctx=ctx, exist_ok=True)--# ---- Account CRUD ----@@ -451,110 +442,6 @@ async def test_list_users(admin_client: httpx.AsyncClient):assert user_ids == {"alice", "bob"}-async def test_list_agents(admin_client: httpx.AsyncClient, admin_service: OpenVikingService):- """ROOT can list agent namespaces in an account."""- acct = _uid()- await admin_client.post(- "/api/v1/admin/accounts",- json={"account_id": acct, "admin_user_id": "alice"},- headers=root_headers(),- )- await create_agent_namespace(admin_service, acct, "research")- await create_agent_namespace(admin_service, acct, "writer")-- resp = await admin_client.get(f"/api/v1/admin/accounts/{acct}/agents", headers=root_headers())-- assert resp.status_code == 200- assert resp.json()["result"] == [- {"agent_id": "default", "uri": "viking://agent/default"},- {"agent_id": "research", "uri": "viking://agent/research"},- {"agent_id": "writer", "uri": "viking://agent/writer"},- ]---async def test_list_agents_returns_default_for_new_account(- admin_client: httpx.AsyncClient,-):- """New accounts should expose the initialized default agent namespace."""- acct = _uid()- await admin_client.post(- "/api/v1/admin/accounts",- json={"account_id": acct, "admin_user_id": "alice"},- headers=root_headers(),- )-- resp = await admin_client.get(f"/api/v1/admin/accounts/{acct}/agents", headers=root_headers())-- assert resp.status_code == 200- assert resp.json()["result"] == [- {"agent_id": "default", "uri": "viking://agent/default"},- ]---async def test_admin_can_list_agents_in_own_account(- admin_client: httpx.AsyncClient,- admin_service: OpenVikingService,-):- """ADMIN can list agent namespaces in their own account."""- acct = _uid()- resp = await admin_client.post(- "/api/v1/admin/accounts",- json={"account_id": acct, "admin_user_id": "alice"},- headers=root_headers(),- )- alice_key = resp.json()["result"]["user_key"]- await create_agent_namespace(admin_service, acct, "assistant")-- resp = await admin_client.get(- f"/api/v1/admin/accounts/{acct}/agents",- headers={"X-API-Key": alice_key},- )-- assert resp.status_code == 200- assert resp.json()["result"] == [- {"agent_id": "assistant", "uri": "viking://agent/assistant"},- {"agent_id": "default", "uri": "viking://agent/default"},- ]---async def test_admin_cannot_list_agents_in_other_account(- admin_client: httpx.AsyncClient,- admin_service: OpenVikingService,-):- """ADMIN cannot list agent namespaces in another account."""- acct = _uid()- other = _uid()- resp = await admin_client.post(- "/api/v1/admin/accounts",- json={"account_id": acct, "admin_user_id": "alice"},- headers=root_headers(),- )- alice_key = resp.json()["result"]["user_key"]- await admin_client.post(- "/api/v1/admin/accounts",- json={"account_id": other, "admin_user_id": "eve"},- headers=root_headers(),- )- await create_agent_namespace(admin_service, other, "foreign")-- resp = await admin_client.get(- f"/api/v1/admin/accounts/{other}/agents",- headers={"X-API-Key": alice_key},- )-- assert resp.status_code == 403---async def test_list_agents_unknown_account_returns_404(admin_client: httpx.AsyncClient):- """Unknown accounts should use the same 404 behavior as other admin account APIs."""- resp = await admin_client.get(- f"/api/v1/admin/accounts/{_uid()}/agents",- headers=root_headers(),- )-- assert resp.status_code == 404--async def test_remove_user(admin_client: httpx.AsyncClient):"""ROOT can remove a user."""acct = _uid()@@ -715,8 +602,6 @@ async def test_trusted_mode_root_can_create_account(json={"account_id": acct,"admin_user_id": "alice",- "isolate_user_scope_by_agent": True,- "isolate_agent_scope_by_user": True,},headers=trusted_headers(account="platform",@@ -728,8 +613,6 @@ async def test_trusted_mode_root_can_create_account(body = resp.json()assert body["result"]["account_id"] == acctassert body["result"]["admin_user_id"] == "alice"- assert body["result"]["isolate_user_scope_by_agent"] is True- assert body["result"]["isolate_agent_scope_by_user"] is Trueassert "user_key" not in body["result"]@@ -928,11 +811,11 @@ async def test_trusted_mode_requires_matching_api_key_for_admin_api(assert resp.status_code == 401-async def test_trusted_mode_create_account_persists_namespace_policy(+async def test_trusted_mode_create_account_lists_current_account_metadata(trusted_admin_client: httpx.AsyncClient,trusted_admin_app,):- """Trusted account creation should persist namespace policy for later requests."""+ """Trusted account creation should list the current account metadata shape."""# Set gateway-admin to ROOT role firstmanager = trusted_admin_app.state.api_key_managerawait manager.set_role("platform", "gateway-admin", "root")@@ -943,8 +826,6 @@ async def test_trusted_mode_create_account_persists_namespace_policy(json={"account_id": acct,"admin_user_id": "alice",- "isolate_user_scope_by_agent": True,- "isolate_agent_scope_by_user": False,},headers=trusted_headers(account="platform",@@ -955,5 +836,5 @@ async def test_trusted_mode_create_account_persists_namespace_policy(assert resp.status_code == 200manager = trusted_admin_app.state.api_key_manager- assert manager.get_account_policy(acct).isolate_user_scope_by_agent is True- assert manager.get_account_policy(acct).isolate_agent_scope_by_user is False+ account = next(item for item in manager.get_accounts() if item["account_id"] == acct)+ assert set(account) == {"account_id", "created_at", "user_count"}diff --git a/tests/server/test_admin_rebuild_api.py b/tests/server/test_admin_rebuild_api.pyindex d1a46a911..387668261 100644--- a/tests/server/test_admin_rebuild_api.py+++ b/tests/server/test_admin_rebuild_api.py@@ -110,7 +110,7 @@ async def test_reindex_resource_vectors_only_wait_true(monkeypatch):}ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)request = ReindexRequest(uri="viking://resources/demo", mode="vectors_only", wait=True)@@ -144,7 +144,7 @@ async def test_reindex_resource_vectors_only_wait_false(monkeypatch):}ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)request = ReindexRequest(uri="viking://resources/demo", mode="vectors_only", wait=False)@@ -185,7 +185,7 @@ async def test_reindex_memory_semantic_and_vectors_rebuilds_full_subtree(monkeypservice = ReindexExecutor()counters = _ReindexCounters()ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)@@ -216,10 +216,10 @@ async def test_reindex_executor_infers_resource_and_skill_container_scopes():assert service._infer_target_type("viking://resources") == "resource"assert service._infer_target_type("viking://resources/demo.md") == "resource"- assert service._infer_target_type("viking://agent/default/skills") == "skill_namespace"- assert service._infer_target_type("viking://agent/default/skills/demo") == "skill"+ assert service._infer_target_type("viking://user/default/skills") == "skill_namespace"+ assert service._infer_target_type("viking://user/default/skills/demo") == "skill"with pytest.raises(OpenVikingError, match="Unsupported reindex URI"):- service._infer_target_type("viking://agent/default/skills/demo/SKILL.md")+ service._infer_target_type("viking://user/default/skills/demo/SKILL.md")@pytest.mark.asyncio@@ -233,13 +233,13 @@ async def test_reindex_executor_infers_user_namespace_root():@pytest.mark.asyncio-async def test_reindex_executor_infers_agent_namespace_root():+async def test_reindex_executor_rejects_deprecated_agent_namespace_root():from openviking.service.reindex_executor import ReindexExecutorservice = ReindexExecutor()- assert service._infer_target_type("viking://agent/") == "agent_namespace"- assert service._infer_target_type("viking://agent/default") == "agent_namespace"+ with pytest.raises(OpenVikingError, match="viking://agent is deprecated"):+ service._infer_target_type("viking://agent/")@pytest.mark.asyncio@@ -263,16 +263,16 @@ async def test_reindex_executor_does_not_treat_resource_named_memories_as_memory== "resource")assert not classify_uri("viking://user/default/resources/memories-report.md").is_memory- assert not classify_uri("viking://agent/default/resources/memories-report.md").is_memory+ assert not classify_uri("viking://user/default/resources/memories-report.md").is_memory@pytest.mark.asyncioasync def test_reindex_executor_does_not_treat_skill_subdirectories_as_skill_roots():from openviking.core.namespace import classify_uri- assert classify_uri("viking://agent/default/skills/my_skill").is_skill_root- assert not classify_uri("viking://agent/default/skills/my_skill/assets").is_skill_root- assert not classify_uri("viking://agent/default/resources/skills-report.md").is_skill+ assert classify_uri("viking://user/default/skills/my_skill").is_skill_root+ assert not classify_uri("viking://user/default/skills/my_skill/assets").is_skill_root+ assert not classify_uri("viking://user/default/resources/skills-report.md").is_skill@pytest.mark.asyncio@@ -319,7 +319,7 @@ async def test_reindex_user_namespace_semantic_and_vectors_promotes_memory_mode(service = ReindexExecutor()counters = _ReindexCounters()ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)@@ -381,7 +381,7 @@ async def test_reindex_user_namespace_semantic_and_vectors_does_not_reprocess_meservice = ReindexExecutor()counters = _ReindexCounters()ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)@@ -438,7 +438,7 @@ async def test_reindex_user_namespace_semantic_and_vectors_skips_uncovered_root_service = ReindexExecutor()counters = _ReindexCounters()ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)@@ -454,140 +454,6 @@ async def test_reindex_user_namespace_semantic_and_vectors_skips_uncovered_root_assert "viking://user/default/profile.md" in counters.warnings[0]-async def test_reindex_agent_namespace_semantic_and_vectors_promotes_memory_and_skill_modes(- monkeypatch,-):- from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters-- class FakeVikingFS:- async def tree(- self,- uri,- output="original",- show_all_hidden=True,- node_limit=1000,- level_limit=None,- ctx=None,- ):- return [- {"uri": "viking://agent/default/memories", "isDir": True},- {"uri": "viking://agent/default/skills/demo", "isDir": True},- {"uri": "viking://agent/default/resources", "isDir": True},- ]-- seen = {"memory_modes": [], "skill_modes": [], "semantic_calls": [], "resource_calls": []}-- async def fake_reindex_memory(self, *, uri, mode, run):- seen["memory_modes"].append((uri, mode))-- async def fake_reindex_skill(self, *, uri, mode, run):- seen["skill_modes"].append((uri, mode))-- async def fake_run_semantic_processor(self, *, uri, context_type, ctx, lock=None):- seen["semantic_calls"].append((uri, context_type))-- async def fake_reindex_resource_vectors_from_entries(- self, *, root_uri, directories, files, counters, ctx- ):- seen["resource_calls"].append((root_uri, list(directories), list(files)))-- monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())- monkeypatch.setattr(ReindexExecutor, "_reindex_memory", fake_reindex_memory)- monkeypatch.setattr(ReindexExecutor, "_reindex_skill", fake_reindex_skill)- monkeypatch.setattr(ReindexExecutor, "_run_semantic_processor", fake_run_semantic_processor)- monkeypatch.setattr(- ReindexExecutor,- "_reindex_resource_vectors_from_entries",- fake_reindex_resource_vectors_from_entries,- )-- service = ReindexExecutor()- counters = _ReindexCounters()- ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),- role=Role.ROOT,- )-- await service._reindex_agent_namespace(- uri="viking://agent/default",- mode="semantic_and_vectors",- run=_make_reindex_run(ctx, counters),- )-- assert seen["memory_modes"] == [("viking://agent/default/memories", "semantic_and_vectors")]- assert seen["skill_modes"] == [("viking://agent/default/skills/demo", "semantic_and_vectors")]- assert seen["semantic_calls"] == [("viking://agent/default/resources", "resource")]- assert seen["resource_calls"]---async def test_reindex_agent_namespace_semantic_and_vectors_does_not_reprocess_memory_as_resource(- monkeypatch,-):- from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters-- class FakeVikingFS:- async def tree(- self,- uri,- output="original",- show_all_hidden=True,- node_limit=1000,- level_limit=None,- ctx=None,- ):- return [- {"uri": "viking://agent/default/memories", "isDir": True},- {"uri": "viking://agent/default/memories/cases", "isDir": True},- {"uri": "viking://agent/default/skills/demo", "isDir": True},- {"uri": "viking://agent/default/resources", "isDir": True},- ]-- seen = {"memory_modes": [], "skill_modes": [], "semantic_calls": []}-- async def fake_reindex_memory(self, *, uri, mode, run):- seen["memory_modes"].append((uri, mode))-- async def fake_reindex_skill(self, *, uri, mode, run):- seen["skill_modes"].append((uri, mode))-- async def fake_run_semantic_processor(self, *, uri, context_type, ctx, lock=None):- seen["semantic_calls"].append((uri, context_type))-- async def fake_reindex_resource_vectors_from_entries(- self, *, root_uri, directories, files, counters, ctx- ):- return None-- monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())- monkeypatch.setattr(ReindexExecutor, "_reindex_memory", fake_reindex_memory)- monkeypatch.setattr(ReindexExecutor, "_reindex_skill", fake_reindex_skill)- monkeypatch.setattr(ReindexExecutor, "_run_semantic_processor", fake_run_semantic_processor)- monkeypatch.setattr(- ReindexExecutor,- "_reindex_resource_vectors_from_entries",- fake_reindex_resource_vectors_from_entries,- )-- service = ReindexExecutor()- counters = _ReindexCounters()- ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),- role=Role.ROOT,- )-- await service._reindex_agent_namespace(- uri="viking://agent/default",- mode="semantic_and_vectors",- run=_make_reindex_run(ctx, counters),- )-- assert seen["memory_modes"] == [("viking://agent/default/memories", "semantic_and_vectors")]- assert seen["skill_modes"] == [("viking://agent/default/skills/demo", "semantic_and_vectors")]- assert seen["semantic_calls"] == [("viking://agent/default/resources", "resource")]--@pytest.mark.asyncioasync def test_reindex_skill_namespace_reindexes_only_skill_roots(monkeypatch):from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters@@ -605,9 +471,9 @@ async def test_reindex_skill_namespace_reindexes_only_skill_roots(monkeypatch):assert node_limit is Noneassert level_limit is Nonereturn [- {"uri": "viking://agent/default/skills/my_skill", "isDir": True},- {"uri": "viking://agent/default/skills/my_skill/assets", "isDir": True},- {"uri": "viking://agent/default/skills/my_skill/SKILL.md", "isDir": False},+ {"uri": "viking://user/default/skills/my_skill", "isDir": True},+ {"uri": "viking://user/default/skills/my_skill/assets", "isDir": True},+ {"uri": "viking://user/default/skills/my_skill/SKILL.md", "isDir": False},]seen = []@@ -621,17 +487,17 @@ async def test_reindex_skill_namespace_reindexes_only_skill_roots(monkeypatch):service = ReindexExecutor()counters = _ReindexCounters()ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)await service._reindex_skill_namespace(- uri="viking://agent/default/skills",+ uri="viking://user/default/skills",mode="semantic_and_vectors",run=_make_reindex_run(ctx, counters),)- assert seen == [("viking://agent/default/skills/my_skill", "semantic_and_vectors")]+ assert seen == [("viking://user/default/skills/my_skill", "semantic_and_vectors")]@pytest.mark.asyncio@@ -652,18 +518,15 @@ async def test_reindex_global_namespace_semantic_and_vectors_propagates_to_child):return [{"uri": "viking://user/default", "isDir": True},- {"uri": "viking://agent/default", "isDir": True},+ {"uri": "viking://user/default", "isDir": True},{"uri": "viking://resources", "isDir": True},]- seen = {"user_modes": [], "agent_modes": [], "semantic_calls": [], "resource_calls": []}+ seen = {"user_modes": [], "semantic_calls": [], "resource_calls": []}async def fake_reindex_user_namespace(self, *, uri, mode, run):seen["user_modes"].append((uri, mode))- async def fake_reindex_agent_namespace(self, *, uri, mode, run):- seen["agent_modes"].append((uri, mode))-async def fake_run_semantic_processor(self, *, uri, context_type, ctx, lock=None):seen["semantic_calls"].append((uri, context_type))@@ -674,7 +537,6 @@ async def test_reindex_global_namespace_semantic_and_vectors_propagates_to_childmonkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())monkeypatch.setattr(ReindexExecutor, "_reindex_user_namespace", fake_reindex_user_namespace)- monkeypatch.setattr(ReindexExecutor, "_reindex_agent_namespace", fake_reindex_agent_namespace)monkeypatch.setattr(ReindexExecutor, "_run_semantic_processor", fake_run_semantic_processor)monkeypatch.setattr(ReindexExecutor,@@ -685,7 +547,7 @@ async def test_reindex_global_namespace_semantic_and_vectors_propagates_to_childservice = ReindexExecutor()counters = _ReindexCounters()ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)@@ -696,7 +558,6 @@ async def test_reindex_global_namespace_semantic_and_vectors_propagates_to_child)assert seen["user_modes"] == [("viking://user/default", "semantic_and_vectors")]- assert seen["agent_modes"] == [("viking://agent/default", "semantic_and_vectors")]assert seen["semantic_calls"] == [("viking://resources", "resource")]assert seen["resource_calls"]@@ -723,7 +584,7 @@ async def test_reindex_fetch_existing_record_uses_get_context_by_uri(monkeypatchservice = ReindexExecutor()ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)@@ -799,7 +660,7 @@ async def test_reindex_resource_vectors_only_continues_after_single_record_failuservice = ReindexExecutor()counters = _ReindexCounters()ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)@@ -834,7 +695,7 @@ async def test_reindex_semantic_processor_runs_with_skip_vectorization(monkeypatservice = ReindexExecutor()ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)@@ -905,7 +766,7 @@ async def test_reindex_resource_l2_falls_back_to_vector_text_when_summary_missinservice = ReindexExecutor()counters = _ReindexCounters()ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)@@ -933,7 +794,7 @@ async def test_reindex_resource_vector_text_uses_existing_record_for_non_text(moservice = ReindexExecutor()ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)@@ -961,7 +822,7 @@ async def test_reindex_resource_vector_text_skips_non_text_body_without_summary(service = ReindexExecutor()ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)@@ -1011,7 +872,7 @@ async def test_reindex_resource_vectors_accepts_single_file_uri(monkeypatch):service = ReindexExecutor()counters = _ReindexCounters()ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)@@ -1061,7 +922,7 @@ async def test_reindex_memory_l2_falls_back_to_body_when_abstract_missing(monkeyservice = ReindexExecutor()counters = _ReindexCounters()ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)@@ -1113,7 +974,7 @@ async def test_reindex_memory_l2_strips_memory_fields_from_abstract(monkeypatch)service = ReindexExecutor()counters = _ReindexCounters()ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)@@ -1189,7 +1050,7 @@ async def test_reindex_memory_vectors_walks_deep_subtree(monkeypatch):service = ReindexExecutor()counters = _ReindexCounters()ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)@@ -1277,7 +1138,7 @@ async def test_reindex_memory_vectors_rebuilds_directory_levels_without_regeneraservice = ReindexExecutor()counters = _ReindexCounters()ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)@@ -1299,7 +1160,7 @@ async def test_reindex_memory_vectors_rebuilds_directory_levels_without_regenera@pytest.mark.asyncio-async def test_reindex_user_namespace_partitions_memory_and_resource(monkeypatch):+async def test_reindex_user_namespace_partitions_memory_skill_and_resource(monkeypatch):from openviking.service.reindex_executor import ReindexExecutor, _ReindexCountersclass FakeVikingFS:@@ -1315,17 +1176,23 @@ async def test_reindex_user_namespace_partitions_memory_and_resource(monkeypatchreturn [{"uri": "viking://user/default/memories", "isDir": True},{"uri": "viking://user/default/memories/preferences", "isDir": True},+ {"uri": "viking://user/default/skills", "isDir": True},+ {"uri": "viking://user/default/skills/my_skill", "isDir": True},{"uri": "viking://user/default/resources", "isDir": True},{"uri": "viking://user/default/resources/doc.md", "isDir": False},{"uri": "viking://user/default/profile.md", "isDir": False},{"uri": "viking://user/default/memories/preferences/theme.md", "isDir": False},+ {"uri": "viking://user/default/skills/my_skill/SKILL.md", "isDir": False},]- seen = {"memory": [], "resource_dirs": [], "resource_files": []}+ seen = {"memory": [], "skill": [], "resource_dirs": [], "resource_files": []}async def fake_reindex_memory(self, *, uri, mode, run):seen["memory"].append((uri, mode))+ async def fake_reindex_skill(self, *, uri, mode, run):+ seen["skill"].append((uri, mode))+async def fake_reindex_resource_vectors_from_entries(self,*,@@ -1340,6 +1207,7 @@ async def test_reindex_user_namespace_partitions_memory_and_resource(monkeypatchmonkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())monkeypatch.setattr(ReindexExecutor, "_reindex_memory", fake_reindex_memory)+ monkeypatch.setattr(ReindexExecutor, "_reindex_skill", fake_reindex_skill)monkeypatch.setattr(ReindexExecutor,"_reindex_resource_vectors_from_entries",@@ -1349,7 +1217,7 @@ async def test_reindex_user_namespace_partitions_memory_and_resource(monkeypatchservice = ReindexExecutor()counters = _ReindexCounters()ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)@@ -1360,8 +1228,10 @@ async def test_reindex_user_namespace_partitions_memory_and_resource(monkeypatch)assert seen["memory"] == [("viking://user/default/memories", "vectors_only")]+ assert seen["skill"] == [("viking://user/default/skills/my_skill", "vectors_only")]assert "viking://user/default/resources" in seen["resource_dirs"]assert "viking://user/default/memories" not in seen["resource_dirs"]+ assert "viking://user/default/skills" not in seen["resource_dirs"]assert seen["resource_files"] == ["viking://user/default/resources/doc.md","viking://user/default/profile.md",@@ -1369,86 +1239,7 @@ async def test_reindex_user_namespace_partitions_memory_and_resource(monkeypatch@pytest.mark.asyncio-async def test_reindex_agent_namespace_partitions_memory_skill_and_resource(monkeypatch):- from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters-- class FakeVikingFS:- async def tree(- self,- uri,- output="original",- show_all_hidden=True,- node_limit=1000,- level_limit=None,- ctx=None,- ):- return [- {"uri": "viking://agent/default/memories", "isDir": True},- {"uri": "viking://agent/default/memories/cases", "isDir": True},- {"uri": "viking://agent/default/skills", "isDir": True},- {"uri": "viking://agent/default/skills/my_skill", "isDir": True},- {"uri": "viking://agent/default/resources", "isDir": True},- {"uri": "viking://agent/default/resources/doc.md", "isDir": False},- {"uri": "viking://agent/default/notes.md", "isDir": False},- {"uri": "viking://agent/default/memories/cases/a.md", "isDir": False},- {"uri": "viking://agent/default/skills/my_skill/SKILL.md", "isDir": False},- ]-- seen = {"memory": [], "skill": [], "resource_dirs": [], "resource_files": []}-- async def fake_reindex_memory(self, *, uri, mode, run):- seen["memory"].append((uri, mode))-- async def fake_reindex_skill(self, *, uri, mode, run):- seen["skill"].append((uri, mode))-- async def fake_reindex_resource_vectors_from_entries(- self,- *,- root_uri,- directories,- files,- counters,- ctx,- ):- seen["resource_dirs"] = list(directories)- seen["resource_files"] = list(files)-- monkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())- monkeypatch.setattr(ReindexExecutor, "_reindex_memory", fake_reindex_memory)- monkeypatch.setattr(ReindexExecutor, "_reindex_skill", fake_reindex_skill)- monkeypatch.setattr(- ReindexExecutor,- "_reindex_resource_vectors_from_entries",- fake_reindex_resource_vectors_from_entries,- )-- service = ReindexExecutor()- counters = _ReindexCounters()- ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),- role=Role.ROOT,- )-- await service._reindex_agent_namespace(- uri="viking://agent/",- mode="vectors_only",- run=_make_reindex_run(ctx, counters),- )-- assert seen["memory"] == [("viking://agent/default/memories", "vectors_only")]- assert seen["skill"] == [("viking://agent/default/skills/my_skill", "vectors_only")]- assert "viking://agent/default/resources" in seen["resource_dirs"]- assert "viking://agent/default/memories" not in seen["resource_dirs"]- assert "viking://agent/default/skills" not in seen["resource_dirs"]- assert seen["resource_files"] == [- "viking://agent/default/resources/doc.md",- "viking://agent/default/notes.md",- ]---async def test_reindex_global_namespace_partitions_user_agent_and_resources(monkeypatch):+async def test_reindex_global_namespace_partitions_user_and_resources(monkeypatch):from openviking.service.reindex_executor import ReindexExecutor, _ReindexCountersclass FakeVikingFS:@@ -1465,9 +1256,8 @@ async def test_reindex_global_namespace_partitions_user_agent_and_resources(monk{"uri": "viking://user", "isDir": True},{"uri": "viking://user/default", "isDir": True},{"uri": "viking://user/default/memories", "isDir": True},- {"uri": "viking://agent", "isDir": True},- {"uri": "viking://agent/default", "isDir": True},- {"uri": "viking://agent/default/skills", "isDir": True},+ {"uri": "viking://user/default", "isDir": True},+ {"uri": "viking://user/default/skills", "isDir": True},{"uri": "viking://session", "isDir": True},{"uri": "viking://session/default", "isDir": True},{"uri": "viking://resources", "isDir": True},@@ -1476,14 +1266,11 @@ async def test_reindex_global_namespace_partitions_user_agent_and_resources(monk{"uri": "viking://README.md", "isDir": False},]- seen = {"user": [], "agent": [], "resource_dirs": [], "resource_files": []}+ seen = {"user": [], "resource_dirs": [], "resource_files": []}async def fake_reindex_user_namespace(self, *, uri, mode, run):seen["user"].append((uri, mode))- async def fake_reindex_agent_namespace(self, *, uri, mode, run):- seen["agent"].append((uri, mode))-async def fake_reindex_resource_vectors_from_entries(self,*,@@ -1498,7 +1285,6 @@ async def test_reindex_global_namespace_partitions_user_agent_and_resources(monkmonkeypatch.setattr("openviking.service.reindex_executor.get_viking_fs", lambda: FakeVikingFS())monkeypatch.setattr(ReindexExecutor, "_reindex_user_namespace", fake_reindex_user_namespace)- monkeypatch.setattr(ReindexExecutor, "_reindex_agent_namespace", fake_reindex_agent_namespace)monkeypatch.setattr(ReindexExecutor,"_reindex_resource_vectors_from_entries",@@ -1508,7 +1294,7 @@ async def test_reindex_global_namespace_partitions_user_agent_and_resources(monkservice = ReindexExecutor()counters = _ReindexCounters()ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)@@ -1519,11 +1305,9 @@ async def test_reindex_global_namespace_partitions_user_agent_and_resources(monk)assert seen["user"] == [("viking://user/default", "vectors_only")]- assert seen["agent"] == [("viking://agent/default", "vectors_only")]assert "viking://resources" in seen["resource_dirs"]assert "viking://" not in seen["resource_dirs"]assert "viking://user" not in seen["resource_dirs"]- assert "viking://agent" not in seen["resource_dirs"]assert "viking://session" not in seen["resource_dirs"]assert "viking://session/default" not in seen["resource_dirs"]assert seen["resource_files"] == ["viking://resources/demo.txt"]@@ -1568,17 +1352,17 @@ async def test_reindex_skill_l2_falls_back_to_skill_content_when_abstract_missinservice = ReindexExecutor()counters = _ReindexCounters()ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ROOT,)await service._reindex_skill_vectors(- uri="viking://agent/skills/my_skill",+ uri="viking://user/skills/my_skill",counters=counters,ctx=ctx,)- assert seen["viking://agent/skills/my_skill/SKILL.md"]["abstract"] == "skill abstract"+ assert seen["viking://user/skills/my_skill/SKILL.md"]["abstract"] == "skill abstract"@pytest.mark.asyncio@@ -1605,7 +1389,7 @@ async def test_openviking_service_reindex_uses_default_root_context(monkeypatch)service = OpenVikingService.__new__(OpenVikingService)service._initialized = True- service._user = UserIdentifier(account_id="acct", user_id="alice", agent_id="assistant")+ service._user = UserIdentifier(account_id="acct", user_id="alice")result = await OpenVikingService.reindex(service,@@ -1618,4 +1402,3 @@ async def test_openviking_service_reindex_uses_default_root_context(monkeypatch)assert seen["ctx"].role == Role.ROOTassert seen["ctx"].user.account_id == "acct"assert seen["ctx"].user.user_id == "alice"- assert seen["ctx"].user.agent_id == "assistant"diff --git a/tests/server/test_api_content.py b/tests/server/test_api_content.pyindex 433e5e56a..ecfbffa3b 100644--- a/tests/server/test_api_content.py+++ b/tests/server/test_api_content.py@@ -154,7 +154,7 @@ async def test_reindex_uses_request_tenant_for_exists(monkeypatch):return {"status": "completed", "uri": uri, "mode": mode}ctx = RequestContext(- user=UserIdentifier(account_id="test", user_id="alice", agent_id="default"),+ user=UserIdentifier(account_id="test", user_id="alice"),role=Role.ADMIN,)request = ReindexRequest(diff --git a/tests/server/test_api_key_manager.py b/tests/server/test_api_key_manager.pyindex 46ff06ee2..8bd5df6d1 100644--- a/tests/server/test_api_key_manager.py+++ b/tests/server/test_api_key_manager.py@@ -9,7 +9,7 @@ import pytestimport pytest_asynciofrom openviking.server.api_keys import APIKeyManager-from openviking.server.identity import AccountNamespacePolicy, Role+from openviking.server.identity import Rolefrom openviking.service.core import OpenVikingServicefrom openviking_cli.exceptions import AlreadyExistsError, NotFoundError, UnauthenticatedErrorfrom openviking_cli.session.user_id import UserIdentifier@@ -113,7 +113,6 @@ async def test_default_account_exists(manager: APIKeyManager):"""Default account should be created on load."""accounts = manager.get_accounts()assert any(a["account_id"] == "default" for a in accounts)- assert manager.get_account_policy("default") == AccountNamespacePolicy()# ---- User lifecycle tests ----@@ -254,8 +253,8 @@ async def test_persistence_across_reload(manager_service):assert identity.role == Role.ADMIN-async def test_legacy_account_without_settings_infers_user_and_agent_policy(manager_service):- """Legacy accounts default to user-shared + agent-shared and persist the inferred policy."""+async def test_legacy_account_without_settings_loads_without_namespace_settings(manager_service):+ """Legacy accounts no longer create account settings during load."""acct = _uid()created_at = "2026-04-16T00:00:00+00:00"@@ -274,18 +273,12 @@ async def test_legacy_account_without_settings_infers_user_and_agent_policy(mana)await mgr.load()- assert mgr.get_account_policy(acct) == AccountNamespacePolicy(- isolate_user_scope_by_agent=False,- isolate_agent_scope_by_user=False,- )+ identity = mgr.resolve("legacy-key-alice")+ assert identity.account_id == acct+ assert identity.user_id == "alice"settings = await mgr._read_json(f"/local/{acct}/_system/setting.json")- assert settings == {- "namespace": {- "isolate_user_scope_by_agent": False,- "isolate_agent_scope_by_user": False,- }- }+ assert settings is None# ---- Encryption tests ----diff --git a/tests/server/test_api_local_input_security.py b/tests/server/test_api_local_input_security.pyindex fffcc8292..af476767f 100644--- a/tests/server/test_api_local_input_security.py+++ b/tests/server/test_api_local_input_security.py@@ -42,7 +42,7 @@ description: temp uploaded skillassert resp.status_code == 200body = resp.json()assert body["status"] == "ok"- assert body["result"]["uri"].startswith("viking://agent/default/skills/")+ assert body["result"]["uri"].startswith("viking://user/default/skills/")async def test_add_skill_rejects_direct_local_path(client: httpx.AsyncClient):@@ -82,7 +82,7 @@ description: inlineassert resp.status_code == 200body = resp.json()assert body["status"] == "ok"- assert body["result"]["uri"].startswith("viking://agent/default/skills/")+ assert body["result"]["uri"].startswith("viking://user/default/skills/")@pytest.fixturediff --git a/tests/server/test_api_resources.py b/tests/server/test_api_resources.pyindex a3a0ea6e1..7074d22c5 100644--- a/tests/server/test_api_resources.py+++ b/tests/server/test_api_resources.py@@ -7,7 +7,6 @@ import asyncioimport zipfileimport httpx-import pytestfrom openviking.storage.viking_fs import get_viking_fsfrom openviking.telemetry import get_current_telemetry@@ -288,17 +287,6 @@ async def test_add_resource_rejects_events_only_telemetry(assert "events" in body["error"]["message"]-async def test_add_resource_file_not_found(client: httpx.AsyncClient):- resp = await client.post(- "/api/v1/resources",- json={"path": "/nonexistent/file.txt", "reason": "test"},- )- assert resp.status_code == 403- body = resp.json()- assert body["status"] == "error"- assert body["error"]["code"] == "PERMISSION_DENIED"--async def test_add_resource_with_to(client: httpx.AsyncClient,sample_markdown_file,@@ -503,7 +491,6 @@ async def test_add_resource_with_watch_interval_auto_binds_root_uri(account_id="default",user_id="test_user",role="ROOT",- agent_id="default",)assert task is not Noneassert task.to_uri == root_uri@@ -622,6 +609,7 @@ async def test_shared_temp_upload_and_add_resource_deletes_upload_dir(async def test_shared_temp_upload_failed_consume_is_retryable(client: httpx.AsyncClient,+ app,service,monkeypatch,):@@ -636,11 +624,13 @@ async def test_shared_temp_upload_failed_consume_is_retryable(raise RuntimeError("boom")monkeypatch.setattr(service.resources, "add_resource", fake_add_resource)- with pytest.raises(RuntimeError, match="boom"):- await client.post(+ transport = httpx.ASGITransport(app=app, raise_app_exceptions=False)+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as http_client:+ resp = await http_client.post("/api/v1/resources",json={"temp_file_id": temp_file_id, "reason": "shared upload", "wait": True},)+ assert resp.status_code == 500upload_id = temp_file_id[len("shared_") :]meta_uri = f"viking://upload/{upload_id}/meta.json"diff --git a/tests/server/test_api_search.py b/tests/server/test_api_search.pyindex 3a028a1f2..86e9db46f 100644--- a/tests/server/test_api_search.py+++ b/tests/server/test_api_search.py@@ -20,9 +20,15 @@ from openviking_cli.session.user_id import UserIdentifier@pytest.fixture(autouse=True)def fake_query_embedder(service):class FakeEmbedder:+ def prepare_embedding_input(self, text: str) -> str:+ return text+def embed(self, text: str, is_query: bool = False) -> EmbedResult:return EmbedResult(dense_vector=[0.1, 0.2, 0.3])+ async def embed_async(self, text: str, is_query: bool = False) -> EmbedResult:+ return self.embed(text, is_query=is_query)+service.viking_fs.query_embedder = FakeEmbedder()@@ -320,7 +326,7 @@ async def test_find_with_inaccessible_target_uri_returns_permission_denied(try:resp = await client.post("/api/v1/search/find",- json={"query": "sample", "target_uri": "viking://agent/foreign-agent", "limit": 5},+ json={"query": "sample", "target_uri": "viking://user/foreign/memories", "limit": 5},)finally:app.dependency_overrides.pop(get_request_context, None)diff --git a/tests/server/test_api_sessions.py b/tests/server/test_api_sessions.pyindex cb246c741..961535c53 100644--- a/tests/server/test_api_sessions.py+++ b/tests/server/test_api_sessions.py@@ -12,8 +12,7 @@ import pytestfrom fastapi import FastAPIfrom starlette.requests import Request-from openviking.message import Message-from openviking.server.api_keys import APIKeyManager+from openviking.message import Message, TextPartfrom openviking.server.app import create_appfrom openviking.server.config import ServerConfig, ToolOutputExternalizationConfigfrom openviking.server.dependencies import set_service@@ -34,19 +33,15 @@ def _message_request(*,content: str | None = None,parts: list[dict] | None = None,- role_id: object = _UNSET,+ peer_id: object = _UNSET,) -> dict:payload = {"role": role}if content is not None:payload["content"] = contentif parts is not None:payload["parts"] = parts- if role_id is _UNSET and role == "user":- payload["role_id"] = DEFAULT_USER.user_id- elif role_id is _UNSET and role == "assistant":- payload["role_id"] = DEFAULT_USER.agent_id- elif role_id is not None:- payload["role_id"] = role_id+ if peer_id is not _UNSET and peer_id is not None:+ payload["peer_id"] = peer_idreturn payload@@ -303,10 +298,17 @@ async def test_get_session_context_includes_incomplete_archive_messages(session = service.sessions.session(ctx, session_id)await session.load()pending_messages = [- Message.create_user("Pending user message", role_id=DEFAULT_USER.user_id),- Message.create_assistant(- "Pending assistant response",- role_id=DEFAULT_USER.agent_id,+ Message(+ id="pending-user",+ role="user",+ parts=[TextPart("Pending user message")],+ peer_id=DEFAULT_USER.user_id,+ ),+ Message(+ id="pending-assistant",+ role="assistant",+ parts=[TextPart("Pending assistant response")],+ peer_id="assistant-default",),]await session._viking_fs.write_file(@@ -377,97 +379,10 @@ async def test_add_message_splits_tool_result_aggregate(client: httpx.AsyncClienassert body["result"]["message_count"] == 2-async def test_add_message_root_request_autofills_role_id(service, monkeypatch):- session_id = "root-auto-fill"- ctx = RequestContext(user=DEFAULT_USER, role=Role.ROOT)-- response = await _call_add_message_route(- service,- monkeypatch,- ctx=ctx,- payload=_message_request("user", content="hello root", role_id=None),- session_id=session_id,- )-- assert response.result["message_count"] == 1- session = await service.sessions.get(session_id, ctx, auto_create=False)- await session.load()- assert session.messages[-1].role_id == DEFAULT_USER.user_id---async def test_add_message_trusted_request_allows_explicit_role_id(service, monkeypatch):- session_id = "trusted-explicit-role-id"- ctx = RequestContext(- user=UserIdentifier("acct_trusted", "caller", "assistant-a"),- role=Role.USER,- )-- response = await _call_add_message_route(- service,- monkeypatch,- ctx=ctx,- payload=_message_request("assistant", content="hello trusted", role_id="assistant-b"),- session_id=session_id,- )-- assert response.result["message_count"] == 1- session = await service.sessions.get(session_id, ctx, auto_create=False)- await session.load()- assert session.messages[-1].role_id == "assistant-b"---async def test_add_message_admin_request_allows_registered_user_role_id(service, monkeypatch):- manager = APIKeyManager(root_key=TEST_ROOT_KEY, viking_fs=service.viking_fs)- await manager.load()- account_id = "acct_session_admin"- await manager.create_account(account_id, "admin_user")- await manager.register_user(account_id, "alice")-- ctx = RequestContext(- user=UserIdentifier(account_id, "admin_user", "assistant-admin"),- role=Role.ADMIN,- )- session_id = "admin-explicit-role-id"-- response = await _call_add_message_route(- service,- monkeypatch,- ctx=ctx,- payload=_message_request("user", content="hello admin", role_id="alice"),- session_id=session_id,- )-- assert response.result["message_count"] == 1- session = await service.sessions.get(session_id, ctx, auto_create=False)- await session.load()- assert session.messages[-1].role_id == "alice"---async def test_add_message_user_request_allows_explicit_role_id(service, monkeypatch):- session_id = "user-explicit-role-id"- ctx = RequestContext(- user=UserIdentifier("acct_session_user", "alice", "assistant-user"),- role=Role.USER,- )-- response = await _call_add_message_route(- service,- monkeypatch,- ctx=ctx,- payload=_message_request("user", content="hello user", role_id="wx/user-01@abc"),- session_id=session_id,- )-- assert response.result["message_count"] == 1- session = await service.sessions.get(session_id, ctx, auto_create=False)- await session.load()- assert session.messages[-1].role_id == "wx/user-01@abc"---async def test_add_message_user_request_autofills_role_id(service, monkeypatch):- session_id = "user-auto-fill-role-id"+async def test_add_message_request_persists_peer_id(service, monkeypatch):+ session_id = "trusted-peer-id"ctx = RequestContext(- user=UserIdentifier("acct_session_user", "alice", "assistant-user"),+ user=UserIdentifier("acct_trusted", "caller"),role=Role.USER,)@@ -475,39 +390,14 @@ async def test_add_message_user_request_autofills_role_id(service, monkeypatch):service,monkeypatch,ctx=ctx,- payload=_message_request("assistant", content="hello user", role_id=None),+ payload=_message_request("assistant", content="hello trusted", peer_id="assistant-b"),session_id=session_id,)assert response.result["message_count"] == 1session = await service.sessions.get(session_id, ctx, auto_create=False)await session.load()- assert session.messages[-1].role_id == "assistant-user"---async def test_add_message_admin_request_allows_unregistered_user_role_id(service, monkeypatch):- manager = APIKeyManager(root_key=TEST_ROOT_KEY, viking_fs=service.viking_fs)- await manager.load()- account_id = "acct_session_invalid"- await manager.create_account(account_id, "admin_user")-- ctx = RequestContext(- user=UserIdentifier(account_id, "admin_user", "assistant-admin"),- role=Role.ADMIN,- )-- response = await _call_add_message_route(- service,- monkeypatch,- ctx=ctx,- payload=_message_request("user", content="hello invalid", role_id="ghost"),- session_id="invalid-user-role-id",- )-- assert response.result["message_count"] == 1- session = await service.sessions.get("invalid-user-role-id", ctx, auto_create=False)- await session.load()- assert session.messages[-1].role_id == "ghost"+ assert session.messages[-1].peer_id == "assistant-b"async def test_add_multiple_messages(client: httpx.AsyncClient):diff --git a/tests/server/test_api_watches.py b/tests/server/test_api_watches.pyindex 96f2a7a4b..59d468d7f 100644--- a/tests/server/test_api_watches.py+++ b/tests/server/test_api_watches.py@@ -22,7 +22,6 @@ async def _seed(to_uri="viking://resources/test/foo",account="default",user="default",- agent="default",role="user",interval=60.0,path="https://example.com/foo",@@ -31,7 +30,6 @@ async def _seed(path=path,account_id=account,user_id=user,- agent_id=agent,original_role=role,to_uri=to_uri,watch_interval=interval,@@ -166,8 +164,7 @@ async def test_dual_key_mismatch_returns_400(client: httpx.AsyncClient, watch_maasync def test_delete_missing_key_400(client: httpx.AsyncClient):"""DELETE /watches without {task_id} path and without ?to_uri= must 400."""resp = await client.delete("/api/v1/watches")- # The by-uri route requires to_uri as a Query(...) so FastAPI will 422 it.- assert resp.status_code == 422+ assert resp.status_code == 400async def test_not_found_404(client: httpx.AsyncClient):@@ -186,7 +183,7 @@ async def test_patch_rejects_non_positive_watch_interval(client: httpx.AsyncClieto WatchManager.update_task, which deactivates the task and stores thebad cadence. A later resume (`is_active=true`) then fails insideupdate_task with ValueError → 404, misleading callers about the root- cause. Reject upfront with 422 instead, matching CLI/MCP semantics.+ cause. Reject upfront through the structured 400 error mapper."""task = await _seed(watch_manager, to_uri="viking://resources/test/nonpos")for bad in [-1, 0, -42.5]:@@ -194,14 +191,14 @@ async def test_patch_rejects_non_positive_watch_interval(client: httpx.AsyncClief"/api/v1/watches/{task.task_id}",json={"watch_interval": bad},)- assert resp.status_code == 422, (- f"watch_interval={bad} should be 422, got {resp.status_code}: {resp.text[:200]}"+ assert resp.status_code == 400, (+ f"watch_interval={bad} should be 400, got {resp.status_code}: {resp.text[:200]}")async def test_patch_rejects_unknown_field(client: httpx.AsyncClient, watch_manager):"""UpdateWatchRequest has extra='forbid'; passing a field outside the allowed- set (watch_interval / is_active / reason / instruction) returns 422.+ set (watch_interval / is_active / reason / instruction) returns 400.Note: `to_uri` is intentionally NOT exposed via PATCH. WatchManager'supdate_task supports rebinding to_uri (which is the only mutation that can@@ -213,7 +210,7 @@ async def test_patch_rejects_unknown_field(client: httpx.AsyncClient, watch_manaf"/api/v1/watches/{task.task_id}",json={"to_uri": "viking://resources/test/other"},)- assert resp.status_code == 422+ assert resp.status_code == 400async def test_trigger_by_uri(client: httpx.AsyncClient, watch_manager, monkeypatch):diff --git a/tests/server/test_auth.py b/tests/server/test_auth.pyindex f11e72a4f..fd453d539 100644--- a/tests/server/test_auth.py+++ b/tests/server/test_auth.py@@ -3,8 +3,6 @@"""Tests for multi-tenant authentication (openviking/server/auth.py)."""-import io-import loggingimport uuidimport httpx@@ -15,7 +13,6 @@ from fastapi import Request as FastAPIRequestfrom fastapi.responses import JSONResponsefrom starlette.requests import Request-from openviking.server import app as server_app_modulefrom openviking.server.app import create_appfrom openviking.server.auth import get_request_context, resolve_identityfrom openviking.server.config import ServerConfig, _is_localhost, validate_server_config@@ -24,7 +21,12 @@ from openviking.server.identity import ResolvedIdentity, Rolefrom openviking.server.models import ERROR_CODE_TO_HTTP_STATUS, ErrorInfo, Responsefrom openviking.service.core import OpenVikingServicefrom openviking.service.task_store import PersistentTaskStore-from openviking.service.task_tracker import TaskTracker, get_task_tracker, reset_task_tracker, set_task_tracker+from openviking.service.task_tracker import (+ TaskTracker,+ get_task_tracker,+ reset_task_tracker,+ set_task_tracker,+)from openviking_cli.exceptions import InvalidArgumentError, OpenVikingError, PermissionDeniedErrorfrom openviking_cli.session.user_id import UserIdentifier@@ -62,8 +64,7 @@ class _FakeAgfs:return [{"name": file_path[len(prefix) + 1 :], "path": file_path, "is_dir": False}for file_path in self.files- if file_path.startswith(prefix + "/")- and "/" not in file_path[len(prefix) + 1 :]+ if file_path.startswith(prefix + "/") and "/" not in file_path[len(prefix) + 1 :]]def rm(self, path: str, recursive: bool = False, force: bool = True):@@ -238,8 +239,9 @@ async def auth_client(auth_app):async def user_key(auth_app):"""Create a test user and return its key."""manager = auth_app.state.api_key_manager- key = await manager.create_account(_uid(), "test_admin")- return key+ account_id = _uid()+ await manager.create_account(account_id, "test_admin")+ return await manager.register_user(account_id, "test_user")# ---- Basic auth tests ----@@ -332,8 +334,8 @@ async def test_auth_on_multiple_endpoints(auth_client: httpx.AsyncClient):"/api/v1/fs/ls?uri=viking://",headers={"X-API-Key": ROOT_KEY},)- assert tenant_resp.status_code == 400- assert tenant_resp.json()["error"]["code"] == "INVALID_ARGUMENT"+ assert tenant_resp.status_code == 403+ assert tenant_resp.json()["error"]["code"] == "PERMISSION_DENIED"tenant_resp = await auth_client.get("/api/v1/fs/ls?uri=viking://",@@ -343,7 +345,8 @@ async def test_auth_on_multiple_endpoints(auth_client: httpx.AsyncClient):"X-OpenViking-User": "default",},)- assert tenant_resp.status_code == 200+ assert tenant_resp.status_code == 403+ assert tenant_resp.json()["error"]["code"] == "PERMISSION_DENIED"async def test_task_endpoints_require_auth():@@ -378,10 +381,10 @@ async def test_task_endpoints_are_user_scoped():)alice_app = _build_task_http_test_app(- ResolvedIdentity(role=Role.ADMIN, account_id=account_id, user_id="alice")+ ResolvedIdentity(role=Role.USER, account_id=account_id, user_id="alice"))bob_app = _build_task_http_test_app(- ResolvedIdentity(role=Role.ADMIN, account_id=account_id, user_id="bob")+ ResolvedIdentity(role=Role.USER, account_id=account_id, user_id="bob"))alice_transport = httpx.ASGITransport(app=alice_app)bob_transport = httpx.ASGITransport(app=bob_app)@@ -424,17 +427,8 @@ async def test_user_key_cannot_access_admin_api(auth_client: httpx.AsyncClient,assert resp.status_code == 403-async def test_agent_id_header_forwarded(auth_client: httpx.AsyncClient):- """X-OpenViking-Agent header should be captured in identity."""- resp = await auth_client.get(- "/api/v1/system/status",- headers={"X-API-Key": ROOT_KEY, "X-OpenViking-Agent": "my-agent"},- )- assert resp.status_code == 200---async def test_admin_key_can_switch_effective_user_and_agent_within_account(auth_app):- """ADMIN keys may reuse X-OpenViking-User/Agent within their own account."""+async def test_admin_key_cannot_switch_effective_user_within_account(auth_app):+ """ADMIN API keys cannot assert a different data-plane user in api_key mode."""manager = auth_app.state.api_key_manageraccount_id = _uid()admin_key = await manager.create_account(account_id, "admin_user")@@ -446,24 +440,18 @@ async def test_admin_key_can_switch_effective_user_and_agent_within_account(auth"X-API-Key": admin_key,"X-OpenViking-Account": account_id,"X-OpenViking-User": "alice",- "X-OpenViking-Agent": "assistant-2",},auth_enabled=True,api_key_manager=manager,)- identity = await resolve_identity(- request,- x_api_key=admin_key,- x_openviking_account=account_id,- x_openviking_user="alice",- x_openviking_agent="assistant-2",- )-- assert identity.role == Role.ADMIN- assert identity.account_id == account_id- assert identity.user_id == "alice"- assert identity.agent_id == "assistant-2"+ with pytest.raises(PermissionDeniedError, match="X-OpenViking-Account"):+ await resolve_identity(+ request,+ x_api_key=admin_key,+ x_openviking_account=account_id,+ x_openviking_user="alice",+ )async def test_admin_key_cannot_switch_account_via_header(auth_app):@@ -490,8 +478,8 @@ async def test_admin_key_cannot_switch_account_via_header(auth_app):)-async def test_user_key_can_switch_agent_but_not_user(auth_app):- """USER keys may set agent context but may not impersonate another user."""+async def test_user_key_resolves_to_key_user_and_cannot_switch_user(auth_app):+ """USER keys resolve to their owner and may not impersonate another user."""manager = auth_app.state.api_key_manageraccount_id = _uid()await manager.create_account(account_id, "admin_user")@@ -501,7 +489,6 @@ async def test_user_key_can_switch_agent_but_not_user(auth_app):"/api/v1/resources",headers={"X-API-Key": user_key,- "X-OpenViking-Agent": "assistant-7",},auth_enabled=True,api_key_manager=manager,@@ -510,13 +497,11 @@ async def test_user_key_can_switch_agent_but_not_user(auth_app):identity = await resolve_identity(request,x_api_key=user_key,- x_openviking_agent="assistant-7",)assert identity.role == Role.USERassert identity.account_id == account_idassert identity.user_id == "alice"- assert identity.agent_id == "assistant-7"forbidden_request = _make_request("/api/v1/resources",@@ -539,8 +524,12 @@ async def test_user_key_can_switch_agent_but_not_user(auth_app):async def test_cross_tenant_session_get_returns_not_found(auth_client: httpx.AsyncClient, auth_app):"""A user must not access another tenant's session by session_id."""manager = auth_app.state.api_key_manager- alice_key = await manager.create_account(_uid(), "alice")- bob_key = await manager.create_account(_uid(), "bob")+ alice_account_id = _uid()+ bob_account_id = _uid()+ await manager.create_account(alice_account_id, "alice_admin")+ await manager.create_account(bob_account_id, "bob_admin")+ alice_key = await manager.register_user(alice_account_id, "alice")+ bob_key = await manager.register_user(bob_account_id, "bob")create_resp = await auth_client.post("/api/v1/sessions", json={}, headers={"X-API-Key": alice_key}@@ -568,12 +557,12 @@ async def test_cross_tenant_session_get_returns_not_found(auth_client: httpx.Asyassert cross_get.json()["error"]["code"] == "NOT_FOUND"-async def test_root_tenant_scoped_requests_require_explicit_identity():- """ROOT must specify account/user headers on tenant-scoped APIs."""+async def test_root_tenant_scoped_requests_rejected_in_api_key_mode():+ """ROOT API keys cannot access tenant-scoped data APIs in api_key mode."""request = _make_request("/api/v1/resources", auth_enabled=True)identity = ResolvedIdentity(role=Role.ROOT, account_id="default", user_id="default")- with pytest.raises(InvalidArgumentError, match="X-OpenViking-Account"):+ with pytest.raises(PermissionDeniedError, match="ROOT API keys"):await get_request_context(request, identity)@@ -589,8 +578,8 @@ async def test_root_system_status_allows_implicit_default_identity():assert ctx.user.user_id == "default"-async def test_root_tenant_scoped_requests_allow_explicit_identity():- """ROOT can access tenant-scoped APIs when account/user headers are present."""+async def test_root_tenant_scoped_requests_reject_explicit_identity_in_api_key_mode():+ """Header identity assertion belongs to trusted mode, not ROOT API key access."""request = _make_request("/api/v1/resources",headers={@@ -601,36 +590,29 @@ async def test_root_tenant_scoped_requests_allow_explicit_identity():)identity = ResolvedIdentity(role=Role.ROOT, account_id="acme", user_id="alice")- ctx = await get_request_context(request, identity)-- assert ctx.role == Role.ROOT- assert ctx.user.account_id == "acme"- assert ctx.user.user_id == "alice"+ with pytest.raises(PermissionDeniedError, match="ROOT API keys"):+ await get_request_context(request, identity)-async def test_root_reindex_requests_require_explicit_account():- """ROOT reindex must select an account because indexes are account-scoped."""+async def test_root_reindex_requests_rejected_in_api_key_mode():+ """ROOT API keys cannot select tenant data through data-plane reindex."""request = _make_request("/api/v1/content/reindex", auth_enabled=True)identity = ResolvedIdentity(role=Role.ROOT, account_id="default", user_id="default")- with pytest.raises(InvalidArgumentError, match="X-OpenViking-Account"):+ with pytest.raises(PermissionDeniedError, match="ROOT API keys"):await get_request_context(request, identity)-async def test_root_reindex_requests_allow_account_without_user():- """ROOT reindex is account-scoped and does not require a user header."""- request = _make_request(- "/api/v1/content/reindex",- headers={"X-OpenViking-Account": "acme"},- auth_enabled=True,- )- identity = ResolvedIdentity(role=Role.ROOT, account_id="acme", user_id="default")+async def test_admin_reindex_requests_use_key_owner_in_api_key_mode():+ """ADMIN reindex is allowed for the admin key's own account only."""+ request = _make_request("/api/v1/content/reindex", auth_enabled=True)+ identity = ResolvedIdentity(role=Role.ADMIN, account_id="acme", user_id="admin")ctx = await get_request_context(request, identity)- assert ctx.role == Role.ROOT+ assert ctx.role == Role.ADMINassert ctx.user.account_id == "acme"- assert ctx.user.user_id == "default"+ assert ctx.user.user_id == "admin"async def test_root_monitoring_requests_allow_implicit_default_identity():@@ -656,12 +638,12 @@ async def test_root_system_wait_allows_implicit_default_identity():assert ctx.role == Role.ROOT-async def test_root_debug_vector_requests_require_explicit_identity():- """Tenant-scoped debug routes must not bypass explicit tenant checks."""+async def test_root_debug_vector_requests_rejected_in_api_key_mode():+ """Tenant-scoped debug routes cannot use ROOT API keys in api_key mode."""request = _make_request("/api/v1/debug/vector/scroll", auth_enabled=True)identity = ResolvedIdentity(role=Role.ROOT, account_id="default", user_id="default")- with pytest.raises(InvalidArgumentError, match="X-OpenViking-Account"):+ with pytest.raises(PermissionDeniedError, match="ROOT API keys"):await get_request_context(request, identity)@@ -677,8 +659,8 @@ async def test_dev_mode_root_tenant_scoped_requests_allow_implicit_identity():assert ctx.user.user_id == "default"-async def test_root_tenant_scoped_requests_return_structured_400_via_http():- """Tenant-scoped HTTP routes should reject implicit ROOT tenant fallback."""+async def test_root_tenant_scoped_requests_return_structured_403_via_http():+ """Tenant-scoped HTTP routes should reject ROOT API-key data-plane access."""app = _build_auth_http_test_app(ResolvedIdentity(role=Role.ROOT, account_id="default", user_id="default"),auth_enabled=True,@@ -688,8 +670,8 @@ async def test_root_tenant_scoped_requests_return_structured_400_via_http():async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:response = await client.get("/api/v1/fs/ls")- assert response.status_code == 400- assert response.json()["error"]["code"] == "INVALID_ARGUMENT"+ assert response.status_code == 403+ assert response.json()["error"]["code"] == "PERMISSION_DENIED"async def test_root_monitoring_requests_keep_200_via_http():@@ -722,8 +704,8 @@ async def test_root_system_wait_keeps_200_via_http():assert response.json()["status"] == "ok"-async def test_root_debug_vector_requests_return_structured_400_via_http():- """Tenant-scoped debug routes should reject implicit ROOT tenant fallback."""+async def test_root_debug_vector_requests_return_structured_403_via_http():+ """Tenant-scoped debug routes should reject ROOT API-key data-plane access."""app = _build_auth_http_test_app(ResolvedIdentity(role=Role.ROOT, account_id="default", user_id="default"),auth_enabled=True,@@ -733,8 +715,8 @@ async def test_root_debug_vector_requests_return_structured_400_via_http():async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:response = await client.get("/api/v1/debug/vector/scroll")- assert response.status_code == 400- assert response.json()["error"]["code"] == "INVALID_ARGUMENT"+ assert response.status_code == 403+ assert response.json()["error"]["code"] == "PERMISSION_DENIED"async def test_dev_mode_root_tenant_scoped_requests_keep_200_via_http():@@ -759,7 +741,6 @@ async def test_trusted_mode_allows_header_identity_without_api_key():headers={"X-OpenViking-Account": "acme","X-OpenViking-User": "alice",- "X-OpenViking-Agent": "assistant-1",},auth_enabled=False,auth_mode="trusted",@@ -769,13 +750,11 @@ async def test_trusted_mode_allows_header_identity_without_api_key():request,x_openviking_account="acme",x_openviking_user="alice",- x_openviking_agent="assistant-1",)assert identity.role == Role.USERassert identity.account_id == "acme"assert identity.user_id == "alice"- assert identity.agent_id == "assistant-1"async def test_trusted_mode_defaults_role_to_user():@@ -934,7 +913,6 @@ async def test_trusted_mode_with_root_api_key_accepts_matching_api_key():"X-API-Key": ROOT_KEY,"X-OpenViking-Account": "acme","X-OpenViking-User": "alice",- "X-OpenViking-Agent": "assistant-1",},auth_enabled=False,auth_mode="trusted",@@ -946,13 +924,11 @@ async def test_trusted_mode_with_root_api_key_accepts_matching_api_key():x_api_key=ROOT_KEY,x_openviking_account="acme",x_openviking_user="alice",- x_openviking_agent="assistant-1",)assert identity.role == Role.USERassert identity.account_id == "acme"assert identity.user_id == "alice"- assert identity.agent_id == "assistant-1"async def test_trusted_mode_tenant_http_routes_require_explicit_identity_headers():@@ -986,7 +962,6 @@ async def test_trusted_mode_tenant_http_routes_accept_explicit_identity_headers(headers={"X-OpenViking-Account": "acme","X-OpenViking-User": "alice",- "X-OpenViking-Agent": "assistant-1",},)@@ -1074,7 +1049,6 @@ async def test_trusted_mode_http_routes_accept_api_key_when_root_key_configured("X-API-Key": ROOT_KEY,"X-OpenViking-Account": "acme","X-OpenViking-User": "alice",- "X-OpenViking-Agent": "assistant-1",},)@@ -1082,27 +1056,6 @@ async def test_trusted_mode_http_routes_accept_api_key_when_root_key_configured(assert response.json()["result"] == {"account_id": "acme", "user_id": "alice"}-async def test_trusted_mode_startup_log_mentions_root_key_requirement_when_configured(- auth_service,-):- """Trusted mode startup warning should mention the configured server API key requirement."""- config = ServerConfig(auth_mode="trusted", root_api_key=ROOT_KEY)- app = create_app(config=config, service=auth_service)- log_stream = io.StringIO()- handler = logging.StreamHandler(log_stream)- handler.setFormatter(logging.Formatter("%(message)s"))- server_app_module.logger.addHandler(handler)-- try:- async with app.router.lifespan_context(app):- pass- finally:- server_app_module.logger.removeHandler(handler)-- assert "configured server API key" in log_stream.getvalue()--# ---- _is_localhost tests ----@@ -1168,27 +1121,6 @@ async def test_trusted_mode_admin_api_without_identity_defaults_to_root():assert identity.role == Role.ROOTassert identity.account_id == "trusted"assert identity.user_id == "trusted"- assert identity.agent_id == "default"---async def test_trusted_mode_admin_api_without_identity_accepts_agent_header():- """Trusted mode admin APIs without identity should still respect X-OpenViking-Agent."""- request = _make_request(- "/api/v1/admin/accounts",- headers={"X-OpenViking-Agent": "my-admin-agent"},- auth_enabled=False,- auth_mode="trusted",- )-- identity = await resolve_identity(- request,- x_openviking_agent="my-admin-agent",- )-- assert identity.role == Role.ROOT- assert identity.account_id == "trusted"- assert identity.user_id == "trusted"- assert identity.agent_id == "my-admin-agent"async def test_trusted_mode_admin_api_with_partial_identity_still_requires_full_identity():diff --git a/tests/server/test_content_write_service.py b/tests/server/test_content_write_service.pyindex fd658e6f0..6a8927c90 100644--- a/tests/server/test_content_write_service.py+++ b/tests/server/test_content_write_service.py@@ -49,7 +49,7 @@ async def test_write_denies_foreign_user_memory_space(service):await service.viking_fs.write_file(memory_uri, "Owner note", ctx=owner_ctx)foreign_ctx = RequestContext(- user=UserIdentifier(owner_ctx.account_id, "other_user", owner_ctx.user.agent_id),+ user=UserIdentifier(owner_ctx.account_id, "other_user"),role=Role.USER,)diff --git a/tests/server/test_http_client_sdk.py b/tests/server/test_http_client_sdk.pyindex 99cbd192a..23a4d1657 100644--- a/tests/server/test_http_client_sdk.py+++ b/tests/server/test_http_client_sdk.py@@ -11,19 +11,22 @@ import pytest_asynciofrom openviking_cli.client.http import AsyncHTTPClientfrom openviking_cli.exceptions import ConflictError, FailedPreconditionError, ProcessingError-from tests.server.conftest import SAMPLE_MD_CONTENT, SDK_ROOT_API_KEY, TEST_TMP_DIR+from tests.server.conftest import SAMPLE_MD_CONTENT, TEST_TMP_DIRfrom tests.server.ovpack_test_helpers import build_ovpack_bytes@pytest_asyncio.fixture()async def http_client(running_server):"""Create an AsyncHTTPClient connected to the running server."""- port, svc = running_server+ port, svc, sdk_user_key = running_serverclient = AsyncHTTPClient(url=f"http://127.0.0.1:{port}",- api_key=SDK_ROOT_API_KEY,- account="default",- user="sdk_test_user",+ api_key=sdk_user_key,+ account="",+ user="",+ timeout=33.0,+ extra_headers={},+ profile_enabled=False,)await client.initialize()yield client, svc@@ -113,7 +116,7 @@ description: SDK localhost upload testassert "root_uri" in resultassert "uri" in resultassert result["root_uri"] == result["uri"]- assert result["uri"].startswith("viking://agent/default/skills/")+ assert result["uri"].startswith("viking://user/sdk_test_user/skills/")async def test_sdk_import_ovpack_from_local_file(http_client):@@ -213,13 +216,13 @@ async def test_sdk_batch_add_messages_and_commit_keep_recent_count(http_client):[{"role": "user",- "role_id": "sdk-user-1",+ "peer_id": "sdk-user-1","created_at": "2026-05-01T12:00:00Z","parts": [{"type": "text", "text": "Batch hello"}],},{"role": "assistant",- "role_id": "sdk-bot-1",+ "peer_id": "sdk-bot-1","created_at": "2026-05-01T12:00:05Z","parts": [{"type": "text", "text": "Batch answer"},@@ -241,7 +244,7 @@ async def test_sdk_batch_add_messages_and_commit_keep_recent_count(http_client):pre_commit = await client.get_session_context(session_id)assert [m["role"] for m in pre_commit["messages"]] == ["user", "assistant", "user"]- assert pre_commit["messages"][0]["role_id"] == "sdk-user-1"+ assert pre_commit["messages"][0]["peer_id"] == "sdk-user-1"assert pre_commit["messages"][0]["created_at"] == "2026-05-01T12:00:00Z"assert pre_commit["messages"][1]["parts"][1]["type"] == "context"assert pre_commit["messages"][1]["parts"][1]["abstract"] == "SDK doc abstract"diff --git a/tests/server/test_identity.py b/tests/server/test_identity.pyindex 450a708c1..77dae0f79 100644--- a/tests/server/test_identity.py+++ b/tests/server/test_identity.py@@ -4,11 +4,9 @@"""Tests for identity types (openviking/server/identity.py)."""from openviking.server.identity import (- AccountNamespacePolicy,RequestContext,ResolvedIdentity,Role,- ToolContext,)from openviking_cli.session.user_id import UserIdentifier@@ -33,7 +31,6 @@ def test_resolved_identity_defaults():assert identity.role == Role.ROOTassert identity.account_id is Noneassert identity.user_id is None- assert identity.agent_id is Nonedef test_resolved_identity_with_all_fields():@@ -42,38 +39,16 @@ def test_resolved_identity_with_all_fields():role=Role.USER,account_id="acme",user_id="bob",- agent_id="my-agent",)assert identity.role == Role.USERassert identity.account_id == "acme"assert identity.user_id == "bob"- assert identity.agent_id == "my-agent"def test_request_context_account_id_property():"""RequestContext.account_id should delegate to user.account_id."""- user = UserIdentifier("acme", "bob", "agent1")+ user = UserIdentifier("acme", "bob")ctx = RequestContext(user=user, role=Role.USER)assert ctx.account_id == "acme"assert ctx.role == Role.USERassert ctx.user.account_id == "acme"---def test_tool_context_proxies_namespace_policy_from_request_context():- policy = AccountNamespacePolicy(- isolate_user_scope_by_agent=True,- isolate_agent_scope_by_user=True,- )- request_ctx = RequestContext(- user=UserIdentifier(- account_id="test-account",- user_id="test-user",- agent_id="test-agent",- ),- role=Role.USER,- namespace_policy=policy,- )-- tool_ctx = ToolContext(viking_fs=object(), request_ctx=request_ctx)-- assert tool_ctx.namespace_policy is policydiff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.pyindex 31451157b..887fdb100 100644--- a/tests/server/test_mcp_endpoint.py+++ b/tests/server/test_mcp_endpoint.py@@ -245,23 +245,16 @@ async def test_store_batch_messages(service):assert "2 message" in result-async def test_store_populates_role_id_from_ctx(service, monkeypatch):- """Regression: MCP store used to persist role_id=None because it skipped the- HTTP router's fallback resolver. With ctx.resolve_role_id, user msgs should- get user.user_id and assistant msgs should get user.agent_id.-- We capture role_id at the add_message boundary instead of reading it back from- storage, because store() commits the session synchronously and committed- messages move out of session.messages into archive files.- """+async def test_store_does_not_autofill_peer_id_from_ctx(service, monkeypatch):+ """MCP store should not create synthetic peer_id values."""from openviking.session.session import Sessioncaptured: list[tuple[str, str | None]] = []original = Session.add_message- def _spy(self, role, parts, role_id=None, created_at=None):- captured.append((role, role_id))- return original(self, role, parts, role_id=role_id, created_at=created_at)+ def _spy(self, role, parts, peer_id=None, created_at=None):+ captured.append((role, peer_id))+ return original(self, role, parts, peer_id=peer_id, created_at=created_at)monkeypatch.setattr(Session, "add_message", _spy)@@ -273,8 +266,8 @@ async def test_store_populates_role_id_from_ctx(service, monkeypatch):)assert captured == [- ("user", DEFAULT_CTX.user.user_id),- ("assistant", DEFAULT_CTX.user.agent_id),+ ("user", None),+ ("assistant", None),]@@ -283,8 +276,8 @@ async def test_store_skips_empty_message_content(service, monkeypatch):def __init__(self):self.messages = []- def add_message(self, role, parts, role_id=None, created_at=None):- self.messages.append((role, parts, role_id, created_at))+ def add_message(self, role, parts, peer_id=None, created_at=None):+ self.messages.append((role, parts, peer_id, created_at))fake_session = FakeSession()monkeypatch.setattr(service.sessions, "get", AsyncMock(return_value=fake_session))@@ -299,10 +292,10 @@ async def test_store_skips_empty_message_content(service, monkeypatch):assert "2 message" in resultassert len(fake_session.messages) == 1- role, parts, role_id, created_at = fake_session.messages[0]+ role, parts, peer_id, created_at = fake_session.messages[0]assert role == "assistant"assert parts[0].text == "Noted."- assert role_id == DEFAULT_CTX.user.agent_id+ assert peer_id is Noneassert created_at is Noneservice.sessions.commit_async.assert_awaited_once()@@ -489,7 +482,6 @@ async def _seed_watch(service, to_uri="viking://resources/test/foo"):path="https://example.com/foo",account_id=DEFAULT_CTX.account_id,user_id=DEFAULT_CTX.user.user_id,- agent_id=DEFAULT_CTX.user.agent_id,original_role="root",to_uri=to_uri,watch_interval=1440.0,diff --git a/tests/server/test_peer_id_compat.py b/tests/server/test_peer_id_compat.pynew file mode 100644index 000000000..043ddae0d--- /dev/null+++ b/tests/server/test_peer_id_compat.py@@ -0,0 +1,129 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++"""Peer ID compatibility tests."""++import pytest++from openviking.core.peer_id import normalize_peer_id+from openviking.core.retrieval_targets import default_target_directories, resolve_retrieval_targets+from openviking.server.identity import RequestContext, Role+from openviking_cli.exceptions import InvalidArgumentError+from openviking_cli.retrieve import ContextType+from openviking_cli.session.user_id import UserIdentifier+++def test_normalize_peer_id_accepts_peer_id():+ assert normalize_peer_id("web:visitor:alice") == "web:visitor:alice"+++def _target_dirs(target_uri="", peer_id=None):+ ctx = RequestContext(user=UserIdentifier("acct", "support_bot"), role=Role.USER)+ return resolve_retrieval_targets(target_uri, ctx, peer_id).target_directories+++def test_default_search_targets_user_memory_without_all_peer_memories():+ targets = _target_dirs()++ assert targets == [+ "viking://user/support_bot/memories",+ "viking://resources",+ "viking://user/support_bot/skills",+ ]+++def test_default_peer_search_targets_self_and_requested_peer_memories():+ targets = _target_dirs(peer_id="web:visitor:alice")++ assert targets == [+ "viking://user/support_bot/memories",+ "viking://user/support_bot/peers/web:visitor:alice/memories",+ "viking://resources",+ "viking://user/support_bot/skills",+ ]+++def test_peer_search_keeps_explicit_target_uri():+ targets = _target_dirs("viking://resources/docs", peer_id="web:visitor:alice")++ assert targets == ["viking://resources/docs"]+++def test_peer_search_expands_default_user_memory_target():+ targets = _target_dirs("viking://user/memories", peer_id="web:visitor:alice")++ assert targets == [+ "viking://user/support_bot/memories",+ "viking://user/support_bot/peers/web:visitor:alice/memories",+ ]+++def test_peer_search_explicit_peer_root_targets_that_peer_memory():+ targets = _target_dirs("viking://user/support_bot/peers/web:visitor:alice")++ assert targets == ["viking://user/support_bot/peers/web:visitor:alice/memories"]+++def test_peer_search_explicit_peer_memory_matches_peer_id():+ targets = _target_dirs(+ "viking://user/support_bot/peers/web:visitor:alice/memories",+ peer_id="web:visitor:alice",+ )++ assert targets == ["viking://user/support_bot/peers/web:visitor:alice/memories"]+++def test_peer_search_explicit_peer_target_rejects_mismatched_peer_id():+ with pytest.raises(InvalidArgumentError, match="target_uri peer does not match peer_id"):+ _target_dirs(+ "viking://user/support_bot/peers/web:visitor:alice/memories",+ peer_id="web:visitor:bob",+ )+++def test_peer_search_rejects_all_peers_target():+ with pytest.raises(InvalidArgumentError, match="all peer memories"):+ _target_dirs("viking://user/support_bot/peers")+++def test_peer_search_user_root_targets_user_memory_and_skills_only():+ targets = _target_dirs("viking://user", peer_id="web:visitor:alice")++ assert targets == [+ "viking://user/support_bot/memories",+ "viking://user/support_bot/peers/web:visitor:alice/memories",+ "viking://user/support_bot/skills",+ ]+++def test_peer_search_expands_canonical_user_memory_target():+ targets = _target_dirs(+ "viking://user/support_bot/memories",+ peer_id="web:visitor:alice",+ )++ assert targets == [+ "viking://user/support_bot/memories",+ "viking://user/support_bot/peers/web:visitor:alice/memories",+ ]+++def test_peer_search_list_expands_only_default_memory_targets():+ targets = _target_dirs(+ ["viking://user/memories", "viking://resources/docs"],+ peer_id="web:visitor:alice",+ )++ assert targets == [+ "viking://user/support_bot/memories",+ "viking://user/support_bot/peers/web:visitor:alice/memories",+ "viking://resources/docs",+ ]+++def test_default_memory_roots_exclude_all_peer_memories():+ ctx = RequestContext(user=UserIdentifier("acct", "support_bot"), role=Role.USER)++ assert default_target_directories(ctx, context_type=ContextType.MEMORY) == [+ "viking://user/support_bot/memories",+ ]diff --git a/tests/server/test_privacy_config_service.py b/tests/server/test_privacy_config_service.pyindex 6b8f7c243..e4b801262 100644--- a/tests/server/test_privacy_config_service.py+++ b/tests/server/test_privacy_config_service.py@@ -3,9 +3,10 @@import pytest+from openviking.core.namespace import canonical_user_rootfrom openviking.privacy.skill_extractor import extract_skill_privacy_valuesfrom openviking.privacy.skill_placeholder import placeholderize_skill_content_with_blocks-from openviking.server.identity import AccountNamespacePolicy, RequestContext, Role+from openviking.server.identity import RequestContext, Rolefrom openviking_cli.session.user_id import UserIdentifier@@ -55,7 +56,6 @@ async def test_privacy_config_service_versions(service):async def test_skill_read_restores_placeholder(service):ctx = RequestContext(user=UserIdentifier.the_default_user("privacy_restore"), role=Role.ROOT)await service.initialize_user_directories(ctx)- await service.initialize_agent_directories(ctx)await service.resources.add_skill(data={@@ -67,10 +67,9 @@ async def test_skill_read_restores_placeholder(service):wait=False,)- stored = await service.viking_fs.read_file(- "viking://agent/skills/restore-skill/SKILL.md", ctx=ctx- )- restored = await service.fs.read("viking://agent/skills/restore-skill/SKILL.md", ctx=ctx)+ skill_file_uri = f"{canonical_user_root(ctx)}/skills/restore-skill/SKILL.md"+ stored = await service.viking_fs.read_file(skill_file_uri, ctx=ctx)+ restored = await service.fs.read(skill_file_uri, ctx=ctx)assert "secret-xyz" not in storedassert "{{ov_privacy:skill:restore-skill:api_key}}" in stored@@ -79,12 +78,11 @@ async def test_skill_read_restores_placeholder(service):@pytest.mark.asyncio-async def test_skill_read_restores_placeholder_with_agent_segment(service):+async def test_skill_read_restores_placeholder_with_user_shorthand(service):ctx = RequestContext(- user=UserIdentifier.the_default_user("privacy_restore_agent_segment"), role=Role.ROOT+ user=UserIdentifier.the_default_user("privacy_restore_user_shorthand"), role=Role.ROOT)await service.initialize_user_directories(ctx)- await service.initialize_agent_directories(ctx)await service.resources.add_skill(data={@@ -97,7 +95,7 @@ async def test_skill_read_restores_placeholder_with_agent_segment(service):)restored = await service.fs.read(- "viking://agent/default/skills/restore-skill-agent-segment/SKILL.md",+ "viking://user/skills/restore-skill-agent-segment/SKILL.md",ctx=ctx,)@@ -134,9 +132,8 @@ async def test_skill_read_appends_notice_for_unreplaced_placeholders(service):user=UserIdentifier.the_default_user("privacy_partial_restore"), role=Role.ROOT)await service.initialize_user_directories(ctx)- await service.initialize_agent_directories(ctx)- skill_uri = "viking://agent/skills/partial-restore-skill"+ skill_uri = f"{canonical_user_root(ctx)}/skills/partial-restore-skill"await service.viking_fs.mkdir(skill_uri, exist_ok=True, ctx=ctx)await service.viking_fs.write_file(f"{skill_uri}/SKILL.md",@@ -169,9 +166,8 @@ async def test_skill_read_appends_notice_for_extra_configured_keys(service):user=UserIdentifier.the_default_user("privacy_extra_config"), role=Role.ROOT)await service.initialize_user_directories(ctx)- await service.initialize_agent_directories(ctx)- skill_uri = "viking://agent/skills/extra-config-skill"+ skill_uri = f"{canonical_user_root(ctx)}/skills/extra-config-skill"await service.viking_fs.mkdir(skill_uri, exist_ok=True, ctx=ctx)await service.viking_fs.write_file(f"{skill_uri}/SKILL.md",@@ -195,11 +191,10 @@ async def test_skill_read_appends_notice_for_extra_configured_keys(service):@pytest.mark.asyncio-async def test_privacy_config_service_uses_policy_aware_user_root(service):+async def test_privacy_config_service_uses_user_root(service):ctx = RequestContext(- user=UserIdentifier("acme", "privacy_user_policy", "demo-agent"),+ user=UserIdentifier("acme", "privacy_user_policy"),role=Role.USER,- namespace_policy=AccountNamespacePolicy(isolate_user_scope_by_agent=True),)await service.initialize_user_directories(ctx)diff --git a/tests/server/test_request_wait_tracking.py b/tests/server/test_request_wait_tracking.pyindex 1ec6f1fef..8eacc3ff7 100644--- a/tests/server/test_request_wait_tracking.py+++ b/tests/server/test_request_wait_tracking.py@@ -177,7 +177,7 @@ async def test_add_skill_wait_uses_request_tracker(service, monkeypatch):async def _fake_process_skill(**kwargs):del kwargs- return {"status": "success", "uri": "viking://agent/skills/demo", "name": "demo"}+ return {"status": "success", "uri": "viking://user/default/skills/demo", "name": "demo"}monkeypatch.setattr(service.resources._skill_processor, "process_skill", _fake_process_skill)monkeypatch.setattr(@@ -218,7 +218,7 @@ async def test_add_skill_wait_uses_request_tracker_when_telemetry_disabled(serviasync def _fake_process_skill(**kwargs):del kwargs- return {"status": "success", "uri": "viking://agent/skills/demo", "name": "demo"}+ return {"status": "success", "uri": "viking://user/default/skills/demo", "name": "demo"}monkeypatch.setattr(service.resources._skill_processor, "process_skill", _fake_process_skill)monkeypatch.setattr(@@ -239,7 +239,7 @@ async def test_add_skill_wait_uses_request_tracker_when_telemetry_disabled(servitimeout=9.0,)- assert result["root_uri"] == "viking://agent/skills/demo"+ assert result["root_uri"] == "viking://user/default/skills/demo"assert result["queue_status"] == tracker.queue_statusassert tracker.registered_requests == [telemetry.telemetry_id]assert tracker.wait_calls == [(telemetry.telemetry_id, 9.0)]diff --git a/tests/server/test_resources_temp_upload_signed.py b/tests/server/test_resources_temp_upload_signed.pyindex f2ce25bba..bd789b72e 100644--- a/tests/server/test_resources_temp_upload_signed.py+++ b/tests/server/test_resources_temp_upload_signed.py@@ -19,8 +19,8 @@ def _reset_token_store():upload_token_store.clear()-def _issue(account_id: str = "acct", user_id: str = "user", agent_id: str = "agent"):- token, _ = upload_token_store.issue(account_id, user_id, agent_id, ttl_seconds=600)+def _issue(account_id: str = "acct", user_id: str = "user"):+ token, _ = upload_token_store.issue(account_id, user_id, ttl_seconds=600)return tokendiff --git a/tests/server/test_temp_scope_acl.py b/tests/server/test_temp_scope_acl.pyindex 1be456590..c30e9708c 100644--- a/tests/server/test_temp_scope_acl.py+++ b/tests/server/test_temp_scope_acl.py@@ -115,11 +115,11 @@ def viking_fs():@pytest.mark.asyncioasync def test_temp_scope_isolated_between_users_in_same_account(viking_fs):owner_ctx = RequestContext(- user=UserIdentifier(account_id="acct1", user_id="alice", agent_id="agent1"),+ user=UserIdentifier(account_id="acct1", user_id="alice"),role=Role.USER,)other_ctx = RequestContext(- user=UserIdentifier(account_id="acct1", user_id="bob", agent_id="agent2"),+ user=UserIdentifier(account_id="acct1", user_id="bob"),role=Role.USER,)@@ -141,11 +141,11 @@ async def test_temp_scope_isolated_between_users_in_same_account(viking_fs):@pytest.mark.asyncioasync def test_temp_scope_user_id_matching_legacy_pattern_stays_isolated(viking_fs):owner_ctx = RequestContext(- user=UserIdentifier(account_id="acct1", user_id="04011234_abcdef", agent_id="agent1"),+ user=UserIdentifier(account_id="acct1", user_id="04011234_abcdef"),role=Role.USER,)other_ctx = RequestContext(- user=UserIdentifier(account_id="acct1", user_id="bob", agent_id="agent2"),+ user=UserIdentifier(account_id="acct1", user_id="bob"),role=Role.USER,)@@ -163,11 +163,11 @@ async def test_temp_scope_user_id_matching_legacy_pattern_stays_isolated(viking_@pytest.mark.asyncioasync def test_temp_root_listing_only_shows_callers_own_entries(viking_fs):alice_ctx = RequestContext(- user=UserIdentifier(account_id="acct1", user_id="alice", agent_id="agent1"),+ user=UserIdentifier(account_id="acct1", user_id="alice"),role=Role.USER,)bob_ctx = RequestContext(- user=UserIdentifier(account_id="acct1", user_id="bob", agent_id="agent2"),+ user=UserIdentifier(account_id="acct1", user_id="bob"),role=Role.USER,)@@ -196,7 +196,7 @@ async def test_temp_root_listing_only_shows_callers_own_entries(viking_fs):@pytest.mark.asyncioasync def test_temp_root_destructive_operations_are_blocked_for_non_root_users(viking_fs):alice_ctx = RequestContext(- user=UserIdentifier(account_id="acct1", user_id="alice", agent_id="agent1"),+ user=UserIdentifier(account_id="acct1", user_id="alice"),role=Role.USER,)@@ -210,11 +210,11 @@ async def test_temp_root_destructive_operations_are_blocked_for_non_root_users(v@pytest.mark.asyncioasync def test_legacy_temp_trees_remain_accessible_for_same_account_users(viking_fs):alice_ctx = RequestContext(- user=UserIdentifier(account_id="acct1", user_id="alice", agent_id="agent1"),+ user=UserIdentifier(account_id="acct1", user_id="alice"),role=Role.USER,)bob_ctx = RequestContext(- user=UserIdentifier(account_id="acct1", user_id="bob", agent_id="agent2"),+ user=UserIdentifier(account_id="acct1", user_id="bob"),role=Role.USER,)@@ -234,7 +234,7 @@ async def test_legacy_temp_trees_remain_accessible_for_same_account_users(vikingdef test_create_temp_uri_uses_user_scope_segment(viking_fs):ctx = RequestContext(- user=UserIdentifier(account_id="acct1", user_id="alice", agent_id="agent1"),+ user=UserIdentifier(account_id="acct1", user_id="alice"),role=Role.USER,)@@ -253,11 +253,11 @@ def test_create_temp_uri_without_context_preserves_legacy_shape(viking_fs):@pytest.mark.asyncioasync def test_legacy_temp_uri_remains_accessible_to_same_account_users(viking_fs):alice_ctx = RequestContext(- user=UserIdentifier(account_id="acct1", user_id="alice", agent_id="agent1"),+ user=UserIdentifier(account_id="acct1", user_id="alice"),role=Role.USER,)bob_ctx = RequestContext(- user=UserIdentifier(account_id="acct1", user_id="bob", agent_id="agent2"),+ user=UserIdentifier(account_id="acct1", user_id="bob"),role=Role.USER,)@@ -273,11 +273,11 @@ async def test_legacy_temp_uri_remains_accessible_to_same_account_users(viking_f@pytest.mark.asyncioasync def test_non_root_cannot_delete_temp_root_recursively(viking_fs):alice_ctx = RequestContext(- user=UserIdentifier(account_id="acct1", user_id="alice", agent_id="agent1"),+ user=UserIdentifier(account_id="acct1", user_id="alice"),role=Role.USER,)bob_ctx = RequestContext(- user=UserIdentifier(account_id="acct1", user_id="bob", agent_id="agent2"),+ user=UserIdentifier(account_id="acct1", user_id="bob"),role=Role.USER,)diff --git a/tests/server/test_watch_task_acl.py b/tests/server/test_watch_task_acl.pyindex 02adf3d21..bd5584de3 100644--- a/tests/server/test_watch_task_acl.py+++ b/tests/server/test_watch_task_acl.py@@ -26,7 +26,7 @@ def root_ctx() -> RequestContext:@pytest.fixturedef user_ctx() -> RequestContext:- return RequestContext(user=UserIdentifier("default", "alice", "default"), role=Role.USER)+ return RequestContext(user=UserIdentifier("default", "alice"), role=Role.USER)@pytest.fixturediff --git a/tests/service/test_reindex_file_lock.py b/tests/service/test_reindex_file_lock.pyindex 48f824e57..8ca48f7cb 100644--- a/tests/service/test_reindex_file_lock.py+++ b/tests/service/test_reindex_file_lock.py@@ -53,7 +53,7 @@ async def test_reindex_single_file_uri_acquires_tree_lock_without_not_a_directorexecutor._fetch_existing_record = AsyncMock(return_value=None)executor._upsert_context = AsyncMock()ctx = RequestContext(- user=UserIdentifier("acc1", "test_user", "test_agent"),+ user=UserIdentifier("acc1", "test_user"),role=Role.ROOT,)diff --git a/tests/service/test_resource_service_watch.py b/tests/service/test_resource_service_watch.pyindex 98ba4b35e..d1dd210a3 100644--- a/tests/service/test_resource_service_watch.py+++ b/tests/service/test_resource_service_watch.py@@ -21,7 +21,6 @@ async def get_task_by_uri(service: ResourceService, to_uri: str, ctx: RequestConaccount_id=ctx.account_id,user_id=ctx.user.user_id,role=ctx.role.value,- agent_id=ctx.user.agent_id,)@@ -79,7 +78,7 @@ async def resource_service(watch_manager: WatchManager) -> AsyncGenerator[Resourdef request_context() -> RequestContext:"""Create request context for testing."""return RequestContext(- user=UserIdentifier("test_account", "test_user", "test_agent"),+ user=UserIdentifier("test_account", "test_user"),role=Role.USER,)@@ -272,7 +271,7 @@ class TestWatchTaskConflict:):to_uri = "viking://resources/cross_user_conflict"other_user_ctx = RequestContext(- user=UserIdentifier("test_account", "other_user", "other_agent"),+ user=UserIdentifier("test_account", "other_user"),role=Role.USER,)@@ -301,13 +300,12 @@ class TestWatchTaskConflict:assert task is not None@pytest.mark.asyncio- async def test_conflict_when_task_exists_but_hidden_by_other_agent(+ async def test_same_user_context_sees_existing_task(self, resource_service: ResourceService, request_context: RequestContext):- to_uri = "viking://resources/cross_agent_conflict"- other_agent_ctx = RequestContext(- user=UserIdentifier("test_account", "test_user", "other_agent"),- role=Role.USER,+ to_uri = "viking://resources/same_user_conflict"+ same_user_ctx = RequestContext(+ user=UserIdentifier("test_account", "test_user"), role=Role.USER)await resource_service.add_resource(@@ -317,18 +315,18 @@ class TestWatchTaskConflict:watch_interval=30.0,)- hidden_task = await get_task_by_uri(resource_service, to_uri, other_agent_ctx)- assert hidden_task is None+ visible_task = await get_task_by_uri(resource_service, to_uri, same_user_ctx)+ assert visible_task is not Nonewith pytest.raises(ConflictError) as exc_info:await resource_service.add_resource(path="/test/path2",- ctx=other_agent_ctx,+ ctx=same_user_ctx,to=to_uri,watch_interval=45.0,)- assert "already used by another task" in str(exc_info.value)+ assert "already being monitored" in str(exc_info.value)assert to_uri in str(exc_info.value)original_task = await get_task_by_uri(resource_service, to_uri, request_context)@@ -357,7 +355,6 @@ class TestWatchTaskConflict:account_id=request_context.account_id,user_id=request_context.user.user_id,role=request_context.role.value,- agent_id=request_context.user.agent_id,is_active=False,)@@ -452,13 +449,12 @@ class TestWatchTaskCancellation:assert result is not None@pytest.mark.asyncio- async def test_cancel_does_not_touch_other_agent_task(+ async def test_same_user_can_cancel_existing_task(self, resource_service: ResourceService, request_context: RequestContext):- to_uri = "viking://resources/cancel_other_agent"- other_agent_ctx = RequestContext(- user=UserIdentifier("test_account", "test_user", "other_agent"),- role=Role.USER,+ to_uri = "viking://resources/cancel_same_user"+ same_user_ctx = RequestContext(+ user=UserIdentifier("test_account", "test_user"), role=Role.USER)await resource_service.add_resource(@@ -470,14 +466,14 @@ class TestWatchTaskCancellation:await resource_service.add_resource(path="/test/path",- ctx=other_agent_ctx,+ ctx=same_user_ctx,to=to_uri,watch_interval=0,)original_task = await get_task_by_uri(resource_service, to_uri, request_context)assert original_task is not None- assert original_task.is_active is True+ assert original_task.is_active is Falseclass TestWatchTaskUpdate:@@ -508,7 +504,6 @@ class TestWatchTaskUpdate:account_id=request_context.account_id,user_id=request_context.user.user_id,role=request_context.role.value,- agent_id=request_context.user.agent_id,is_active=False,)diff --git a/tests/service/test_session_service_metrics.py b/tests/service/test_session_service_metrics.pyindex e038fc3d4..8fa3e5ff6 100644--- a/tests/service/test_session_service_metrics.py+++ b/tests/service/test_session_service_metrics.py@@ -14,7 +14,7 @@ from openviking_cli.session.user_id import UserIdentifierdef _make_ctx() -> RequestContext:return RequestContext(- user=UserIdentifier("acme", "alice", "agent1"),+ user=UserIdentifier("acme", "alice"),role=Role.ADMIN,)diff --git a/tests/session/conftest.py b/tests/session/conftest.pyindex d49df6270..432f0a089 100644--- a/tests/session/conftest.py+++ b/tests/session/conftest.py@@ -72,7 +72,7 @@ async def session_with_tool_call(tool_id=tool_id,tool_name="test_tool",tool_uri=f"viking://session/{session.session_id}/tools/{tool_id}",- skill_uri="viking://agent/skills/test_skill",+ skill_uri="viking://user/skills/test_skill",tool_input={"param": "value"},tool_status="running",)diff --git a/tests/session/memory/test_agent_experience_context_provider.py b/tests/session/memory/test_agent_experience_context_provider.pyindex f92a98474..4309014e7 100644--- a/tests/session/memory/test_agent_experience_context_provider.py+++ b/tests/session/memory/test_agent_experience_context_provider.py@@ -6,9 +6,10 @@ from unittest.mock import AsyncMock, patchimport pytest-from openviking.server.identity import AccountNamespacePolicy, RequestContext, Role-from openviking.session.memory.agent_experience_context_provider import AgentExperienceContextProvider-from openviking.session.memory.memory_updater import ExtractContext+from openviking.server.identity import RequestContext, Role+from openviking.session.memory.agent_experience_context_provider import (+ AgentExperienceContextProvider,+)from openviking_cli.session.user_id import UserIdentifier@@ -16,12 +17,12 @@ def test_create_tool_context_uses_extract_context_page_id_map():provider = AgentExperienceContextProvider(messages=[],trajectory_summary="album release party discussion",- trajectory_uri="viking://agent/agent_sample_9/memories/trajectories/album_release_party_discussion.md",+ trajectory_uri="viking://user/user_sample_9/memories/trajectories/album_release_party_discussion.md",)extract_context = provider.get_extract_context()extract_context.page_id_map.get_page_id(- "viking://agent/agent_sample_9/memories/trajectories/album_release_party_discussion.md"+ "viking://user/user_sample_9/memories/trajectories/album_release_party_discussion.md")tool_ctx = provider.create_tool_context()@@ -34,12 +35,11 @@ async def test_agent_experience_prefetch_starts_with_conversation_and_new_trajecprovider = AgentExperienceContextProvider(messages=[],trajectory_summary="album release party discussion",- trajectory_uri="viking://agent/agent_sample_9/memories/trajectories/album_release_party_discussion.md",+ trajectory_uri="viking://user/user_sample_9/memories/trajectories/album_release_party_discussion.md",)provider._ctx = RequestContext(- user=UserIdentifier(account_id="acc", user_id="user_1", agent_id="agent_sample_9"),+ user=UserIdentifier(account_id="acc", user_id="user_1"),role=Role.USER,- namespace_policy=AccountNamespacePolicy(),)provider._viking_fs = AsyncMock()provider._transaction_handle = None@@ -66,18 +66,19 @@ async def test_agent_experience_prefetch_includes_structured_read_results():provider = AgentExperienceContextProvider(messages=[],trajectory_summary="album release party discussion",- trajectory_uri="viking://agent/agent_sample_9/memories/trajectories/album_release_party_discussion.md",+ trajectory_uri="viking://user/user_sample_9/memories/trajectories/album_release_party_discussion.md",)provider._ctx = RequestContext(- user=UserIdentifier(account_id="acc", user_id="user_1", agent_id="agent_sample_9"),+ user=UserIdentifier(account_id="acc", user_id="user_1"),role=Role.USER,- namespace_policy=AccountNamespacePolicy(),)provider._viking_fs = AsyncMock()provider._transaction_handle = Noneprovider.search_files = AsyncMock(- return_value=["viking://agent/agent_sample_9/memories/experiences/personal_experience_sharing_conversation_flow.md"]+ return_value=[+ "viking://user/user_sample_9/memories/experiences/personal_experience_sharing_conversation_flow.md"+ ])read_result = {@@ -88,7 +89,7 @@ async def test_agent_experience_prefetch_includes_structured_read_results():}provider.read_file = AsyncMock(return_value=read_result)provider._read_file_contents = {- "viking://agent/agent_sample_9/memories/experiences/personal_experience_sharing_conversation_flow.md": SimpleNamespace(+ "viking://user/user_sample_9/memories/experiences/personal_experience_sharing_conversation_flow.md": SimpleNamespace(extra_fields={"experience_name": "personal_experience_sharing_conversation_flow"},content="line one\nline two",links=[],@@ -102,5 +103,8 @@ async def test_agent_experience_prefetch_includes_structured_read_results():assert any(msg.get("role") == "user" for msg in messages)assert add_tool_call_pair.call_count == 2- assert add_tool_call_pair.call_args_list[1].kwargs["result"]["context_role"] == "candidate_experience"+ assert (+ add_tool_call_pair.call_args_list[1].kwargs["result"]["context_role"]+ == "candidate_experience"+ )assert add_tool_call_pair.call_args_list[1].kwargs["result"]["page_id"] == 1diff --git a/tests/session/memory/test_compressor_v2.py b/tests/session/memory/test_compressor_v2.pyindex 44a54b7af..d1dda6366 100644--- a/tests/session/memory/test_compressor_v2.py+++ b/tests/session/memory/test_compressor_v2.py@@ -17,7 +17,13 @@ from openviking.message import Message, TextPartfrom openviking.server.identity import RequestContext, Rolefrom openviking.session import compressor_v2 as compressor_v2_modulefrom openviking.session.compressor_v2 import SessionCompressorV2-from openviking.session.memory.dataclass import MemoryField, MemoryFile, MemoryTypeSchema+from openviking.session.memory.dataclass import (+ MemoryField,+ MemoryFile,+ MemoryTypeSchema,+ ResolvedOperation,+ ResolvedOperations,+)from openviking.session.memory.extract_loop import ExtractLoopfrom openviking.session.memory.memory_isolation_handler import RoleScopefrom openviking.session.memory.memory_updater import ExtractContext, MemoryUpdateResult@@ -50,7 +56,7 @@ class MockVikingFS:def _get_parent_uri(self, uri: str) -> str:"""Get parent directory URI."""- # Handle URIs like "viking://agent/default/memories/cards/file.md"+ # Handle URIs like "viking://user/default/memories/cards/file.md"parts = uri.split("/")if len(parts) <= 3:return uri # Root or protocol level@@ -269,7 +275,7 @@ def create_test_conversation() -> List[Message]:role="user",parts=[TextPart(- "Cards are stored in viking://agent/{agent_space}/memories/cards, each card has name and content fields. "+ "Cards are stored in viking://user/{user_space}/memories/cards, each card has name and content fields. ""Events are stored in viking://user/{user_space}/memories/events, each event has event_name, event_time, and content fields.")],@@ -310,7 +316,7 @@ class TestCompressorV2:compressor = SessionCompressorV2(vikingdb=None)user = UserIdentifier.the_default_user()ctx = RequestContext(user=user, role=Role.ROOT)- messages = [Message.create_user("Current task")]+ messages = [Message(id="msg-current-task", role="user", parts=[TextPart("Current task")])]class DummyOrchestrator:registry = object()@@ -453,7 +459,7 @@ class TestCompressorV2:compressor = SessionCompressorV2(vikingdb=None)user = UserIdentifier.the_default_user()ctx = RequestContext(user=user, role=Role.ROOT)- messages = [Message.create_user("test")]+ messages = [Message(id="msg-test", role="user", parts=[TextPart("test")])]dummy_registry = SimpleNamespace(initialize_memory_files=AsyncMock())dummy_orchestrator = SimpleNamespace(@@ -484,13 +490,49 @@ class TestCompressorV2:warning_mock.assert_not_called()debug_mock.assert_any_call("AGFS unavailable, running memory extraction without locks")+ @pytest.mark.asyncio+ async def test_extract_long_term_memories_skips_self_init_when_self_disabled(self):+ compressor = SessionCompressorV2(vikingdb=None)+ user = UserIdentifier.the_default_user()+ ctx = RequestContext(user=user, role=Role.ROOT)+ messages = [Message(id="msg-test", role="user", parts=[TextPart("test")])]++ dummy_registry = SimpleNamespace(initialize_memory_files=AsyncMock())+ dummy_orchestrator = SimpleNamespace(+ context_provider=SimpleNamespace(get_memory_schemas=lambda _ctx: []),+ _transaction_handle=None,+ run=AsyncMock(return_value=(None, [])),+ )++ with (+ patch("openviking.storage.viking_fs.get_viking_fs", return_value=None),+ patch("openviking.storage.transaction.init_lock_manager"),+ patch("openviking.storage.transaction.get_lock_manager", return_value=None),+ patch(+ "openviking.session.memory.memory_type_registry.create_default_registry",+ return_value=dummy_registry,+ ),+ patch.object(compressor, "_get_or_create_react", return_value=dummy_orchestrator),+ ):+ result = await compressor.extract_long_term_memories(+ messages=messages,+ ctx=ctx,+ strict_extract_errors=False,+ allow_self_memory=False,+ allowed_peer_ids={"main"},+ allowed_memory_types={"profile"},+ )++ assert result == []+ dummy_registry.initialize_memory_files.assert_not_awaited()+@pytest.mark.asyncioasync def test_v2_lock_acquire_waits_without_retry_loop(self):"""v2 memory extraction should delegate waiting to lock manager without local retries."""compressor = SessionCompressorV2(vikingdb=None)user = UserIdentifier.the_default_user()ctx = RequestContext(user=user, role=Role.ROOT)- messages = [Message.create_user("test")]+ messages = [Message(id="msg-test", role="user", parts=[TextPart("test")])]class FixedSchema:directory = "viking://user/{{ user_space }}/memories"@@ -564,7 +606,7 @@ class TestCompressorV2:compressor = SessionCompressorV2(vikingdb=None)user = UserIdentifier.the_default_user()ctx = RequestContext(user=user, role=Role.ROOT)- messages = [Message.create_user("test")]+ messages = [Message(id="msg-test", role="user", parts=[TextPart("test")])]events: List[str] = []class FakeVikingFS:@@ -585,19 +627,32 @@ class TestCompressorV2:passasync def run(self):- return SimpleNamespace(upsert_operations=[], delete_file_contents=[]), []+ return (+ ResolvedOperations(+ upsert_operations=[+ ResolvedOperation(+ old_memory_file_content=None,+ memory_fields={},+ memory_type="experiences",+ uris=["viking://user/default/memories/experiences/debug.md"],+ )+ ],+ delete_file_contents=[],+ errors=[],+ ),+ [],+ )class DummyUpdater:async def apply_operations(self, operations, ctx, **kwargs):events.append("apply")result = MemoryUpdateResult()- result.written_uris = ["viking://agent/default/memories/experiences/debug.md"]+ result.written_uris = ["viking://user/default/memories/experiences/debug.md"]return resultconfig = SimpleNamespace(vlm=SimpleNamespace(get_vlm_instance=lambda: object()),memory=SimpleNamespace(- role_id_memory_isolation_enabled=False,v2_lock_max_retries=1,v2_lock_retry_interval_seconds=0.0,),@@ -618,7 +673,7 @@ class TestCompressorV2:)async def post_apply(result, inheritance_map, lock_handle):- assert result.written_uris == ["viking://agent/default/memories/experiences/debug.md"]+ assert result.written_uris == ["viking://user/default/memories/experiences/debug.md"]assert inheritance_map == {}assert lock_handle is handleevents.append("post_apply")@@ -626,10 +681,6 @@ class TestCompressorV2:with (patch("openviking.session.compressor_v2.get_viking_fs", return_value=FakeVikingFS()),patch("openviking.session.compressor_v2.get_openviking_config", return_value=config),- patch(- "openviking.session.memory.memory_isolation_handler.get_openviking_config",- return_value=config,- ),patch("openviking.session.compressor_v2.ExtractLoop", DummyExtractLoop),patch("openviking.storage.transaction.init_lock_manager"),patch("openviking.storage.transaction.get_lock_manager", return_value=lock_manager),@@ -644,7 +695,7 @@ class TestCompressorV2:post_apply=post_apply,)- assert result[0] == ["viking://agent/default/memories/experiences/debug.md"]+ assert result[0] == ["viking://user/default/memories/experiences/debug.md"]assert events == ["acquire", "apply", "post_apply", "release"]@pytest.mark.asyncio@@ -653,10 +704,10 @@ class TestCompressorV2:compressor = SessionCompressorV2(vikingdb=None)user = UserIdentifier.the_default_user()ctx = RequestContext(user=user, role=Role.ROOT)- exp_uri = "viking://agent/default/memories/experiences/debug.md"+ exp_uri = "viking://user/default/memories/experiences/debug.md"events: List[str] = []- traj_uri = "viking://agent/default/memories/trajectories/traj-1.md"+ traj_uri = "viking://user/default/memories/trajectories/traj-1.md"class FakeVikingFS:def __init__(self):@@ -670,7 +721,7 @@ class TestCompressorV2:}def _uri_to_path(self, uri: str, ctx=None) -> str:- return f"/local/default/agent/default/memories/experiences/{uri.rsplit('/', 1)[-1]}"+ return f"/local/default/user/default/memories/experiences/{uri.rsplit('/', 1)[-1]}"async def read_file(self, uri: str, ctx=None):events.append("read")@@ -707,20 +758,24 @@ class TestCompressorV2:# exp: exp.links 有指向 traj 的边(exp→traj, derived_from)exp_mf = MemoryFileUtils.read(viking_fs.files[exp_uri], uri=exp_uri)assert "source_trajectories" not in exp_mf.extra_fields- assert any(l.get("to_uri") == traj_uri for l in exp_mf.links), "exp.links should point to traj"+ assert any(l.get("to_uri") == traj_uri for l in exp_mf.links), (+ "exp.links should point to traj"+ )assert exp_mf.backlinks == [], "exp should have no backlinks"# traj: write_stored_links 写入 traj.backlinks(同一条边的 to 端)traj_mf = MemoryFileUtils.read(viking_fs.files[traj_uri], uri=traj_uri)assert traj_mf.links == [], "traj should have no forward links"- assert any(l.get("from_uri") == exp_uri for l in traj_mf.backlinks), "traj.backlinks should reference exp"+ assert any(l.get("from_uri") == exp_uri for l in traj_mf.backlinks), (+ "traj.backlinks should reference exp"+ )# event order: lock → read exp → write exp → read traj → write traj → releaseassert events == [- "exact:/local/default/agent/default/memories/experiences/debug.md",- "read", # exp read+ "exact:/local/default/user/default/memories/experiences/debug.md",+ "read", # exp read"write", # exp write (exp.links)- "read", # traj read (write_stored_links)+ "read", # traj read (write_stored_links)"write", # traj write (traj.backlinks)"release",]@@ -787,11 +842,10 @@ class TestExtractLoopPatchRepair:class DummyIsolationHandler:def get_read_scope(self):- return RoleScope(user_ids=["default"], agent_ids=["default"])+ return RoleScope(user_ids=["default"])- def fill_role_ids(self, item_dict, role_scope):+ def fill_identity_fields(self, item_dict, role_scope):item_dict.setdefault("user_id", "default")- item_dict.setdefault("agent_id", "default")def calculate_memory_uris(self, memory_type_schema, operation, extract_context):return [target_uri]@@ -885,11 +939,10 @@ class TestExtractLoopPatchRepair:class DummyIsolationHandler:def get_read_scope(self):- return RoleScope(user_ids=["default"], agent_ids=["default"])+ return RoleScope(user_ids=["default"])- def fill_role_ids(self, item_dict, role_scope):+ def fill_identity_fields(self, item_dict, role_scope):item_dict.setdefault("user_id", "default")- item_dict.setdefault("agent_id", "default")def calculate_memory_uris(self, memory_type_schema, operation, extract_context):return [target_uri]@@ -982,11 +1035,10 @@ class TestExtractLoopPatchRepair:class DummyIsolationHandler:def get_read_scope(self):- return RoleScope(user_ids=["default"], agent_ids=["default"])+ return RoleScope(user_ids=["default"])- def fill_role_ids(self, item_dict, role_scope):+ def fill_identity_fields(self, item_dict, role_scope):item_dict.setdefault("user_id", "default")- item_dict.setdefault("agent_id", "default")def calculate_memory_uris(self, memory_type_schema, operation, extract_context):return [target_uri]diff --git a/tests/session/memory/test_graph_view.py b/tests/session/memory/test_graph_view.pyindex fd1b3ea34..b4b994362 100644--- a/tests/session/memory/test_graph_view.py+++ b/tests/session/memory/test_graph_view.py@@ -9,7 +9,9 @@ from openviking.session.memory.graph_view import _render_graph_htmldef test_graph_view_module_compiles_without_escape_warnings():- path = Path(__file__).resolve().parents[3] / "openviking" / "session" / "memory" / "graph_view.py"+ path = (+ Path(__file__).resolve().parents[3] / "openviking" / "session" / "memory" / "graph_view.py"+ )with warnings.catch_warnings():warnings.simplefilter("error", SyntaxWarning)py_compile.compile(str(path), doraise=True)@@ -33,7 +35,7 @@ def test_render_graph_html_supports_relative_markdown_links():assert "function resolveRelativeUri(baseUri, relativeUri)" in htmlassert "const resolvedUri = resolveRelativeUri(baseUri, href);" in html- assert "data-target-uri=\"${resolvedUri}\"" in html+ assert 'data-target-uri="${resolvedUri}"' in htmldef test_render_graph_html_renders_tooltip_content_as_markdown():@@ -68,25 +70,37 @@ def test_render_graph_html_embeds_full_markdown_content_and_link_targets():html = _render_graph_html(nodes, edges)- assert '"content_full": "# Caroline\\n\\nSee [music](viking://user/Caroline/memories/preferences/music.md)"' in html+ assert (+ '"content_full": "# Caroline\\n\\nSee [music](viking://user/Caroline/memories/preferences/music.md)"'+ in html+ )assert "function renderMarkdown" in html- assert "detailContent.innerHTML = renderMarkdown(node.content_full || node.content_preview || '', node.uri || '');" in html+ assert (+ "detailContent.innerHTML = renderMarkdown(node.content_full || node.content_preview || '', node.uri || '');"+ in html+ )assert "detailContent.addEventListener('click'" in htmlassert "const targetNodeId = link.dataset.targetUri;" in html- assert "network.focus(targetNodeId, { animation: { duration: 350, easingFunction: 'easeInOutQuad' }, scale: network.getScale() });" in html+ assert (+ "network.focus(targetNodeId, { animation: { duration: 350, easingFunction: 'easeInOutQuad' }, scale: network.getScale() });"+ in html+ )def test_render_graph_html_clicking_detail_link_centers_target_node():html = _render_graph_html([], [])- assert "network.focus(targetNodeId, { animation: { duration: 350, easingFunction: 'easeInOutQuad' }, scale: network.getScale() });" in html+ assert (+ "network.focus(targetNodeId, { animation: { duration: 350, easingFunction: 'easeInOutQuad' }, scale: network.getScale() });"+ in html+ )def test_render_graph_html_uses_dark_node_background_with_light_text():nodes = [{- "id": "viking://agent/demo/memories/experiences/a.md",- "uri": "viking://agent/demo/memories/experiences/a.md",+ "id": "viking://user/demo/memories/experiences/a.md",+ "uri": "viking://user/demo/memories/experiences/a.md","label": "a","memory_type": "experiences","category": "",@@ -106,8 +120,8 @@ def test_render_graph_html_uses_dark_node_background_with_light_text():def test_render_graph_html_embeds_vis_network_viewer_metadata():nodes = [{- "id": "viking://agent/demo/memories/experiences/a.md",- "uri": "viking://agent/demo/memories/experiences/a.md",+ "id": "viking://user/demo/memories/experiences/a.md",+ "uri": "viking://user/demo/memories/experiences/a.md","label": "a","memory_type": "experiences","category": "",@@ -117,8 +131,8 @@ def test_render_graph_html_embeds_vis_network_viewer_metadata():]edges = [{- "source": "viking://agent/demo/memories/experiences/a.md",- "target": "viking://agent/demo/memories/experiences/b.md",+ "source": "viking://user/demo/memories/experiences/a.md",+ "target": "viking://user/demo/memories/experiences/b.md","link_type": "related_to","weight": 0.8,"description": "same topic",@@ -143,7 +157,10 @@ def test_render_graph_html_embeds_vis_network_load_guard():html = _render_graph_html([], [])assert 'window.__OPENVIKING_VIS_NETWORK_SOURCE__ = "external";' in html- assert '<script src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script>' in html+ assert (+ '<script src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script>'+ in html+ )assert "if (!window.vis || !window.vis.DataSet || !window.vis.Network)" in htmlassert "Graph library failed to load. If you opened this file locally" in html@@ -192,13 +209,11 @@ def test_render_graph_html_restores_visibility_without_rebuilding_dataset():assert "hidden: false" in html--def test_render_graph_html_inverts_selected_node_colors():nodes = [{- "id": "viking://agent/demo/memories/experiences/a.md",- "uri": "viking://agent/demo/memories/experiences/a.md",+ "id": "viking://user/demo/memories/experiences/a.md",+ "uri": "viking://user/demo/memories/experiences/a.md","label": "a","memory_type": "experiences","category": "",@@ -226,14 +241,13 @@ def test_render_graph_html_edge_details_include_source_and_target_uris():assert "detailMeta.textContent = `${edge.link_type} · weight=${edge.weight}`;" in htmlassert "const sourceUri = edge.from || edge.source || '';" in htmlassert "const targetUri = edge.to || edge.target || '';" in html- assert """detailContent.innerHTML = renderMarkdown(`- from_uri: ${escapeHtml(sourceUri)}+ assert (+ """detailContent.innerHTML = renderMarkdown(`- from_uri: ${escapeHtml(sourceUri)}- to_uri: ${escapeHtml(targetUri)}-${escapeHtml(edge.description || '(no description)')}`);""" in html----+${escapeHtml(edge.description || '(no description)')}`);"""+ in html+ )def test_render_graph_html_renders_dynamic_relationship_legend_from_edges():@@ -264,7 +278,10 @@ def test_render_graph_html_renders_dynamic_relationship_legend_from_edges():html = _render_graph_html([], edges)assert "const activeLinkTypes = new Set();" in html- assert "const linkTypes = [...new Set(originalEdges.map((edge) => edge.link_type).filter(Boolean))].sort();" in html+ assert (+ "const linkTypes = [...new Set(originalEdges.map((edge) => edge.link_type).filter(Boolean))].sort();"+ in html+ )assert "activeLinkTypes.has(linkType)" in htmlassert "activeLinkTypes.add(linkType)" in htmlassert "activeLinkTypes.delete(linkType)" in html@@ -272,8 +289,6 @@ def test_render_graph_html_renders_dynamic_relationship_legend_from_edges():assert "works_with" in html--def test_render_graph_html_keeps_node_label_plain_text_while_rendering_body_links():nodes = [{@@ -291,5 +306,11 @@ def test_render_graph_html_keeps_node_label_plain_text_while_rendering_body_linkhtml = _render_graph_html(nodes, [])assert '"label": "Caroline profile"' in html- assert '"content_full": "她喜欢[角色扮演游戏](entities/games/rpg.md),也喜欢开放世界游戏。"' in html- assert '"content_preview": "她喜欢[角色扮演游戏](entities/games/rpg.md),也喜欢开放世界游戏。"' in html+ assert (+ '"content_full": "她喜欢[角色扮演游戏](entities/games/rpg.md),也喜欢开放世界游戏。"'+ in html+ )+ assert (+ '"content_preview": "她喜欢[角色扮演游戏](entities/games/rpg.md),也喜欢开放世界游戏。"'+ in html+ )diff --git a/tests/session/memory/test_graph_view_collect.py b/tests/session/memory/test_graph_view_collect.pyindex 8b78d7793..ba0ffef62 100644--- a/tests/session/memory/test_graph_view_collect.py+++ b/tests/session/memory/test_graph_view_collect.py@@ -30,7 +30,7 @@ async def test_collect_graph_data_preserves_markdown_links_in_content_full():mock_fs.read_file = AsyncMock(return_value=content)graph = MemoryGraph(viking_fs=mock_fs)- ctx = RequestContext(user=UserIdentifier("acme", "alice", "bot"), role=Role.USER)+ ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)nodes, edges = await graph._collect_graph_data(["viking://user/Calvin/memories"], ctx)@@ -53,7 +53,7 @@ async def test_collect_graph_data_includes_root_level_profile_markdown():mock_fs.read_file = AsyncMock(return_value=content)graph = MemoryGraph(viking_fs=mock_fs)- ctx = RequestContext(user=UserIdentifier("acme", "alice", "bot"), role=Role.USER)+ ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)nodes, edges = await graph._collect_graph_data(["viking://user/Caroline/memories"], ctx)@@ -69,14 +69,16 @@ async def test_collect_graph_data_includes_content_preview():mock_fs = MagicMock()mock_fs.tree = AsyncMock(- return_value=[_file_entry("viking://agent/demo/memories/experiences/a.md", "experiences/a.md")]+ return_value=[+ _file_entry("viking://user/demo/memories/experiences/a.md", "experiences/a.md")+ ])mock_fs.read_file = AsyncMock(return_value=content)graph = MemoryGraph(viking_fs=mock_fs)- ctx = RequestContext(user=UserIdentifier("acme", "alice", "bot"), role=Role.USER)+ ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)- nodes, edges = await graph._collect_graph_data(["viking://agent/demo/memories"], ctx)+ nodes, edges = await graph._collect_graph_data(["viking://user/demo/memories"], ctx)assert len(nodes) == 1assert nodes[0]["memory_type"] == "experiences"@@ -96,7 +98,7 @@ async def test_collect_graph_data_keeps_profile_body_as_content_preview():mock_fs.read_file = AsyncMock(return_value=content)graph = MemoryGraph(viking_fs=mock_fs)- ctx = RequestContext(user=UserIdentifier("acme", "alice", "bot"), role=Role.USER)+ ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)nodes, edges = await graph._collect_graph_data(["viking://user/Caroline/memories"], ctx)@@ -118,7 +120,7 @@ async def test_collect_graph_data_infers_memory_type_from_parent_directory():mock_fs.read_file = AsyncMock(return_value=content)graph = MemoryGraph(viking_fs=mock_fs)- ctx = RequestContext(user=UserIdentifier("acme", "alice", "bot"), role=Role.USER)+ ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)nodes, edges = await graph._collect_graph_data(["viking://user/Caroline/memories"], ctx)@@ -145,7 +147,7 @@ async def test_collect_graph_data_reads_all_nodes_before_filling_edge_targets():mock_fs.read_file = AsyncMock(side_effect=[child_content, profile_content])graph = MemoryGraph(viking_fs=mock_fs)- ctx = RequestContext(user=UserIdentifier("acme", "alice", "bot"), role=Role.USER)+ ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)nodes, edges = await graph._collect_graph_data(["viking://user/Caroline/memories"], ctx)@@ -171,7 +173,7 @@ async def test_collect_graph_data_raises_when_reading_memory_file_fails():mock_fs.read_file = AsyncMock(side_effect=RuntimeError("boom"))graph = MemoryGraph(viking_fs=mock_fs)- ctx = RequestContext(user=UserIdentifier("acme", "alice", "bot"), role=Role.USER)+ ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)with pytest.raises(RuntimeError, match="boom"):await graph._collect_graph_data(["viking://user/Caroline/memories"], ctx)@@ -184,13 +186,11 @@ async def test_collect_graph_data_drops_edges_to_unloaded_external_nodes():child_content = f"""Blue\n\n<!-- MEMORY_FIELDS\n{{\"memory_type\": \"preferences\", \"links\": [{{\"to_uri\": \"{external_profile_uri}\", \"link_type\": \"belongs_to\"}}]}}\n-->"""mock_fs = MagicMock()- mock_fs.tree = AsyncMock(- return_value=[_file_entry(child_uri, "preferences/color.md")]- )+ mock_fs.tree = AsyncMock(return_value=[_file_entry(child_uri, "preferences/color.md")])mock_fs.read_file = AsyncMock(return_value=child_content)graph = MemoryGraph(viking_fs=mock_fs)- ctx = RequestContext(user=UserIdentifier("acme", "alice", "bot"), role=Role.USER)+ ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)nodes, edges = await graph._collect_graph_data(["viking://user/Melanie/memories"], ctx)diff --git a/tests/session/memory/test_memory_diff.py b/tests/session/memory/test_memory_diff.pyindex 1eb8ad159..9bedb5a7c 100644--- a/tests/session/memory/test_memory_diff.py+++ b/tests/session/memory/test_memory_diff.py@@ -32,7 +32,6 @@ class TestMemoryDiffArchive:def mock_ctx(self):"""Mock RequestContext for testing."""ctx = MagicMock()- ctx.namespace_policy = MagicMock()ctx.user = MagicMock()ctx.user.user_id = "test_user"ctx.account_id = "test_account"diff --git a/tests/session/memory/test_memory_extractor_flow.py b/tests/session/memory/test_memory_extractor_flow.pydeleted file mode 100644index b2141d02a..000000000--- a/tests/session/memory/test_memory_extractor_flow.py+++ /dev/null@@ -1,709 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: AGPL-3.0-"""-Test memory extraction flow with memory module components.--This test simulates the complete memory extraction workflow:-1. Setup conversation messages-2. Pre-fetch memory directory structure-3. Call ReAct orchestrator to analyze and determine memory changes-4. Generate memory operations-5. Apply operations via MemoryUpdater-"""--import logging-from typing import Any, Dict, List, Tuple-from unittest.mock import patch--import pytest--from openviking.message import Message, TextPart-from openviking.server.identity import RequestContext, Role-from openviking.session.memory import (- ExtractLoop,- MemoryUpdater,- MemoryUpdateResult,-)-from openviking_cli.session.user_id import UserIdentifier-from openviking_cli.utils.config import get_openviking_config, initialize_openviking_config--# 让 openviking logger 的日志 propagate 到 pytest-for logger_name in ["openviking", "openviking.session.memory"]:- logger = logging.getLogger(logger_name)- logger.propagate = True- logger.setLevel(logging.DEBUG)--# Module logger for this test-logger = logging.getLogger(__name__)---class MockVikingFS:- """Mock VikingFS for testing with unified memory storage."""-- def __init__(self):- # Unified storage: key is URI, value is dict with type and content/children- self._store: Dict[str, Dict[str, Any]] = {}- self._snapshot: Dict[str, str] = {}-- def _get_parent_uri(self, uri: str) -> str:- """Get parent directory URI."""- # Handle URIs like "viking://agent/default/memories/cards/file.md"- parts = uri.split("/")- if len(parts) <= 3:- return uri # Root or protocol level- return "/".join(parts[:-1])-- def _get_name_from_uri(self, uri: str) -> str:- """Get file/directory name from URI."""- parts = uri.split("/")- return parts[-1] if parts else ""-- async def read_file(self, uri: str, **kwargs) -> str:- """Mock read_file."""- entry = self._store.get(uri)- if entry and entry.get("type") == "file":- return entry.get("content", "")- return ""-- async def write_file(self, uri: str, content: str, **kwargs) -> None:- """Mock write_file - automatically updates parent directory entries."""- # Create parent directories if they don't exist- parent_uri = self._get_parent_uri(uri)- if parent_uri and parent_uri != uri:- await self.mkdir(parent_uri)-- # Write the file- self._store[uri] = {"type": "file", "content": content}-- # Update parent directory's entries- if parent_uri and parent_uri in self._store:- name = self._get_name_from_uri(uri)- # Create entry for this file in parent's children- file_entry = {- "name": name,- "isDir": False,- "uri": uri,- "abstract": content[:100] if content else "",- }- # Update or add to parent's children- parent = self._store[parent_uri]- if "children" not in parent:- parent["children"] = []- # Remove existing entry if present- parent["children"] = [c for c in parent["children"] if c.get("name") != name]- parent["children"].append(file_entry)-- async def ls(self, uri: str, **kwargs) -> List[Dict[str, Any]]:- """Mock ls - returns entries from unified storage."""- entry = self._store.get(uri)- if entry and entry.get("type") == "dir":- return entry.get("children", [])- return []-- async def mkdir(self, uri: str, **kwargs) -> None:- """Mock mkdir - recursively creates parent directories."""- if uri in self._store:- return # Already exists-- # Create parent directories first- parent_uri = self._get_parent_uri(uri)- if parent_uri and parent_uri != uri:- await self.mkdir(parent_uri)-- # Create this directory- self._store[uri] = {"type": "dir", "children": []}-- # Update parent directory's entries- if parent_uri and parent_uri in self._store:- name = self._get_name_from_uri(uri)- dir_entry = {"name": name, "isDir": True, "uri": uri}- parent = self._store[parent_uri]- # Remove existing entry if present- parent["children"] = [c for c in parent["children"] if c.get("name") != name]- parent["children"].append(dir_entry)-- async def rm(self, uri: str, **kwargs) -> None:- """Mock rm - removes file and updates parent directory."""- if uri not in self._store:- return-- # Remove from parent's children- parent_uri = self._get_parent_uri(uri)- name = self._get_name_from_uri(uri)- if parent_uri and parent_uri in self._store:- parent = self._store[parent_uri]- parent["children"] = [c for c in parent.get("children", []) if c.get("name") != name]-- # Remove the file/directory- del self._store[uri]-- async def stat(self, uri: str, **kwargs) -> Dict[str, Any]:- """Mock stat."""- entry = self._store.get(uri)- if entry:- return {"type": entry["type"], "uri": uri}- raise FileNotFoundError(f"Not found: {uri}")-- async def find(self, query: str, **kwargs) -> Dict[str, Any]:- """Mock find - searches file names and content."""- memories = []- query_lower = query.lower()-- for uri, entry in self._store.items():- if entry.get("type") == "file":- name = self._get_name_from_uri(uri)- content = entry.get("content", "")- if query_lower in name.lower() or query_lower in content.lower():- memories.append(- {"uri": uri, "name": name, "abstract": content[:200] if content else ""}- )-- return {- "memories": memories,- "resources": [],- "skills": [],- }-- async def tree(self, uri: str, **kwargs) -> Dict[str, Any]:- """Mock tree."""- return {"uri": uri, "tree": []}-- def snapshot(self) -> None:- """Save a snapshot of the current file state."""- self._snapshot = {}- for uri, entry in self._store.items():- if entry.get("type") == "file":- self._snapshot[uri] = entry.get("content", "")-- def diff_since_snapshot(self) -> Dict[str, Dict[str, Any]]:- """- Compute diff since last snapshot.-- Returns:- Dict with keys 'added', 'modified', 'deleted', each mapping URIs to content.- """- added = {}- modified = {}- deleted = {}-- # Get current files- current_files = {}- for uri, entry in self._store.items():- if entry.get("type") == "file":- current_files[uri] = entry.get("content", "")-- # Check for added/modified files- for uri, content in current_files.items():- if uri not in self._snapshot:- added[uri] = content- elif content != self._snapshot[uri]:- modified[uri] = {"old": self._snapshot[uri], "new": content}-- # Check for deleted files- for uri in self._snapshot:- if uri not in current_files:- deleted[uri] = self._snapshot[uri]-- return {"added": added, "modified": modified, "deleted": deleted}---def print_diff(diff: Dict[str, Dict[str, str]]) -> None:- """- Print diff in a readable format using diff-match-patch with colors.- Uses inline color codes to show character-level changes on the same line.- """- # ANSI color codes - 9m=删除线,31m=红色字体,32m=绿色- STYLE_DELETE = "\033[9m\033[31m"- STYLE_INSERT = "\033[32m"- STYLE_RESET = "\033[0m"- YELLOW = "\033[33m"- GREEN = "\033[32m"- RED = "\033[31m"-- try:- from diff_match_patch import diff_match_patch-- has_dmp = True- except ImportError:- has_dmp = False-- print("\n" + "=" * 80)- print(f"{YELLOW}MEMORY CHANGES DIFF (Character-level){STYLE_RESET}")- print("=" * 80)-- # Added files- if diff["added"]:- print(f"\n{GREEN}[ADDED] {len(diff['added'])} file(s):{STYLE_RESET}")- for uri, content in diff["added"].items():- print(f"\n {uri}")- print(" " + "-" * 76)- for line in content.split("\n"):- print(f"{GREEN} + {line}{STYLE_RESET}")-- # Modified files- if diff["modified"]:- print(f"\n[MODIFIED] {len(diff['modified'])} file(s):")- for uri, changes in diff["modified"].items():- print(f"\n {uri}")- print(" " + "-" * 76)-- old_text = changes["old"] or ""- new_text = changes["new"] or ""-- if has_dmp and old_text and new_text:- try:- dmp = diff_match_patch()- # Compute character-level diff and clean up- diffs = dmp.diff_main(old_text, new_text)- dmp.diff_cleanupSemantic(diffs) # 优化diff结果,减少冗余-- # Format output with inline colors - character-level on same line- _print_inline_diff(diffs, STYLE_DELETE, STYLE_INSERT, STYLE_RESET)- except Exception as e:- # Fallback to simple line-by-line comparison- logger.exception("diff_match_patch fail", e)- else:- logger.exception("has_dmp= False")-- # Deleted files- if diff["deleted"]:- print(f"\n{RED}[DELETED] {len(diff['deleted'])} file(s):{STYLE_RESET}")- for uri, content in diff["deleted"].items():- print(f"\n {uri}")- print(" " + "-" * 76)- for line in content.split("\n"):- print(f"{RED} - {line}{STYLE_RESET}")-- if not any(diff.values()):- print("\n No changes detected.")-- print("\n" + "=" * 80 + "\n")---def _print_inline_diff(- diffs: List[Tuple[int, str]], style_delete: str, style_insert: str, style_reset: str-) -> None:- """- Print character-level diff with inline colors.-- Shows deletions in red strikethrough and insertions in green,- all in the same line flow for easy reading.- """- output = []-- for op, text in diffs:- if op == 0: # 文本无差异:正常显示- output.append(f"{text}")- elif op == -1: # 文本删除:红色删除线- output.append("\n".join([f"{style_delete}{t}{style_reset}" for t in text.split("\n")]))- elif op == 1: # 文本新增:绿色- output.append("\n".join([f"{style_insert}{t}{style_reset}" for t in text.split("\n")]))-- # 合并并打印最终结果,添加行号- formatted_text = "".join(output)- for idx, line in enumerate(formatted_text.split("\n")):- print(f" {idx + 1}: {line}")---def create_test_conversation() -> List[Message]:- """Create a test conversation focused on cards and events."""- messages = []-- # Message 1: User starts talking about a project- msg1 = Message(- id="msg1",- role="user",- parts=[- TextPart(- "We're starting the memory extraction feature for the OpenViking project today. This project is an Agent-native context database."- )- ],- )- messages.append(msg1)-- # Message 2: Assistant responds- msg2 = Message(- id="msg2",- role="assistant",- parts=[- TextPart(- "Great! The memory extraction feature is important. What technical approach are we planning to use?"- )- ],- )- messages.append(msg2)-- # Message 3: User talks about architecture decisions- msg3 = Message(- id="msg3",- role="user",- parts=[- TextPart(- "We've decided to use the ExtractLoop pattern, combined with LLMs to analyze conversations and generate memory operations. "- "There are two main memory types: cards for knowledge cards (Zettelkasten note-taking method), and events for recording important events and decisions."- )- ],- )- messages.append(msg3)-- # Message 4: Assistant asks about schemas- msg4 = Message(- id="msg4",- role="assistant",- parts=[TextPart("Got it! What's the specific structure of these two schemas?")],- )- messages.append(msg4)-- # Message 5: User explains schemas- msg5 = Message(- id="msg5",- role="user",- parts=[- TextPart(- "Cards are stored in viking://agent/{agent_space}/memories/cards, each card has name and content fields. "- "Events are stored in viking://user/{user_space}/memories/events, each event has event_name, event_time, and content fields. "- "Just now, we also decided to add diff-match-patch to print memory modification differences."- )- ],- )- messages.append(msg5)-- return messages---def create_existing_memories_content() -> Dict[str, str]:- """Create existing memory content for update test with cards and events."""- return {- "viking://agent/default/memories/cards/openviking_project.md": """# OpenViking Project--## Overview-OpenViking is an Agent-native context database.--## Technical Approach-- Uses ExtractLoop pattern-- Combines LLM to analyze conversations and generate memory operations---<!-- MEMORY_FIELDS-{- "name": "openviking_project"-}--->""",- "viking://agent/default/memories/cards/extract_loop.md": """# ExtractLoop Pattern--## Overview-ExtractLoop is an orchestrator pattern for memory extraction.--## Features-- Analyze conversation content-- Generate memory operations---<!-- MEMORY_FIELDS-{- "name": "extract_loop"-}--->""",- "viking://user/default/memories/events/2026-03-20_Started_memory_extraction_feature_development.md": """# Event: Started memory extraction feature development--## Event Name-Started memory extraction feature development--## Event Time-2026-03-20--## Content-Today we started working on the memory extraction feature for the OpenViking project. Decided to use the ExtractLoop pattern.---<!-- MEMORY_FIELDS-{- "event_name": "Started_memory_extraction_feature_development",- "event_time": "2026-03-20"-}--->""",- }---def create_update_conversation() -> List[Message]:- """Create a conversation for updating existing cards and events."""- messages = []-- # Message 1: User corrects and adds details to existing OpenViking project card- msg1 = Message(- id="msg1",- role="user",- parts=[- TextPart(- "I just looked at our OpenViking project card and need to correct it: "- "OpenViking is not just a context database, it's an Agent-native memory system, "- "supporting multi-level memory (L0/L1/L2) and incremental updates. "- "Also, in the technical approach section, we not only use the ExtractLoop pattern, "- "but also need to support schema-driven memory extraction."- )- ],- )- messages.append(msg1)-- # Message 2: Assistant responds- msg2 = Message(- id="msg2",- role="assistant",- parts=[- TextPart(- "Okay, I'll update the project card! Does the ExtractLoop pattern description need adjustment too?"- )- ],- )- messages.append(msg2)-- # Message 3: User updates ExtractLoop card and adds to event- msg3 = Message(- id="msg3",- role="user",- parts=[- TextPart(- "Yes, the ExtractLoop card also needs updating: ExtractLoop is not just about analyzing conversations and generating operations, "- "it's a complete orchestrator responsible for tool calling, LLM reasoning, and memory operation integration. "- "Also, the event card that mentions 'Decided to use ExtractLoop pattern' "- "needs to add the reason: because the ExtractLoop pattern can handle uncertainty well, "- "verifying the correctness of memory operations through the ReAct flow."- )- ],- )- messages.append(msg3)-- return messages---class TestExtractLoopFlow:- """Test the complete memory extraction flow."""-- @pytest.mark.integration- @pytest.mark.asyncio- async def test_full_flow_with_real_llm(self):- # Only mock VikingFS, everything else is real!- viking_fs = MockVikingFS()- initialize_openviking_config()- config = get_openviking_config()- vlm = config.vlm.get_vlm_instance()- print(f"vlm={vlm}")- user = UserIdentifier.the_default_user()- ctx = RequestContext(user=user, role=Role.ROOT)-- # Create test conversation- messages = create_test_conversation()-- # Format conversation as string- conversation_str = "\n".join([f"[{msg.role}]: {msg.content}" for msg in messages])-- print("-" * 60)- print("使用真实 LLM 测试完整流程(cards & events)...")- print("对话内容:")- print(conversation_str[:800] + "..." if len(conversation_str) > 800 else conversation_str)- print("-" * 60)-- # Initialize orchestrator with real VLM!- orchestrator = ExtractLoop(- vlm=vlm,- viking_fs=viking_fs,- ctx=ctx,- )-- # Take snapshot BEFORE running orchestrator to capture all changes- viking_fs.snapshot()-- # Actually run the orchestrator with real LLM calls!- operations, tools_used = await orchestrator.run(- messages=messages,- )-- # Verify results- assert operations is not None- assert tools_used is not None-- print("-" * 60)- print("生成的操作:")- print(f" 写入:{len(operations.write_uris)}")- print(f" 编辑:{len(operations.edit_uris)}")- print(f" 删除:{len(operations.delete_uris)}")- print(f" 使用的工具:{len(tools_used)}")- print("-" * 60)-- # Now test MemoryUpdater with the operations, mock get_viking_fs- with patch(- "openviking.session.memory.memory_updater.get_viking_fs", return_value=viking_fs- ):- updater = MemoryUpdater(registry=orchestrator.registry)- result = await updater.apply_operations(operations, ctx)-- assert isinstance(result, MemoryUpdateResult)-- print("已应用的操作:")- print(f" 已写入:{len(result.written_uris)}")- print(f" 已编辑:{len(result.edited_uris)}")- print(f" 已删除:{len(result.deleted_uris)}")- print(f" 错误:{len(result.errors)}")- print("-" * 60)-- # Print diff since snapshot- diff = viking_fs.diff_since_snapshot()- print_diff(diff)-- # Check that at least something happened (could be write/edit/delete depending on LLM)- total_changes = (- len(operations.write_uris) + len(operations.edit_uris) + len(operations.delete_uris)- )- print(f"LLM 建议的总变更数:{total_changes}")-- @pytest.mark.integration- @pytest.mark.asyncio- async def test_update_existing_memories_with_real_llm(self):- """Test updating existing cards and events with real LLM (only VikingFS is mocked)."""- # Check if VLM is available- initialize_openviking_config()- config = get_openviking_config()- vlm = config.vlm.get_vlm_instance()- print(f"vlm={vlm}")-- # Only mock VikingFS, everything else is real!- viking_fs = MockVikingFS()- user = UserIdentifier.the_default_user()- ctx = RequestContext(user=user, role=Role.ROOT)-- existing_memories = create_existing_memories_content()- for uri, content in existing_memories.items():- await viking_fs.write_file(uri, content)-- # Create test conversation for updating- messages = create_update_conversation()-- # Format conversation as string- conversation_str = "\n".join([f"[{msg.role}]: {msg.content}" for msg in messages])-- print("=" * 60)- print("测试更新已有 cards 和 events...")- print("-" * 60)- print("已有记忆内容:")- for uri, content in existing_memories.items():- print(f"\n--- {uri} ---")- print(content[:300] + "..." if len(content) > 300 else content)- print("-" * 60)- print("新对话内容:")- print(conversation_str)- print("=" * 60)-- # Initialize orchestrator with real VLM!- orchestrator = ExtractLoop(- vlm=vlm,- viking_fs=viking_fs,- ctx=ctx,- )-- # Take snapshot BEFORE running orchestrator to capture all changes- viking_fs.snapshot()-- # Actually run the orchestrator with real LLM calls!- operations, tools_used = await orchestrator.run(- messages=messages,- )-- # Verify results- assert operations is not None- assert tools_used is not None- print(f"operations={operations.model_dump_json(indent=4)}")- print("=" * 60)- print("生成的操作:")- print(f" 写入:{len(operations.write_uris)}")- print(f" 编辑:{len(operations.edit_uris)}")- print(f" 删除:{len(operations.delete_uris)}")- print(f" 使用的工具:{len(tools_used)}")-- if operations.edit_uris:- print("\n编辑操作详情:")- for op in operations.edit_uris:- # Handle both dict and model objects- if isinstance(op, dict):- print(f" - memory_type: {op.get('memory_type', 'unknown')}")- if "fields" in op:- print(f" - fields: {op['fields']}")- if "patches" in op:- print(f" 补丁:{list(op['patches'].keys())}")- if "content" in op:- print(f" - content: {str(op['content'])[:100]}...")- else:- # Try to access as model attributes- memory_type = getattr(op, "memory_type", "unknown")- print(f" - memory_type: {memory_type}")- fields = getattr(op, "fields", None)- if fields:- print(f" - fields: {fields}")- patches = getattr(op, "patches", None)- if patches:- print(f" 补丁:{list(patches.keys())}")- content = getattr(op, "content", None)- if content:- print(f" - content: {str(content)[:100]}...")-- print("=" * 60)-- # Now test MemoryUpdater with the operations, mock get_viking_fs- with patch(- "openviking.session.memory.memory_updater.get_viking_fs", return_value=viking_fs- ):- updater = MemoryUpdater(registry=orchestrator.registry)- result = await updater.apply_operations(operations, ctx)-- assert isinstance(result, MemoryUpdateResult)-- print("已应用的操作:")- print(f" 已写入:{len(result.written_uris)}")- print(f" 已编辑:{len(result.edited_uris)}")- print(f" 已删除:{len(result.deleted_uris)}")- print(f" 错误:{len(result.errors)}")- print("=" * 60)-- # Print diff since snapshot- diff = viking_fs.diff_since_snapshot()- print_diff(diff)-- # Check updated content- print("\n更新后的记忆内容:")- for uri in existing_memories.keys():- new_content = await viking_fs.read_file(uri)- if new_content != existing_memories.get(uri, ""):- print(f"\n--- {uri} (已更新) ---")- print(new_content[:500] + "..." if len(new_content) > 500 else new_content)- else:- print(f"\n--- {uri} (未变化) ---")- # Also check if new cards/events were created- print("\n--- cards 目录内容 ---")- try:- card_files = await viking_fs.ls("viking://agent/default/memories/cards")- for f in card_files:- print(f" - {f.get('name', 'unknown')}")- except Exception as e:- print(f" 无法列出目录: {e}")- print("\n--- events 目录内容 ---")- try:- event_files = await viking_fs.ls("viking://user/default/memories/events")- for f in event_files:- print(f" - {f.get('name', 'unknown')}")- except Exception as e:- print(f" 无法列出目录: {e}")- print("=" * 60)-- # Check that at least something happened (could be write/edit/delete depending on LLM)- total_changes = (- len(operations.write_uris) + len(operations.edit_uris) + len(operations.delete_uris)- )- print(f"LLM 建议的总变更数:{total_changes}")-- def test_message_formatting(self):- """Test that messages can be formatted correctly."""- messages = create_test_conversation()-- assert len(messages) == 5- assert messages[0].role == "user"- assert "OpenViking" in messages[0].content- assert "memory extraction" in messages[0].contentdiff --git a/tests/session/memory/test_memory_isolation_handler.py b/tests/session/memory/test_memory_isolation_handler.pyindex 8b88cc969..04c41b3cd 100644--- a/tests/session/memory/test_memory_isolation_handler.py+++ b/tests/session/memory/test_memory_isolation_handler.py@@ -8,41 +8,37 @@ from unittest.mock import MagicMock, patchfrom openviking.message.message import Messagefrom openviking.message.part import TextPart-from openviking.server.identity import AccountNamespacePolicy, RequestContext, Role+from openviking.server.identity import RequestContext, Rolefrom openviking.session.memory.memory_isolation_handler import (MemoryIsolationHandler,)from openviking_cli.session.user_id import UserIdentifier-def create_message(role: str, role_id: str, content: str = "test") -> Message:+def create_message(+ role: str,+ content: str = "test",+ peer_id: str | None = None,+) -> Message:"""Helper to create a test message."""return Message(- id=f"msg_{role}_{role_id}",+ id=f"msg_{role}_{peer_id or 'self'}",role=role,parts=[TextPart(text=content)],- role_id=role_id,+ peer_id=peer_id,)def create_ctx(account_id: str = "test_account",user_id: str = "user_a",- agent_id: str = "agent_a",- isolate_user_by_agent: bool = False,- isolate_agent_by_user: bool = False,) -> RequestContext:"""Helper to create a test RequestContext."""user = UserIdentifier(account_id=account_id,user_id=user_id,- agent_id=agent_id,)- policy = AccountNamespacePolicy(- isolate_user_scope_by_agent=isolate_user_by_agent,- isolate_agent_scope_by_user=isolate_agent_by_user,- )- return RequestContext(user=user, role=Role.USER, namespace_policy=policy)+ return RequestContext(user=user, role=Role.USER)def create_mock_extract_context(messages):@@ -55,12 +51,12 @@ def create_mock_extract_context(messages):class TestGetReadScope:"""Tests for get_read_scope."""- def test_single_user_single_agent(self):- """Test extracting single user and agent."""+ def test_single_user_scope(self):+ """Test extracting the authenticated user scope."""ctx = create_ctx()messages = [- create_message("user", "user_a", "Hello"),- create_message("assistant", "agent_a", "Hi there"),+ create_message("user", "Hello"),+ create_message("assistant", "Hi there"),]extract_ctx = create_mock_extract_context(messages)handler = MemoryIsolationHandler(ctx, extract_ctx)@@ -68,31 +64,13 @@ class TestGetReadScope:scope = handler.get_read_scope()assert scope.user_ids == ["user_a"]- assert scope.agent_ids == ["agent_a"]-- def test_multiple_users(self):- """Test extracting multiple users."""- ctx = create_ctx()- messages = [- create_message("user", "user_a", "Hello from A"),- create_message("user", "user_b", "Hello from B"),- create_message("assistant", "agent_a", "Hi"),- ]- extract_ctx = create_mock_extract_context(messages)- handler = MemoryIsolationHandler(ctx, extract_ctx)- scope = handler.get_read_scope()-- assert set(scope.user_ids) == {"user_a", "user_b"}- assert scope.agent_ids == ["agent_a"]-- def test_multiple_agents(self):- """Test extracting multiple agents."""+ def test_message_peer_ids_do_not_expand_self_extraction_scope(self):+ """Message peer_id should not make self extraction read or write peer memory."""ctx = create_ctx()messages = [- create_message("user", "user_a", "Hello"),- create_message("assistant", "agent_a", "Response from A"),- create_message("assistant", "agent_b", "Response from B"),+ create_message("user", peer_id="web:visitor:alice"),+ create_message("user", peer_id="web:visitor:bob"),]extract_ctx = create_mock_extract_context(messages)handler = MemoryIsolationHandler(ctx, extract_ctx)@@ -100,15 +78,15 @@ class TestGetReadScope:scope = handler.get_read_scope()assert scope.user_ids == ["user_a"]- assert set(scope.agent_ids) == {"agent_a", "agent_b"}+ assert scope.peer_ids == []def test_deduplicate_users(self):"""Test that duplicate users are deduplicated."""ctx = create_ctx()messages = [- create_message("user", "user_a", "First message"),- create_message("user", "user_a", "Second message"),- create_message("user", "user_a", "Third message"),+ create_message("user", "First message"),+ create_message("user", "Second message"),+ create_message("user", "Third message"),]extract_ctx = create_mock_extract_context(messages)handler = MemoryIsolationHandler(ctx, extract_ctx)@@ -119,102 +97,79 @@ class TestGetReadScope:def test_empty_messages_uses_ctx_defaults(self):"""Test that empty messages fall back to ctx defaults."""- ctx = create_ctx(user_id="default_user", agent_id="default_agent")- messages = []- extract_ctx = create_mock_extract_context(messages)- handler = MemoryIsolationHandler(ctx, extract_ctx)-- scope = handler.get_read_scope()-- assert scope.user_ids == ["default_user"]- assert scope.agent_ids == ["default_agent"]-- def test_messages_without_role_id_uses_ctx_defaults(self):- """Test that messages without role_id fall back to ctx defaults."""- ctx = create_ctx(user_id="default_user", agent_id="default_agent")-- # Message without role_id- msg = Message(- id="msg_no_role_id",- role="user",- parts=[TextPart(text="Hello")],- role_id=None,+ ctx = create_ctx(+ user_id="default_user",)- messages = [msg]+ messages = []extract_ctx = create_mock_extract_context(messages)handler = MemoryIsolationHandler(ctx, extract_ctx)scope = handler.get_read_scope()- # Should use ctx defaults because no valid role_id found in messagesassert scope.user_ids == ["default_user"]- assert scope.agent_ids == ["default_agent"]-class TestFillRoleIds:- """Tests for fill_role_ids."""+class TestFillIdentityFields:+ """Tests for fill_identity_fields."""- def test_fill_role_ids_with_specified_values(self):- """Test fill_role_ids with specified user_id and agent_id."""+ def test_fill_identity_fields_with_specified_values(self):+ """Test fill_identity_fields keeps writes scoped to the ctx user."""ctx = create_ctx()messages = [- create_message("user", "user_a"),- create_message("assistant", "agent_a"),+ create_message("user"),+ create_message("assistant"),]extract_ctx = create_mock_extract_context(messages)handler = MemoryIsolationHandler(ctx, extract_ctx)role_scope = handler.get_read_scope()- item_dict = {"user_id": "user_a", "agent_id": "agent_a"}- handler.fill_role_ids(item_dict, role_scope)+ item_dict = {"user_id": "user_a"}+ handler.fill_identity_fields(item_dict, role_scope)assert item_dict["user_id"] == "user_a"- assert item_dict["agent_id"] == "agent_a"- def test_fill_role_ids_without_values_uses_default(self):- """Test fill_role_ids without values uses first in scope."""+ def test_fill_identity_fields_without_values_uses_default(self):+ """Test fill_identity_fields without values uses ctx user."""ctx = create_ctx()messages = [- create_message("user", "user_a"),- create_message("user", "user_b"),- create_message("assistant", "agent_a"),- create_message("assistant", "agent_b"),+ create_message("user"),+ create_message("user"),+ create_message("assistant"),+ create_message("assistant"),]extract_ctx = create_mock_extract_context(messages)handler = MemoryIsolationHandler(ctx, extract_ctx)role_scope = handler.get_read_scope()item_dict = {}- handler.fill_role_ids(item_dict, role_scope)+ handler.fill_identity_fields(item_dict, role_scope)- assert item_dict["user_id"] in ["user_a", "user_b"]- assert item_dict["agent_id"] in ["agent_a", "agent_b"]+ assert item_dict["user_id"] == "user_a"- def test_fill_role_ids_invalid_user_id_ignored(self):+ def test_fill_identity_fields_invalid_user_id_ignored(self):"""Test invalid user_id is ignored, uses default."""ctx = create_ctx()messages = [- create_message("user", "user_a"),- create_message("assistant", "agent_a"),+ create_message("user"),+ create_message("assistant"),]extract_ctx = create_mock_extract_context(messages)handler = MemoryIsolationHandler(ctx, extract_ctx)role_scope = handler.get_read_scope()- item_dict = {"user_id": "invalid_user", "agent_id": "agent_a"}- handler.fill_role_ids(item_dict, role_scope)+ item_dict = {"user_id": "invalid_user"}+ handler.fill_identity_fields(item_dict, role_scope)assert item_dict["user_id"] == "user_a" # fallback to default- assert item_dict["agent_id"] == "agent_a"- def test_fill_role_ids_with_ranges(self):- """Test fill_role_ids with ranges extracts from messages."""+ def test_fill_identity_fields_with_ranges_keeps_ctx_user_only(self):+ """ranges do not create multi-user write scopes."""ctx = create_ctx()messages = [- create_message("user", "user_a"),- create_message("assistant", "agent_a"),- create_message("user", "user_b"),- create_message("assistant", "agent_b"),+ create_message("user"),+ create_message("assistant"),+ create_message("user"),+ create_message("assistant"),]extract_ctx = create_mock_extract_context(messages)@@ -227,68 +182,46 @@ class TestFillRoleIds:role_scope = handler.get_read_scope()item_dict = {"ranges": "0-3"}- handler.fill_role_ids(item_dict, role_scope)-- assert "user_ids" in item_dict- assert "agent_ids" in item_dict- assert set(item_dict["user_ids"]) == {"user_a", "user_b"}- assert set(item_dict["agent_ids"]) == {"agent_a", "agent_b"}-+ handler.fill_identity_fields(item_dict, role_scope)-class TestPrepareMessages:- """Tests for prepare_messages with role_id_memory_isolation_enabled toggle."""-- @patch("openviking.session.memory.memory_isolation_handler.get_openviking_config")- def test_prepare_messages_disabled_fills_missing_role_ids(self, mock_config):- """开关关闭时,prepare_messages 用登录身份回填缺失的 role_id。"""- mock_memory_config = MagicMock()- mock_memory_config.role_id_memory_isolation_enabled = False- mock_config.return_value.memory = mock_memory_config+ assert item_dict["user_id"] == "user_a"+ assert "user_ids" not in item_dict- ctx = create_ctx(user_id="login_user", agent_id="login_agent")- messages = [- create_message("user", None, "Hello"),- create_message("assistant", None, "Hi"),- create_message("user", "user_b", "Hey"),- ]+ def test_fill_identity_fields_normalizes_explicit_peer_id(self):+ ctx = create_ctx()+ messages = [create_message("user", peer_id="web:visitor:alice")]extract_ctx = create_mock_extract_context(messages)handler = MemoryIsolationHandler(ctx, extract_ctx)- handler.prepare_messages()+ role_scope = handler.get_read_scope()++ item_dict = {"peer_id": "web:visitor:alice"}+ handler.fill_identity_fields(item_dict, role_scope)- assert messages[0].role_id == "login_user"- assert messages[1].role_id == "login_agent"- assert messages[2].role_id == "user_b"+ assert item_dict["user_id"] == "user_a"+ assert item_dict["peer_id"] == "web:visitor:alice"- @patch("openviking.session.memory.memory_isolation_handler.get_openviking_config")- def test_prepare_messages_enabled_keeps_role_ids(self, mock_config):- """开关开启时,prepare_messages 不修改 role_id。"""- mock_memory_config = MagicMock()- mock_memory_config.role_id_memory_isolation_enabled = True- mock_config.return_value.memory = mock_memory_config- ctx = create_ctx(user_id="login_user", agent_id="login_agent")+class TestPrepareMessages:+ """Tests for prepare_messages under the user/peer model."""++ def test_prepare_messages_keeps_peer_metadata(self):+ ctx = create_ctx(user_id="login_user")messages = [- create_message("user", "user_a", "Hello"),- create_message("assistant", "agent_a", "Hi"),+ create_message("user", "Hello"),+ create_message("assistant", "Hi"),+ create_message("user", "Hey", peer_id="web:visitor:alice"),]extract_ctx = create_mock_extract_context(messages)handler = MemoryIsolationHandler(ctx, extract_ctx)handler.prepare_messages()- assert messages[0].role_id == "user_a"- assert messages[1].role_id == "agent_a"-- @patch("openviking.session.memory.memory_isolation_handler.get_openviking_config")- def test_get_read_scope_with_prepare_disabled_uses_ctx_for_missing_role_ids(self, mock_config):- """开关关闭时,get_read_scope 对缺失 role_id 的消息回退到登录身份。"""- mock_memory_config = MagicMock()- mock_memory_config.role_id_memory_isolation_enabled = False- mock_config.return_value.memory = mock_memory_config+ assert messages[2].peer_id == "web:visitor:alice"- ctx = create_ctx(user_id="login_user", agent_id="login_agent")+ def test_get_read_scope_uses_ctx_user(self):+ ctx = create_ctx(user_id="login_user")messages = [- create_message("user", None, "Hello"),- create_message("assistant", None, "Hi"),+ create_message("user", "Hello"),+ create_message("assistant", "Hi"),]extract_ctx = create_mock_extract_context(messages)handler = MemoryIsolationHandler(ctx, extract_ctx)@@ -296,54 +229,49 @@ class TestPrepareMessages:scope = handler.get_read_scope()assert scope.user_ids == ["login_user"]- assert scope.agent_ids == ["login_agent"]-- @patch("openviking.session.memory.memory_isolation_handler.get_openviking_config")- def test_get_read_scope_with_prepare_enabled(self, mock_config):- """开关开启时,get_read_scope 从 message role_id 提取参与者。"""- mock_memory_config = MagicMock()- mock_memory_config.role_id_memory_isolation_enabled = True- mock_config.return_value.memory = mock_memory_config- ctx = create_ctx(user_id="login_user", agent_id="login_agent")+ def test_get_read_scope_ignores_message_peer_id_without_target(self):+ ctx = create_ctx(user_id="login_user")messages = [- create_message("user", "user_a", "Hello"),- create_message("assistant", "agent_a", "Hi"),+ create_message("user", "Hello", peer_id="web:visitor:alice"),+ create_message("assistant", "Hi"),]extract_ctx = create_mock_extract_context(messages)handler = MemoryIsolationHandler(ctx, extract_ctx)handler.prepare_messages()scope = handler.get_read_scope()- assert set(scope.user_ids) == {"user_a"}- assert set(scope.agent_ids) == {"agent_a"}-- @patch("openviking.session.memory.memory_isolation_handler.get_openviking_config")- def test_prepare_messages_no_config_fills_missing_role_ids(self, mock_config):- """没有 memory 配置时,默认关闭,并用登录身份回填缺失的 role_id。"""- mock_config.return_value.memory = None+ assert scope.user_ids == ["login_user"]+ assert scope.peer_ids == []- ctx = create_ctx(user_id="login_user", agent_id="login_agent")+ def test_get_read_scope_includes_allowed_peer_ids_when_enabled(self):+ ctx = create_ctx(user_id="login_user")messages = [- create_message("user", None, "Hello"),+ create_message("user", "Hello", peer_id="web:visitor:alice"),]extract_ctx = create_mock_extract_context(messages)- handler = MemoryIsolationHandler(ctx, extract_ctx)+ handler = MemoryIsolationHandler(+ ctx,+ extract_ctx,+ allowed_peer_ids={"web:visitor:alice"},+ )handler.prepare_messages()+ scope = handler.get_read_scope()- assert messages[0].role_id == "login_user"+ assert scope.user_ids == ["login_user"]+ assert scope.peer_ids == ["web:visitor:alice"]class TestCalculateMemoryUris:"""Tests for calculate_memory_uris (integration with URI generation)."""@patch("openviking.session.memory.memory_isolation_handler.generate_uri")- def test_calculate_memory_uris_single_user_agent(self, mock_generate_uri):- """Test calculate_memory_uris with single user and agent."""+ def test_calculate_memory_uris_single_user(self, mock_generate_uri):+ """Test calculate_memory_uris with a single user."""mock_generate_uri.return_value = "viking://user/user_a/memories/preferences"ctx = create_ctx()- messages = [create_message("user", "user_a")]+ messages = [create_message("user")]extract_ctx = create_mock_extract_context(messages)handler = MemoryIsolationHandler(ctx, extract_ctx)@@ -357,7 +285,7 @@ class TestCalculateMemoryUris:operation = ResolvedOperation(old_memory_file_content=None,- memory_fields={"user_id": "user_a", "agent_id": "agent_a"},+ memory_fields={"user_id": "user_a"},memory_type="preferences",uris=[],)@@ -368,14 +296,14 @@ class TestCalculateMemoryUris:assert "user_a" in uris[0]@patch("openviking.session.memory.memory_isolation_handler.generate_uri")- def test_calculate_memory_uris_multiple_users_agents(self, mock_generate_uri):- """Test calculate_memory_uris with multiple users and agents."""+ def test_calculate_memory_uris_ignores_extracted_user_ids(self, mock_generate_uri):+ """LLM-extracted user_ids cannot redirect memory writes."""mock_generate_uri.side_effect = lambda **kwargs: (f"viking://user/{kwargs.get('user_space')}/memories/test")ctx = create_ctx()- messages = [create_message("user", "user_a")]+ messages = [create_message("user")]extract_ctx = create_mock_extract_context(messages)handler = MemoryIsolationHandler(ctx, extract_ctx)@@ -389,11 +317,127 @@ class TestCalculateMemoryUris:operation = ResolvedOperation(old_memory_file_content=None,- memory_fields={"user_ids": ["user_a", "user_b"], "agent_ids": ["agent_a", "agent_b"]},+ memory_fields={"user_ids": ["user_a", "user_b"]},memory_type="test",uris=[],)uris = handler.calculate_memory_uris(schema, operation, extract_ctx)- assert len(uris) == 4 # 2 users * 2 agents+ assert uris == ["viking://user/user_a/memories/test"]+ assert operation.memory_fields["user_id"] == "user_a"++ @patch("openviking.session.memory.memory_isolation_handler.generate_uri")+ def test_calculate_memory_uris_routes_explicit_peer_memory(self, mock_generate_uri):+ mock_generate_uri.side_effect = lambda **kwargs: (+ f"viking://user/{kwargs.get('user_space')}/memories/preferences"+ )++ ctx = create_ctx(+ user_id="support_bot",+ )+ messages = [create_message("user", peer_id="web:visitor:alice")]+ extract_ctx = create_mock_extract_context(messages)+ handler = MemoryIsolationHandler(+ ctx,+ extract_ctx,+ allowed_peer_ids={"web:visitor:alice"},+ )++ from openviking.session.memory.dataclass import MemoryTypeSchema, ResolvedOperation++ schema = MemoryTypeSchema(+ memory_type="preferences",+ filename_template="preferences.md",+ directory="viking://user/{user_space}/memories",+ )+ operation = ResolvedOperation(+ old_memory_file_content=None,+ memory_fields={+ "user_id": "alice",+ "peer_id": "web:visitor:alice",+ },+ memory_type="preferences",+ uris=[],+ )++ uris = handler.calculate_memory_uris(schema, operation, extract_ctx)++ assert uris == ["viking://user/support_bot/peers/web:visitor:alice/memories/preferences"]+ assert operation.memory_fields["user_id"] == "support_bot"+ assert operation.memory_fields["peer_id"] == "web:visitor:alice"++ @patch("openviking.session.memory.memory_isolation_handler.generate_uri")+ def test_calculate_memory_uris_routes_ranges_to_self_and_peer(self, mock_generate_uri):+ mock_generate_uri.side_effect = lambda **kwargs: (+ f"viking://user/{kwargs.get('user_space')}/memories/events/demo"+ )++ ctx = create_ctx(user_id="support_bot")+ messages = [+ create_message("user", "self event"),+ create_message("user", "peer event", peer_id="web:visitor:alice"),+ ]+ extract_ctx = create_mock_extract_context(messages)+ mock_range = MagicMock()+ mock_range.elements = [messages]+ extract_ctx.read_message_ranges.return_value = mock_range+ handler = MemoryIsolationHandler(+ ctx,+ extract_ctx,+ allow_self=True,+ allowed_peer_ids={"web:visitor:alice"},+ )++ from openviking.session.memory.dataclass import MemoryTypeSchema, ResolvedOperation++ schema = MemoryTypeSchema(+ memory_type="events",+ filename_template="demo.md",+ directory="viking://user/{user_space}/memories/events",+ )+ operation = ResolvedOperation(+ old_memory_file_content=None,+ memory_fields={"event_name": "demo", "ranges": "0-1"},+ memory_type="events",+ uris=[],+ )++ uris = handler.calculate_memory_uris(schema, operation, extract_ctx)++ assert set(uris) == {+ "viking://user/support_bot/memories/events/demo",+ "viking://user/support_bot/peers/web:visitor:alice/memories/events/demo",+ }+ assert operation.memory_fields["user_id"] == "support_bot"+ assert "peer_id" not in operation.memory_fields++ @patch("openviking.session.memory.memory_isolation_handler.generate_uri")+ def test_calculate_memory_uris_rejects_unallowed_peer_id(self, mock_generate_uri):+ ctx = create_ctx(user_id="support_bot")+ messages = [create_message("user", peer_id="web:visitor:alice")]+ extract_ctx = create_mock_extract_context(messages)+ handler = MemoryIsolationHandler(+ ctx,+ extract_ctx,+ allowed_peer_ids={"web:visitor:bob"},+ )++ from openviking.session.memory.dataclass import MemoryTypeSchema, ResolvedOperation++ schema = MemoryTypeSchema(+ memory_type="preferences",+ filename_template="preferences.md",+ directory="viking://user/{user_space}/memories",+ )+ operation = ResolvedOperation(+ old_memory_file_content=None,+ memory_fields={"peer_id": "web:visitor:alice"},+ memory_type="preferences",+ uris=[],+ )++ uris = handler.calculate_memory_uris(schema, operation, extract_ctx)++ assert uris == []+ mock_generate_uri.assert_not_called()diff --git a/tests/session/memory/test_memory_react.py b/tests/session/memory/test_memory_react.pyindex 853d76fa0..fd2856ae6 100644--- a/tests/session/memory/test_memory_react.py+++ b/tests/session/memory/test_memory_react.py@@ -4,7 +4,7 @@Tests for memory ExtractLoop orchestrator."""-from unittest.mock import AsyncMock, MagicMock, patch+from unittest.mock import AsyncMock, MagicMockimport pytest@@ -14,6 +14,7 @@ from openviking.session.memory.dataclass import (from openviking.session.memory.extract_loop import (ExtractLoop,)+from openviking.session.memory.memory_type_registry import MemoryTypeRegistryclass TestPreFetchFileFiltering:@@ -154,47 +155,30 @@ class TestAllowedDirectoriesList:def test_get_allowed_directories_list(self, mock_vlm, mock_viking_fs):"""Test that allowed directories list is properly formatted."""- # Patch the registry loading so we can inject our own schemas- with patch(- "openviking.session.memory.extract_loop.MemoryTypeRegistry"- ) as mock_registry_cls:- mock_registry = MagicMock()-- # Create test schemas- schema1 = MemoryTypeSchema(- memory_type="preferences",- description="Preferences",- directory="viking://user/{user_space}/memories/preferences",- filename_template="{topic}.md",- fields=[],- )- schema2 = MemoryTypeSchema(- memory_type="tools",- description="Tools",- directory="viking://agent/{agent_space}/memories/tools",- filename_template="{tool_name}.md",- fields=[],- )-- mock_registry.list_all.return_value = [schema1, schema2]- mock_registry_cls.return_value = mock_registry-- # Also patch schema_model_generator.- with patch("openviking.session.memory.extract_loop.SchemaModelGenerator") as mock_smg:- mock_smg_instance = MagicMock()- mock_smg_instance.generate_all_models = MagicMock()- mock_smg_instance.get_llm_json_schema = MagicMock(return_value={})- mock_smg.return_value = mock_smg_instance+ registry = MemoryTypeRegistry(load_schemas=False)++ schema1 = MemoryTypeSchema(+ memory_type="preferences",+ description="Preferences",+ directory="viking://user/{{ user_space }}/memories/preferences",+ filename_template="{{ topic }}.md",+ fields=[],+ )+ schema2 = MemoryTypeSchema(+ memory_type="tools",+ description="Tools",+ directory="viking://user/{{ user_space }}/memories/tools",+ filename_template="{{ tool_name }}.md",+ fields=[],+ )- # Create ExtractLoop- extract_loop = ExtractLoop(mock_vlm, mock_viking_fs)+ registry.register(schema1)+ registry.register(schema2)- # Call the method- result = extract_loop._get_allowed_directories_list()+ result = registry.list_search_uris(user_space="default")- # Verify the result contains the expected directories with variables replaced- assert "viking://user/default/memories/preferences" in result- assert "viking://agent/default/memories/tools" in result+ assert "viking://user/default/memories/preferences" in result+ assert "viking://user/default/memories/tools" in resultclass TestExtractLoopFinalJsonRetry:@@ -250,6 +234,9 @@ class TestExtractLoopFinalJsonRetry:def get_extract_context(self):return MagicMock()+ def get_output_language(self):+ return "en"+def instruction(self):return "Extract memory operations."diff --git a/tests/session/memory/test_memory_react_system_prompt.py b/tests/session/memory/test_memory_react_system_prompt.pyindex be2af4bae..874a98228 100644--- a/tests/session/memory/test_memory_react_system_prompt.py+++ b/tests/session/memory/test_memory_react_system_prompt.py@@ -40,6 +40,15 @@ class TestProviderInstruction:assert "Target Output Language" in instructionassert "All memory content MUST be written in" in instruction+ def test_instruction_explains_peer_memory_routing(self):+ provider = SessionExtractContextProvider(messages=[])++ instruction = provider.instruction()++ assert "Peer Memory" in instruction+ assert "profile/preferences/entities/events" in instruction+ assert "cases/patterns/tools/skills" in instruction+class TestSkillToolCallExposure:def test_assemble_conversation_includes_skill_tool_call(self):@@ -53,7 +62,7 @@ class TestSkillToolCallExposure:tool_id="tool_1",tool_name="read",tool_uri="viking://session/test/tools/tool_1",- skill_uri="viking://agent/skills/create_presentation",+ skill_uri="viking://user/skills/create_presentation",tool_input={"file_path": "/skills/ppt/SKILL.md"},tool_output="ok",tool_status="completed",@@ -96,6 +105,22 @@ class TestSkillToolCallExposure:assert '"tool_name": "read"' in conversationassert '"skill_name":' not in conversation+ def test_assemble_conversation_uses_peer_id_when_present(self):+ messages = [+ Message(+ id="m1",+ role="user",+ parts=[TextPart("My invoice is still missing.")],+ peer_id="web:visitor:alice",+ )+ ]+ provider = SessionExtractContextProvider(messages=messages)++ conversation = provider._assemble_conversation(messages)++ assert "[0][user][web:visitor:alice]" in conversation+ assert "[0][user][default]" not in conversation+def test_detect_language_only_uses_text_parts(self):messages = [Message(diff --git a/tests/session/memory/test_memory_timestamp_parsing.py b/tests/session/memory/test_memory_timestamp_parsing.pyindex c930abe39..86e121253 100644--- a/tests/session/memory/test_memory_timestamp_parsing.py+++ b/tests/session/memory/test_memory_timestamp_parsing.py@@ -7,12 +7,15 @@ import pytestfrom openviking.message import Messagefrom openviking.message.part import TextPart-from openviking.session.memory.memory_updater import MessageRange+from openviking.server.identity import RequestContext, Role+from openviking.session.memory.dataclass import MemoryFile, MemoryTypeSchema, ResolvedOperation+from openviking.session.memory.memory_isolation_handler import MemoryIsolationHandler+from openviking.session.memory.memory_updater import ExtractContext, MessageRangefrom openviking.session.memory.session_extract_context_provider import (SessionExtractContextProvider,)from openviking.session.memory.utils import MemoryFileUtils-from openviking.session.memory.dataclass import MemoryFile+from openviking_cli.session.user_id import UserIdentifierdef _message(*, created_at: str, role: str = "user", text: str = "hello") -> Message:@@ -71,6 +74,111 @@ def test_message_range_accepts_extended_fractional_seconds():assert msg_range._first_message_time_with_weekday() == "2026-04-17 (Friday)"+def test_message_range_uses_peer_id_when_present():+ msg_range = MessageRange(+ [+ [+ Message(+ id="msg-peer",+ role="user",+ parts=[TextPart(text="invoice follow-up")],+ peer_id="web:visitor:alice",+ )+ ]+ ]+ )++ assert "[web:visitor:alice]: invoice follow-up" in msg_range.pretty_print()+ assert "[default]: invoice follow-up" not in msg_range.pretty_print()+++def test_peer_id_routes_peer_memory_for_all_role_selected_types(stub_provider_config):+ messages = [+ Message(+ id="msg-peer",+ role="user",+ parts=[TextPart(text="I am Alice. Please contact me by email for invoices.")],+ peer_id="web:visitor:alice",+ )+ ]+ extract_context = ExtractContext(messages)+ ctx = RequestContext(+ user=UserIdentifier("acct", "support_bot"),+ role=Role.USER,+ )+ handler = MemoryIsolationHandler(+ ctx,+ extract_context,+ allowed_peer_ids={"web:visitor:alice"},+ )+ role_scope = handler.get_read_scope()+ fields = {"ranges": "0"}+ handler.fill_identity_fields(fields, role_scope)++ profile_schema = MemoryTypeSchema(+ memory_type="profile",+ directory="viking://user/{{ user_space }}/memories",+ filename_template="profile.md",+ fields=[],+ )+ profile_uris = handler.calculate_memory_uris(+ profile_schema,+ ResolvedOperation(memory_fields=fields, memory_type="profile", uris=[]),+ extract_context,+ )+ assert profile_uris == ["viking://user/support_bot/peers/web:visitor:alice/memories/profile.md"]++ tool_schema = MemoryTypeSchema(+ memory_type="tools",+ directory="viking://user/{{ user_space }}/memories/tools",+ filename_template="{{ tool_name }}.md",+ fields=[],+ )+ tool_fields = dict(fields, tool_name="email")+ tool_uris = handler.calculate_memory_uris(+ tool_schema,+ ResolvedOperation(memory_fields=tool_fields, memory_type="tools", uris=[]),+ extract_context,+ )+ assert tool_uris == [+ "viking://user/support_bot/peers/web:visitor:alice/memories/tools/email.md"+ ]+++def test_peer_id_range_does_not_route_without_allowed_peer_ids(stub_provider_config):+ messages = [+ Message(+ id="msg-peer",+ role="user",+ parts=[TextPart(text="I am Alice. Please contact me by email for invoices.")],+ peer_id="web:visitor:alice",+ )+ ]+ extract_context = ExtractContext(messages)+ ctx = RequestContext(+ user=UserIdentifier("acct", "support_bot"),+ role=Role.USER,+ )+ handler = MemoryIsolationHandler(ctx, extract_context)+ role_scope = handler.get_read_scope()+ fields = {"ranges": "0"}+ handler.fill_identity_fields(fields, role_scope)++ profile_schema = MemoryTypeSchema(+ memory_type="profile",+ directory="viking://user/{{ user_space }}/memories",+ filename_template="profile.md",+ fields=[],+ )+ profile_uris = handler.calculate_memory_uris(+ profile_schema,+ ResolvedOperation(memory_fields=fields, memory_type="profile", uris=[]),+ extract_context,+ )++ assert profile_uris == []++def test_deserialize_full_parses_memory_metadata_timestamps_with_z_suffix():mf = MemoryFile(content="memory body",diff --git a/tests/session/memory/test_memory_tools.py b/tests/session/memory/test_memory_tools.pyindex 05a9087ad..2c94fdfca 100644--- a/tests/session/memory/test_memory_tools.py+++ b/tests/session/memory/test_memory_tools.py@@ -6,8 +6,8 @@ Tests for memory tools.import pytest-from openviking.session.memory.dataclass import MemoryFilefrom openviking.server.identity import RequestContext, Role, ToolContext+from openviking.session.memory.dataclass import MemoryFilefrom openviking.session.memory.tools import (MEMORY_TOOLS_REGISTRY,MemoryLsTool,@@ -45,7 +45,7 @@ class TestMemoryTools:"Gina values [emotional support](../../events/2023/03/23/mutual_business_support.md) ""with Jon.\n\n""<!-- MEMORY_FIELDS\n"- "{\"memory_type\": \"experiences\"}\n"+ '{"memory_type": "experiences"}\n'"-->")@@ -114,7 +114,9 @@ class TestMemoryTools:class MockVikingFS:async def read_file(self, uri, ctx=None, **kwargs):- return "line1\nline2\nline3\n\n<!-- MEMORY_FIELDS\n{\"memory_type\": \"experiences\"}\n-->"+ return (+ 'line1\nline2\nline3\n\n<!-- MEMORY_FIELDS\n{"memory_type": "experiences"}\n-->'+ )tool_ctx = ToolContext(viking_fs=MockVikingFS(),@@ -142,7 +144,7 @@ class TestMemoryTools:class MockVikingFS:async def read_file(self, uri, ctx=None, **kwargs):- return "line1\nline2\n\n<!-- MEMORY_FIELDS\n{\"memory_type\": \"experiences\"}\n-->"+ return 'line1\nline2\n\n<!-- MEMORY_FIELDS\n{"memory_type": "experiences"}\n-->'tool_ctx = ToolContext(viking_fs=MockVikingFS(),@@ -199,14 +201,12 @@ class TestMemoryTools:self.received_ctx = ctxself.received_target_uri = target_uriself.received_limit = limit- _ = ctx.namespace_policyreturn MockSearchResult()request_ctx = RequestContext(user=UserIdentifier(account_id="test-account",user_id="test-user",- agent_id="test-agent",),role=Role.USER,)diff --git a/tests/session/memory/test_memory_updater.py b/tests/session/memory/test_memory_updater.pyindex caf9cea2e..82161d766 100644--- a/tests/session/memory/test_memory_updater.py+++ b/tests/session/memory/test_memory_updater.py@@ -4,17 +4,16 @@Tests for MemoryUpdater."""-from types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMockimport pytestfrom openviking.message import Messagefrom openviking.message.part import TextPart-from openviking.server.identity import AccountNamespacePolicy, RequestContext, Role+from openviking.server.identity import RequestContext, Rolefrom openviking.session.memory.dataclass import (- MemoryFile,MemoryField,+ MemoryFile,MemoryTypeSchema,ResolvedOperation,ResolvedOperations,@@ -162,7 +161,7 @@ class TestMemoryUpdater:extract_context.page_id_map.register_new_page_id(bob_uri, 100)isolation_handler = MagicMock()- ctx = RequestContext(user=UserIdentifier("acme", "alice", "bot"), role=Role.USER)+ ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)result = await updater.apply_operations(operations=operations,@@ -201,47 +200,18 @@ class TestMemoryUpdater:delete_file_contents=[],errors=[],)- ctx = RequestContext(user=UserIdentifier("acme", "alice", "bot"), role=Role.USER)+ ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)with pytest.raises(ValueError, match="missing resolved URIs"):await updater.apply_operations(operations=operations, ctx=ctx)@pytest.mark.asyncio- @pytest.mark.parametrize(- ("policy", "schema_directory", "resolved_uri", "expected_directory", "memory_type"),- [- (- AccountNamespacePolicy(- isolate_user_scope_by_agent=True,- isolate_agent_scope_by_user=False,- ),- "viking://user/{{ user_space }}/memories/preferences",- "viking://user/alice/agent/bot/memories/preferences/theme.md",- "viking://user/alice/agent/bot/memories/preferences",- "preferences",- ),- (- AccountNamespacePolicy(- isolate_user_scope_by_agent=False,- isolate_agent_scope_by_user=True,- ),- "viking://agent/{{ agent_space }}/memories/tools",- "viking://agent/bot/user/alice/memories/tools/web_search.md",- "viking://agent/bot/user/alice/memories/tools",- "tools",- ),- ],- )- async def test_apply_operations_matches_overview_directories_with_namespace_policy(- self,- monkeypatch,- policy,- schema_directory,- resolved_uri,- expected_directory,- memory_type,- ):- """Overview generation should use policy-expanded user/agent space fragments."""+ async def test_apply_operations_matches_overview_directory_from_resolved_user_uri(self):+ """Overview generation should use the resolved user memory directory."""+ memory_type = "preferences"+ schema_directory = "viking://user/{{ user_space }}/memories/preferences"+ resolved_uri = "viking://user/alice/memories/preferences/theme.md"+ expected_directory = "viking://user/alice/memories/preferences"schema = MemoryTypeSchema(memory_type=memory_type,description=f"{memory_type} memory",@@ -272,9 +242,8 @@ class TestMemoryUpdater:)ctx = RequestContext(- user=UserIdentifier("acme", "alice", "bot"),+ user=UserIdentifier("acme", "alice"),role=Role.USER,- namespace_policy=policy,)result = await updater.apply_operations(operations=resolved, ctx=ctx)@@ -286,15 +255,16 @@ class TestMemoryUpdater:ctx,None,)+@pytest.mark.asyncioasync def test_apply_operations_skips_link_updates_for_deleted_uris(self, monkeypatch):- deleted_uri = "viking://agent/agent_sample_3/memories/experiences/old.md"- written_uri = "viking://agent/agent_sample_3/memories/experiences/new.md"+ deleted_uri = "viking://user/user_sample_3/memories/experiences/old.md"+ written_uri = "viking://user/user_sample_3/memories/experiences/new.md"schema = MemoryTypeSchema(memory_type="experiences",description="experience memory",- directory="viking://agent/{{ agent_space }}/memories/experiences",+ directory="viking://user/{{ user_space }}/memories/experiences",filename_template="{{ experience_name }}.md",fields=[],overview_template="overview",@@ -307,7 +277,9 @@ class TestMemoryUpdater:updater.generate_overview = AsyncMock()mock_viking_fs = MagicMock()- mock_viking_fs.read_file = AsyncMock(side_effect=AssertionError("deleted URI should not be read"))+ mock_viking_fs.read_file = AsyncMock(+ side_effect=AssertionError("deleted URI should not be read")+ )mock_viking_fs.write_file = AsyncMock()updater._get_viking_fs = MagicMock(return_value=mock_viking_fs)@@ -319,7 +291,9 @@ class TestMemoryUpdater:uris=[written_uri],)],- delete_file_contents=[MemoryFile(uri=deleted_uri, extra_fields={"memory_type": "experiences"})],+ delete_file_contents=[+ MemoryFile(uri=deleted_uri, extra_fields={"memory_type": "experiences"})+ ],errors=[],resolved_links=[StoredLink(@@ -329,7 +303,6 @@ class TestMemoryUpdater:],)-async def mock_apply_upsert(resolved_op, ctx, extract_context=None):return None@@ -339,7 +312,7 @@ class TestMemoryUpdater:updater._apply_upsert = AsyncMock(side_effect=mock_apply_upsert)updater._apply_delete = AsyncMock(side_effect=mock_apply_delete)- ctx = RequestContext(user=UserIdentifier("acme", "alice", "bot"), role=Role.USER)+ ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)result = await updater.apply_operations(operations=resolved, ctx=ctx)@@ -349,8 +322,12 @@ class TestMemoryUpdater:@pytest.mark.asyncioasync def test_apply_operations_routes_backlinks_to_matching_uri_only(self):- caroline_uri = "viking://user/Caroline/memories/events/2023/05/08/career_education_planning.md"- melanie_uri = "viking://user/Melanie/memories/events/2023/05/08/career_education_planning.md"+ caroline_uri = (+ "viking://user/Caroline/memories/events/2023/05/08/career_education_planning.md"+ )+ melanie_uri = (+ "viking://user/Melanie/memories/events/2023/05/08/career_education_planning.md"+ )profile_uri = "viking://user/Caroline/memories/profile.md"schema = MemoryTypeSchema(@@ -405,7 +382,7 @@ class TestMemoryUpdater:],)- ctx = RequestContext(user=UserIdentifier("acme", "alice", "bot"), role=Role.USER)+ ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)await updater.apply_operations(operations=operations, ctx=ctx)@@ -769,7 +746,9 @@ class TestConsecutivePatchesSameURI:trace_info = MagicMock()patch_warning = MagicMock()monkeypatch.setattr("openviking.session.memory.memory_updater.tracer.info", trace_info)- monkeypatch.setattr("openviking.session.memory.merge_op.patch_handler.logger.warning", patch_warning)+ monkeypatch.setattr(+ "openviking.session.memory.merge_op.patch_handler.logger.warning", patch_warning+ )op = ResolvedOperation(old_memory_file_content=MemoryFile(diff --git a/tests/session/memory/test_memory_utils.py b/tests/session/memory/test_memory_utils.pyindex 0ce531d0d..bfa5ad859 100644--- a/tests/session/memory/test_memory_utils.py+++ b/tests/session/memory/test_memory_utils.py@@ -9,19 +9,13 @@ import pytestfrom openviking.session.memory.dataclass import (MemoryField,MemoryFile,- MemoryOperations,MemoryTypeSchema,)-from openviking.session.memory.memory_type_registry import MemoryTypeRegistryfrom openviking.session.memory.merge_op.base import FieldType, MergeOpfrom openviking.session.memory.utils import (- collect_allowed_directories,- collect_allowed_path_patterns,generate_uri,is_uri_allowed,- is_uri_allowed_for_schema,parse_memory_file_with_fields,- resolve_all_operations,validate_uri_template,)from openviking.session.memory.utils.memory_file_utils import MemoryFileUtils@@ -66,7 +60,7 @@ class TestUriGeneration:memory_type = MemoryTypeSchema(memory_type="tools",description="Tool usage memory",- directory="viking://agent/{{ agent_space }}/memories/tools",+ directory="viking://user/{{ user_space }}/memories/tools",filename_template="{{ tool_name }}.md",fields=[MemoryField(@@ -81,10 +75,10 @@ class TestUriGeneration:uri = generate_uri(memory_type,{"tool_name": "web_search"},- agent_space="default",+ user_space="default",)- assert uri == "viking://agent/default/memories/tools/web_search.md"+ assert uri == "viking://user/default/memories/tools/web_search.md"def test_generate_uri_only_directory(self):"""Test generating URI with only directory."""@@ -201,67 +195,11 @@ class TestUriGeneration:class TestUriValidation:"""Tests for URI validation."""- def test_collect_allowed_directories(self):- """Test collecting allowed directories from schemas."""- schemas = [- MemoryTypeSchema(- memory_type="preferences",- description="Preferences",- directory="viking://user/{{ user_space }}/memories/preferences",- filename_template="{{ topic }}.md",- fields=[],- ),- MemoryTypeSchema(- memory_type="tools",- description="Tools",- directory="viking://agent/{{ agent_space }}/memories/tools",- filename_template="{{ tool_name }}.md",- fields=[],- ),- MemoryTypeSchema(- memory_type="disabled",- description="Disabled",- directory="viking://user/default/memories/disabled",- filename_template="",- fields=[],- enabled=False,- ),- ]-- dirs = collect_allowed_directories(- [s for s in schemas if s.enabled], user_space="default", agent_space="default"- )-- assert dirs == {- "viking://user/default/memories/preferences",- "viking://agent/default/memories/tools",- }-- def test_collect_allowed_path_patterns(self):- """Test collecting allowed path patterns from schemas."""- schemas = [- MemoryTypeSchema(- memory_type="preferences",- description="Preferences",- directory="viking://user/{{ user_space }}/memories/preferences",- filename_template="{{ topic }}.md",- fields=[],- ),- ]-- patterns = collect_allowed_path_patterns(- schemas, user_space="default", agent_space="default"- )-- assert patterns == {- "viking://user/default/memories/preferences/{{ topic }}.md",- }-def test_is_uri_allowed_by_directory(self):"""Test URI allowed by matching directory prefix."""allowed_dirs = {"viking://user/default/memories/preferences",- "viking://agent/default/memories/tools",+ "viking://user/default/memories/tools",}allowed_patterns = set()@@ -333,127 +271,6 @@ class TestUriValidation:is False)- def test_is_uri_allowed_for_schema(self):- """Test checking URI against schemas."""- schemas = [- MemoryTypeSchema(- memory_type="preferences",- description="Preferences",- directory="viking://user/{{ user_space }}/memories/preferences",- filename_template="{{ topic }}.md",- fields=[],- ),- ]-- assert (- is_uri_allowed_for_schema(- "viking://user/default/memories/preferences/test.md",- schemas,- )- is True- )-- assert (- is_uri_allowed_for_schema(- "viking://user/default/memories/other/test.md",- schemas,- )- is False- )---class TestUriResolution:- """Tests for URI resolution methods."""-- @pytest.fixture- def test_registry(self):- """Create a test registry with sample schemas."""- registry = MemoryTypeRegistry()-- # Add preferences schema- registry.register(- MemoryTypeSchema(- memory_type="preferences",- description="User preferences",- directory="viking://user/{{ user_space }}/memories/preferences",- filename_template="{{ topic }}.md",- fields=[- MemoryField(name="topic", field_type=FieldType.STRING, description="Topic"),- ],- )- )-- # Add tools schema- registry.register(- MemoryTypeSchema(- memory_type="tools",- description="Tool memories",- directory="viking://agent/{{ agent_space }}/memories/tools",- filename_template="{{ tool_name }}.md",- fields=[- MemoryField(- name="tool_name", field_type=FieldType.STRING, description="Tool name"- ),- ],- )- )-- return registry-- def test_resolve_all_operations(self, test_registry):- """Test resolving all operations at once."""- operations = MemoryOperations(- write_uris=[- {- "memory_type": "preferences",- "topic": "Write test",- "content": "Write content",- },- ],- edit_uris=[- {- "memory_type": "tools",- "tool_name": "edit_tool",- "content": "Updated",- },- ],- delete_uris=[- "viking://user/default/memories/preferences/Delete me.md",- ],- )-- resolved = resolve_all_operations(operations, test_registry)-- assert resolved.has_errors() is False- # All operations are now unified into operations list- assert len(resolved.operations) == 2- assert len(resolved.delete_operations) == 1-- # Verify resolved URIs - both write and edit go to operations list- uris = [op.uri for op in resolved.operations]- assert "viking://user/default/memories/preferences/Write test.md" in uris- assert "viking://agent/default/memories/tools/edit_tool.md" in uris- assert (- resolved.delete_operations[0][1]- == "viking://user/default/memories/preferences/Delete me.md"- )-- def test_resolve_all_operations_with_errors(self, test_registry):- """Test resolving operations with errors."""- operations = MemoryOperations(- write_uris=[- {- "memory_type": "unknown",- },- ],- )-- resolved = resolve_all_operations(operations, test_registry)-- assert resolved.has_errors() is True- assert len(resolved.errors) == 1- assert "Failed to resolve" in resolved.errors[0]-class TestParseMemoryFileWithFields:"""Tests for parse_memory_file_with_fields function."""diff --git a/tests/session/test_commit_skill_inference.py b/tests/session/test_commit_skill_inference.pyindex 268ddb4af..d5c8dd77c 100644--- a/tests/session/test_commit_skill_inference.py+++ b/tests/session/test_commit_skill_inference.py@@ -43,7 +43,7 @@ def _build_duplicate_session_skill_operations() -> ResolvedOperations:"content": content,},memory_type="session_skills",- uris=["viking://agent/default/skills/general-knowledge-flow/SKILL.md"],+ uris=["viking://user/default/skills/general-knowledge-flow/SKILL.md"],),ResolvedOperation(old_memory_file_content=None,@@ -53,7 +53,7 @@ def _build_duplicate_session_skill_operations() -> ResolvedOperations:"content": content,},memory_type="session_skills",- uris=["viking://agent/default/skills/general-knowledge-steps/SKILL.md"],+ uris=["viking://user/default/skills/general-knowledge-steps/SKILL.md"],),],delete_file_contents=[],@@ -75,8 +75,9 @@ async def test_session_compressor_v2_extract_agent_memories_returns_session_skilstrict_extract_errors,phase_label,post_apply=None,+ **kwargs,):- del self, messages, ctx, strict_extract_errors, post_apply+ del self, messages, ctx, strict_extract_errors, post_apply, kwargsassert phase_label == "trajectory"assert provider._include_trajectories is Falseassert provider._include_session_skills is True@@ -89,9 +90,9 @@ async def test_session_compressor_v2_extract_agent_memories_returns_session_skil{"status": "success","action": "create",- "uri": "viking://agent/default/skills/code-review",- "root_uri": "viking://agent/default/skills/code-review",- "skill_md_uri": "viking://agent/default/skills/code-review/SKILL.md",+ "uri": "viking://user/default/skills/code-review",+ "root_uri": "viking://user/default/skills/code-review",+ "skill_md_uri": "viking://user/default/skills/code-review/SKILL.md",}],)@@ -113,9 +114,9 @@ async def test_session_compressor_v2_extract_agent_memories_returns_session_skil{"status": "success","action": "create",- "uri": "viking://agent/default/skills/code-review",- "root_uri": "viking://agent/default/skills/code-review",- "skill_md_uri": "viking://agent/default/skills/code-review/SKILL.md",+ "uri": "viking://user/default/skills/code-review",+ "root_uri": "viking://user/default/skills/code-review",+ "skill_md_uri": "viking://user/default/skills/code-review/SKILL.md","archive_uri": "viking://sessions/s1/history/archive_001",}],@@ -178,7 +179,7 @@ async def test_session_compressor_v2_run_extract_phase_dedups_duplicate_session_)assert result is not None- assert result[4][0]["uri"] == "viking://agent/default/skills/general-knowledge-flow"+ assert result[4][0]["uri"] == "viking://user/default/skills/general-knowledge-flow"@pytest.mark.asyncio@@ -189,7 +190,7 @@ async def test_session_skill_context_provider_prefetch_lists_existing_skills():return_value=[{"name": "code-review",- "uri": "viking://agent/default/skills/code-review",+ "uri": "viking://user/default/skills/code-review","isDir": True,"abstract": "name: code-review\ndescription: Review code carefully",}@@ -239,7 +240,7 @@ async def test_agent_trajectory_context_provider_delegates_skill_prefetch_and_rereturn_value=[{"name": "code-review",- "uri": "viking://agent/default/skills/code-review",+ "uri": "viking://user/default/skills/code-review","isDir": True,"abstract": "name: code-review\ndescription: Review code carefully",}@@ -274,7 +275,7 @@ tags:read_result = await provider.execute_tool(SimpleNamespace(name="read",- arguments={"uri": "viking://agent/default/skills/code-review/SKILL.md"},+ arguments={"uri": "viking://user/default/skills/code-review/SKILL.md"},))@@ -283,7 +284,7 @@ tags:assert provider.get_tools() == ["read"]assert read_result["name"] == "code-review"assert "先读文件" in read_result["content"]- assert "viking://agent/default/skills/code-review/SKILL.md" in provider.read_file_contents+ assert "viking://user/default/skills/code-review/SKILL.md" in provider.read_file_contentsassert provider._skill_provider.read_file_contents is provider.read_file_contentsassert provider._skill_provider._ctx is ctxassert provider._skill_provider._viking_fs is viking_fs@@ -296,8 +297,8 @@ async def test_skill_operation_updater_creates_skill_with_session_defaults():processor.process_skill = AsyncMock(return_value={"status": "success",- "uri": "viking://agent/default/skills/code-review",- "root_uri": "viking://agent/default/skills/code-review",+ "uri": "viking://user/default/skills/code-review",+ "root_uri": "viking://user/default/skills/code-review",})processor.sanitize_skill_privacy = AsyncMock(side_effect=lambda skill_dict, _ctx: skill_dict)@@ -308,7 +309,7 @@ async def test_skill_operation_updater_creates_skill_with_session_defaults():skill_processor=processor,viking_fs=viking_fs,)- uri = "viking://agent/default/skills/code-review/SKILL.md"+ uri = "viking://user/default/skills/code-review/SKILL.md"operations = ResolvedOperations(upsert_operations=[ResolvedOperation(@@ -387,7 +388,7 @@ tags:skill_processor=processor,viking_fs=viking_fs,)- uri = "viking://agent/default/skills/code-review/SKILL.md"+ uri = "viking://user/default/skills/code-review/SKILL.md"operations = ResolvedOperations(upsert_operations=[ResolvedOperation(@@ -490,7 +491,7 @@ tags:skill_processor=processor,viking_fs=viking_fs,)- uri = "viking://agent/default/skills/code-review/SKILL.md"+ uri = "viking://user/default/skills/code-review/SKILL.md"operations = ResolvedOperations(upsert_operations=[ResolvedOperation(diff --git a/tests/session/test_memory_policy.py b/tests/session/test_memory_policy.pynew file mode 100644index 000000000..0a6271d89--- /dev/null+++ b/tests/session/test_memory_policy.py@@ -0,0 +1,37 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++from openviking.session.memory_policy import MemoryPolicy+++def test_memory_policy_defaults_to_self_only():+ policy = MemoryPolicy.from_dict(None)++ assert policy.self_enabled is True+ assert policy.peer_enabled is False+++def test_memory_policy_uses_enabled_switches_only():+ policy = MemoryPolicy.from_dict(+ {+ "self": {"enabled": False, "types": ["profile"]},+ "peer": {"enabled": True, "types": ["events"]},+ }+ )++ assert policy.self_enabled is False+ assert policy.peer_enabled is True+ assert policy.to_dict() == {+ "self": {"enabled": False},+ "peer": {"enabled": True},+ }+++def test_memory_policy_commit_replaces_session_policy():+ session_policy = {"peer": {"enabled": True, "types": ["profile"]}}+ commit_policy = {"self": {"enabled": False}, "peer": {"enabled": False}}++ policy = MemoryPolicy.merge(session_policy=session_policy, commit_policy=commit_policy)++ assert policy.self_enabled is False+ assert policy.peer_enabled is Falsediff --git a/tests/session/test_session_commit.py b/tests/session/test_session_commit.pyindex 1ea14ae0b..b6d664eca 100644--- a/tests/session/test_session_commit.py+++ b/tests/session/test_session_commit.py@@ -64,6 +64,7 @@ class TestCommit:):config = MagicMock()config.memory.extraction_enabled = False+ config.memory.agent_memory_enabled = Falseconfig.memory.session_skill_extraction_enabled = Truemonkeypatch.setattr("openviking.session.session.get_openviking_config", lambda: config)@@ -74,7 +75,7 @@ class TestCommit:session_with_messages._session_compressor.extract_agent_memories = AsyncMock(return_value={"contexts": [],- "session_skills": [{"uri": "viking://account/test/agent/skills/code-review"}],+ "session_skills": [{"uri": "viking://user/test/skills/code-review"}],})@@ -85,7 +86,7 @@ class TestCommit:assert task_result["result"]["memories_extracted"] == {}assert task_result["result"]["session_skills_extracted"] == 1assert task_result["result"]["session_skill_uris"] == [- "viking://account/test/agent/skills/code-review"+ "viking://user/test/skills/code-review"]session_with_messages._session_compressor.extract_long_term_memories.assert_not_awaited()session_with_messages._session_compressor.extract_agent_memories.assert_awaited_once()@@ -95,6 +96,7 @@ class TestCommit:):config = MagicMock()config.memory.extraction_enabled = True+ config.memory.agent_memory_enabled = Falseconfig.memory.session_skill_extraction_enabled = Falsemonkeypatch.setattr("openviking.session.session.get_openviking_config", lambda: config)@@ -113,7 +115,114 @@ class TestCommit:assert task_result["result"]["session_skills_extracted"] == 0assert task_result["result"]["session_skill_uris"] == []session_with_messages._session_compressor.extract_long_term_memories.assert_awaited_once()- session_with_messages._session_compressor.extract_agent_memories.assert_awaited_once()+ session_with_messages._session_compressor.extract_agent_memories.assert_not_awaited()++ async def test_commit_routes_peer_memory_with_single_full_context_pass(+ self,+ client: AsyncOpenViking,+ monkeypatch,+ ):+ """Peer memory uses one full-context extraction and operation-level routing."""+ config = MagicMock()+ config.memory.extraction_enabled = True+ config.memory.agent_memory_enabled = True+ config.memory.session_skill_extraction_enabled = True+ monkeypatch.setattr("openviking.session.session.get_openviking_config", lambda: config)++ session = client.session(session_id="peer_memory_role_routing_test")+ long_term_calls: list[dict] = []+ agent_calls: list[dict] = []++ async def fake_summary(messages, latest_archive_overview=""):+ del messages, latest_archive_overview+ return "Invoice support summary"++ async def fake_extract(+ *,+ messages,+ ctx,+ allowed_memory_types,+ allow_self_memory=True,+ allowed_peer_ids=None,+ **kwargs,+ ):+ del ctx, kwargs+ long_term_calls.append(+ {+ "allowed_memory_types": set(allowed_memory_types or set()),+ "allow_self_memory": allow_self_memory,+ "allowed_peer_ids": set(allowed_peer_ids or set()),+ "roles": [message.role for message in messages],+ "peer_ids": [message.peer_id for message in messages],+ }+ )+ return []++ async def fake_agent_extract(+ *,+ messages,+ allowed_memory_types,+ include_session_skills=None,+ **kwargs,+ ):+ del kwargs+ agent_calls.append(+ {+ "allowed_memory_types": set(allowed_memory_types or set()),+ "include_session_skills": include_session_skills,+ "roles": [message.role for message in messages],+ }+ )+ return {"contexts": [], "session_skills": []}++ monkeypatch.setattr(session, "_generate_archive_summary_async", fake_summary)+ monkeypatch.setattr(session._session_compressor, "extract_long_term_memories", fake_extract)+ monkeypatch.setattr(+ session._session_compressor, "extract_agent_memories", fake_agent_extract+ )++ session.add_message(+ "user",+ [TextPart("我是 Alice,后续发票问题请优先邮件联系我,邮箱是 [email protected]。")],+ peer_id="web:visitor:alice",+ )+ session.add_message(+ "assistant",+ [TextPart("收到,我会优先通过邮件联系你,并继续跟进发票问题。")],+ peer_id="web:visitor:alice",+ )++ result = await session.commit_async(+ memory_policy={+ "self": {"enabled": False},+ "peer": {"enabled": True, "types": ["profile"]},+ }+ )+ task_result = await _wait_for_task(result["task_id"])++ assert task_result["status"] == "completed"+ assert task_result["result"]["memories_extracted"] == {}+ assert long_term_calls == [+ {+ "allowed_memory_types": {+ "cases",+ "entities",+ "events",+ "identity",+ "patterns",+ "preferences",+ "profile",+ "skills",+ "soul",+ "tools",+ },+ "allow_self_memory": False,+ "allowed_peer_ids": {"web:visitor:alice"},+ "roles": ["user", "assistant"],+ "peer_ids": ["web:visitor:alice", "web:visitor:alice"],+ },+ ]+ assert agent_calls == []async def test_commit_archives_messages(self, session_with_messages: Session):"""Test commit archives messages"""@@ -189,12 +298,20 @@ class TestCommit:calls = []class _FakeClient:- async def commit_session(self, session_id, telemetry=False, *, keep_recent_count=0):+ async def commit_session(+ self,+ session_id,+ telemetry=False,+ *,+ keep_recent_count=0,+ memory_policy=None,+ ):calls.append({"session_id": session_id,"telemetry": telemetry,"keep_recent_count": keep_recent_count,+ "memory_policy": memory_policy,})return {"task_id": "task-1"}@@ -209,6 +326,7 @@ class TestCommit:"session_id": "s1","telemetry": True,"keep_recent_count": 0,+ "memory_policy": None,}]@@ -216,12 +334,20 @@ class TestCommit:calls = []class _FakeClient:- async def commit_session(self, session_id, telemetry=False, *, keep_recent_count=0):+ async def commit_session(+ self,+ session_id,+ telemetry=False,+ *,+ keep_recent_count=0,+ memory_policy=None,+ ):calls.append({"session_id": session_id,"telemetry": telemetry,"keep_recent_count": keep_recent_count,+ "memory_policy": memory_policy,})return {"task_id": "task-1"}@@ -236,6 +362,7 @@ class TestCommit:"session_id": "s1","telemetry": True,"keep_recent_count": 0,+ "memory_policy": None,}]diff --git a/tests/session/test_session_context.py b/tests/session/test_session_context.pyindex dd30f9498..4deb58e3b 100644--- a/tests/session/test_session_context.py+++ b/tests/session/test_session_context.py@@ -188,8 +188,12 @@ class TestGetContextForSearch:await _wait_for_task(result["task_id"])pending_messages = [- Message.create_user("Pending user message"),- Message.create_assistant("Pending assistant response"),+ Message(id="pending-user", role="user", parts=[TextPart("Pending user message")]),+ Message(+ id="pending-assistant",+ role="assistant",+ parts=[TextPart("Pending assistant response")],+ ),]await session._viking_fs.write_file(uri=f"{session.uri}/history/archive_002/messages.jsonl",@@ -217,8 +221,8 @@ class TestGetContextForSearch:await _wait_for_task(result["task_id"])pending_messages = [- Message.create_user("Pending 1"),- Message.create_assistant("Pending 2"),+ Message(id="pending-1", role="user", parts=[TextPart("Pending 1")]),+ Message(id="pending-2", role="assistant", parts=[TextPart("Pending 2")]),]await session._viking_fs.write_file(uri=f"{session.uri}/history/archive_002/messages.jsonl",diff --git a/tests/session/test_session_messages.py b/tests/session/test_session_messages.pyindex 6cd8000a9..5ab4880f9 100644--- a/tests/session/test_session_messages.py+++ b/tests/session/test_session_messages.py@@ -8,6 +8,7 @@ import pytestfrom openviking import AsyncOpenVikingfrom openviking.message import ContextPart, TextPart, ToolPartfrom openviking.session import Session+from openviking_cli.exceptions import InvalidArgumentErrorclass TestAddMessage:@@ -57,7 +58,7 @@ class TestAddMessage:tool_id="tool_123",tool_name="search_tool",tool_uri="viking://session/test/tools/tool_123",- skill_uri="viking://agent/skills/search",+ skill_uri="viking://user/skills/search",tool_input={"query": "test"},tool_status="running",)@@ -65,6 +66,26 @@ class TestAddMessage:assert len(msg.parts) == 2+ async def test_add_message_with_peer_id(self, session: Session):+ """Test peer_id is persisted on session messages."""+ msg = session.add_message(+ "user",+ [TextPart("Message from Alice")],+ peer_id="web:visitor:alice",+ )++ assert msg.peer_id == "web:visitor:alice"+ assert msg.to_dict()["peer_id"] == "web:visitor:alice"++ async def test_add_message_rejects_peer_id_with_path_separator(self, session: Session):+ """Test direct session usage validates peer_id path safety."""+ with pytest.raises(InvalidArgumentError):+ session.add_message(+ "user",+ [TextPart("Message from Alice")],+ peer_id="web/visitor/alice",+ )+async def test_messages_list_updated(self, session: Session):"""Test message list update"""initial_count = len(session.messages)@@ -74,7 +95,7 @@ class TestAddMessage:assert len(session.messages) == initial_count + 2- async def test_batch_add_messages_preserves_role_id_created_at_and_parts(+ async def test_batch_add_messages_preserves_peer_id_created_at_and_parts(self, client: AsyncOpenViking):session_id = "batch_message_preservation_test"@@ -85,7 +106,7 @@ class TestAddMessage:[{"role": "user",- "role_id": "user-123",+ "peer_id": "user-123","created_at": "2026-05-01T12:00:00Z","parts": [{"type": "text", "text": "Hello batch"},@@ -99,7 +120,7 @@ class TestAddMessage:},{"role": "assistant",- "role_id": "assistant-123",+ "peer_id": "assistant-123","created_at": "2026-05-01T12:00:05Z","parts": [{"type": "text", "text": "Executing tool"},@@ -108,7 +129,7 @@ class TestAddMessage:"tool_id": "tool_123","tool_name": "search_tool","tool_uri": f"viking://session/test/{session_id}/tools/tool_123",- "skill_uri": "viking://agent/skills/search",+ "skill_uri": "viking://user/skills/search","tool_status": "completed","tool_output": "Found a result",},@@ -121,7 +142,7 @@ class TestAddMessage:context = await client.get_session_context(session_id)assert [message["role"] for message in context["messages"]] == ["user", "assistant"]- assert context["messages"][0]["role_id"] == "user-123"+ assert context["messages"][0]["peer_id"] == "user-123"assert context["messages"][0]["created_at"] == "2026-05-01T12:00:00Z"assert context["messages"][0]["parts"][1] == {"type": "context",@@ -129,7 +150,7 @@ class TestAddMessage:"context_type": "resource","abstract": "Test document",}- assert context["messages"][1]["role_id"] == "assistant-123"+ assert context["messages"][1]["peer_id"] == "assistant-123"assert context["messages"][1]["created_at"] == "2026-05-01T12:00:05Z"assert context["messages"][1]["parts"][1]["type"] == "tool"assert context["messages"][1]["parts"][1]["tool_status"] == "completed"diff --git a/tests/session/test_session_usage.py b/tests/session/test_session_usage.pyindex b8a58fe89..d138b2f6b 100644--- a/tests/session/test_session_usage.py+++ b/tests/session/test_session_usage.py@@ -30,7 +30,7 @@ class TestUsed:"""Test recording used skill"""session.add_message("user", [TextPart("Test message")])- session.used(skill={"uri": "viking://agent/skills/search", "name": "search_skill"})+ session.used(skill={"uri": "viking://user/skills/search", "name": "search_skill"})assert len(session.usage_records) > 0@@ -40,7 +40,7 @@ class TestUsed:session.used(contexts=["viking://user/test/resources/doc.md"],- skill={"uri": "viking://agent/skills/analyze", "name": "analyze_skill"},+ skill={"uri": "viking://user/skills/analyze", "name": "analyze_skill"},)assert len(session.usage_records) > 0diff --git a/tests/session/test_tool_result_externalization.py b/tests/session/test_tool_result_externalization.pyindex d9c51c74f..e58b6bee1 100644--- a/tests/session/test_tool_result_externalization.py+++ b/tests/session/test_tool_result_externalization.py@@ -7,7 +7,7 @@ import pytestimport openviking.session.session as session_moduleimport openviking.session.tool_result_store as tool_result_store-from openviking.message import Message, ToolPart+from openviking.message import ToolPartfrom openviking.server.config import ToolOutputExternalizationConfigfrom openviking.session import Sessionfrom openviking.session.tool_result_store import ToolResultStore@@ -97,6 +97,7 @@ async def test_add_message_externalizes_large_tool_output(session: Session):tool_status="completed",)],+ peer_id="web:visitor:alice",)part = msg.get_tool_parts()[0]@@ -109,6 +110,8 @@ async def test_add_message_externalizes_large_tool_output(session: Session):stored = await session.read_tool_result(part.tool_output_ref.rsplit("/", 1)[-1], limit=-1)assert stored["content"] == rawassert stored["offset_unit"] == "unicode_code_point"+ assert stored["metadata"]["user_id"] == session.ctx.user.user_id+ assert stored["metadata"]["peer_id"] == "web:visitor:alice"async def test_hydrate_tool_outputs_for_extraction_uses_memory_copy(session: Session):diff --git a/tests/storage/test_embedding_msg.py b/tests/storage/test_embedding_msg.pyindex 775256a07..da2c9176f 100644--- a/tests/storage/test_embedding_msg.py+++ b/tests/storage/test_embedding_msg.py@@ -15,7 +15,7 @@ def test_embedding_msg_roundtrip_preserves_id_for_request_wait_tracker():try:msg = EmbeddingMsg("hello",- {"uri": "viking://agent/skills/demo"},+ {"uri": "viking://user/default/skills/demo"},telemetry_id=telemetry_id,)tracker.register_embedding_root(telemetry_id, msg.id)diff --git a/tests/storage/test_embedding_msg_converter_tenant.py b/tests/storage/test_embedding_msg_converter_tenant.pyindex d3effdf94..558ddc68d 100644--- a/tests/storage/test_embedding_msg_converter_tenant.py+++ b/tests/storage/test_embedding_msg_converter_tenant.py@@ -11,38 +11,29 @@ from openviking_cli.session.user_id import UserIdentifier@pytest.mark.parametrize(- ("uri", "expected_uri", "expected_owner_user_id", "expected_owner_agent_id"),+ ("uri", "expected_uri", "expected_owner_user_id"),[("viking://user/memories/preferences/me.md",lambda user: f"viking://user/{user.user_id}/memories/preferences/me.md",lambda user: user.user_id,- None,- ),- (- "viking://agent/memories/cases/me.md",- lambda user: f"viking://agent/{user.agent_id}/memories/cases/me.md",- None,- lambda user: user.agent_id,),("viking://resources/doc.md","viking://resources/doc.md",None,- None,),],)def test_embedding_msg_converter_backfills_account_and_owner_fields(- uri, expected_uri, expected_owner_user_id, expected_owner_agent_id+ uri, expected_uri, expected_owner_user_id):- user = UserIdentifier("acme", "alice", "helper")+ user = UserIdentifier("acme", "alice")context = Context(uri=uri, abstract="hello", user=user)# Simulate legacy producer that forgot tenant fields.context.account_id = ""context.owner_user_id = None- context.owner_agent_id = Nonemsg = EmbeddingMsgConverter.from_context(context)@@ -53,10 +44,4 @@ def test_embedding_msg_converter_backfills_account_and_owner_fields(expected_user = (expected_owner_user_id(user) if callable(expected_owner_user_id) else expected_owner_user_id)- expected_agent = (- expected_owner_agent_id(user)- if callable(expected_owner_agent_id)- else expected_owner_agent_id- )assert msg.context_data["owner_user_id"] == expected_user- assert msg.context_data["owner_agent_id"] == expected_agentdiff --git a/tests/storage/test_memory_semantic_stall.py b/tests/storage/test_memory_semantic_stall.pyindex 502b086e2..ef6f58e92 100644--- a/tests/storage/test_memory_semantic_stall.py+++ b/tests/storage/test_memory_semantic_stall.py@@ -15,6 +15,17 @@ from openviking.storage.queuefs.semantic_msg import SemanticMsgfrom openviking.storage.queuefs.semantic_processor import SemanticProcessor+class _NoopLockContext:+ def __init__(self, *args, **kwargs):+ pass++ async def __aenter__(self):+ return self++ async def __aexit__(self, exc_type, exc, tb):+ return False++def _make_msg(uri="viking://user/memories", context_type="memory", **kwargs):"""Build a minimal SemanticMsg for testing."""defaults = {@@ -25,7 +36,7 @@ def _make_msg(uri="viking://user/memories", context_type="memory", **kwargs):"role": "root","account_id": "acc1","user_id": "usr1",- "agent_id": "test-agent",+ "peer_id": "test-peer","telemetry_id": "","target_uri": "","changes": None,@@ -198,6 +209,9 @@ async def test_memory_write_error_reports_error():fake_fs.ls = AsyncMock(return_value=[{"name": "file1.md", "isDir": False}])fake_fs.read_file = AsyncMock(return_value="some content")fake_fs.write_file = AsyncMock(side_effect=PermissionError("Permission denied"))+ fake_fs._uri_to_path = MagicMock(+ side_effect=lambda uri, ctx=None: f"/local/acc1/{uri.removeprefix('viking://')}"+ )msg = _make_msg()data = _build_data(msg)@@ -227,6 +241,7 @@ async def test_memory_write_error_reports_error():"openviking.storage.queuefs.semantic_processor.resolve_telemetry",return_value=None,),+ patch("openviking.storage.transaction.LockContext", _NoopLockContext),patch.object(processor,"_generate_single_file_summary",diff --git a/tests/storage/test_semantic_dag_incremental.py b/tests/storage/test_semantic_dag_incremental.pyindex 628e78156..ee45577c1 100644--- a/tests/storage/test_semantic_dag_incremental.py+++ b/tests/storage/test_semantic_dag_incremental.py@@ -135,7 +135,7 @@ async def test_direct_incremental_update_uses_changes_without_temp_sync(monkeypamonkeypatch.setattr("openviking.storage.queuefs.semantic_dag.get_viking_fs", lambda: fake_fs)processor = _FakeProcessor(fake_fs)- ctx = RequestContext(user=UserIdentifier("acc1", "user1", "agent1"), role=Role.USER)+ ctx = RequestContext(user=UserIdentifier("acc1", "user1"), role=Role.USER)executor = SemanticDagExecutor(processor=processor,context_type="resource",diff --git a/tests/storage/test_semantic_dag_skip_files.py b/tests/storage/test_semantic_dag_skip_files.pyindex 8be58a640..7f2fd155e 100644--- a/tests/storage/test_semantic_dag_skip_files.py+++ b/tests/storage/test_semantic_dag_skip_files.py@@ -106,7 +106,7 @@ async def test_messages_jsonl_excluded_from_summary(monkeypatch):)processor = _FakeProcessor()- ctx = RequestContext(user=UserIdentifier("acc1", "user1", "agent1"), role=Role.USER)+ ctx = RequestContext(user=UserIdentifier("acc1", "user1"), role=Role.USER)executor = SemanticDagExecutor(processor=processor,context_type="session",@@ -143,7 +143,7 @@ async def test_messages_jsonl_excluded_in_subdirectory(monkeypatch):)processor = _FakeProcessor()- ctx = RequestContext(user=UserIdentifier("acc1", "user1", "agent1"), role=Role.USER)+ ctx = RequestContext(user=UserIdentifier("acc1", "user1"), role=Role.USER)executor = SemanticDagExecutor(processor=processor,context_type="session",diff --git a/tests/storage/test_semantic_dag_stats.py b/tests/storage/test_semantic_dag_stats.pyindex ff6ad534a..19e3974cc 100644--- a/tests/storage/test_semantic_dag_stats.py+++ b/tests/storage/test_semantic_dag_stats.py@@ -125,7 +125,7 @@ async def test_semantic_dag_stats_collects_nodes(monkeypatch):)processor = _FakeProcessor()- ctx = RequestContext(user=UserIdentifier("acc1", "user1", "agent1"), role=Role.USER)+ ctx = RequestContext(user=UserIdentifier("acc1", "user1"), role=Role.USER)executor = SemanticDagExecutor(processor=processor,context_type="resource",@@ -161,7 +161,7 @@ async def test_semantic_dag_bounds_active_node_work(monkeypatch):)processor = _TrackingProcessor()- ctx = RequestContext(user=UserIdentifier("acc1", "user1", "agent1"), role=Role.USER)+ ctx = RequestContext(user=UserIdentifier("acc1", "user1"), role=Role.USER)executor = SemanticDagExecutor(processor=processor,context_type="resource",@@ -202,7 +202,7 @@ async def test_semantic_dag_shares_node_scheduler_across_roots(monkeypatch):)processor = _TrackingProcessor()- ctx = RequestContext(user=UserIdentifier("acc1", "user1", "agent1"), role=Role.USER)+ ctx = RequestContext(user=UserIdentifier("acc1", "user1"), role=Role.USER)executor_a = SemanticDagExecutor(processor=processor,context_type="resource",@@ -260,7 +260,7 @@ async def test_semantic_dag_skip_vectorization_does_not_schedule_tasks(monkeypat)processor = _FakeProcessor()- ctx = RequestContext(user=UserIdentifier("acc1", "user1", "agent1"), role=Role.USER)+ ctx = RequestContext(user=UserIdentifier("acc1", "user1"), role=Role.USER)executor = SemanticDagExecutor(processor=processor,context_type="resource",diff --git a/tests/storage/test_semantic_processor_mv_vector_store.py b/tests/storage/test_semantic_processor_mv_vector_store.pyindex a7bab1c68..8ba7fad24 100644--- a/tests/storage/test_semantic_processor_mv_vector_store.py+++ b/tests/storage/test_semantic_processor_mv_vector_store.py@@ -125,7 +125,7 @@ class _NoopLockContext:async def test_mv_vector_store_moves_records(monkeypatch):from openviking.storage.viking_fs import VikingFS- ctx = RequestContext(user=UserIdentifier("acc", "user", "agent"), role=Role.ROOT)+ ctx = RequestContext(user=UserIdentifier("acc", "user"), role=Role.ROOT)old_uri = "viking://resources/a"new_uri = "viking://resources/b"@@ -200,7 +200,7 @@ async def test_mv_vector_store_moves_records(monkeypatch):async def test_mv_vector_store_requires_directories(monkeypatch):from openviking.storage.viking_fs import VikingFS- ctx = RequestContext(user=UserIdentifier("acc", "user", "agent"), role=Role.ROOT)+ ctx = RequestContext(user=UserIdentifier("acc", "user"), role=Role.ROOT)old_uri = "viking://resources/a"new_uri = "viking://resources/b"diff --git a/tests/storage/test_semantic_queue_memory_dedupe.py b/tests/storage/test_semantic_queue_memory_dedupe.pyindex caa584e18..cebfba885 100644--- a/tests/storage/test_semantic_queue_memory_dedupe.py+++ b/tests/storage/test_semantic_queue_memory_dedupe.py@@ -24,7 +24,7 @@ async def test_memory_semantic_enqueue_deduped_within_window():context_type="memory",account_id="acc",user_id="u1",- agent_id="a1",+ peer_id="p1",)r1 = await q.enqueue(msg)r2 = await q.enqueue(@@ -33,7 +33,7 @@ async def test_memory_semantic_enqueue_deduped_within_window():context_type="memory",account_id="acc",user_id="u1",- agent_id="a1",+ peer_id="p1",))assert r1 == "queued-id"@@ -80,7 +80,7 @@ async def test_coalesced_semantic_messages_mark_old_version_stale():with patch.object(NamedQueue, "enqueue", new_callable=AsyncMock) as named_enqueue:named_enqueue.return_value = "queued-id"q = SemanticQueue(mock_agfs, "/queue", "semantic")- coalesce_key = f"resource|acc|u|a|viking://resources/docs/{uuid4().hex}"+ coalesce_key = f"resource|acc|u|p|viking://resources/docs/{uuid4().hex}"first = SemanticMsg(uri="viking://resources/docs",context_type="resource",@@ -158,7 +158,7 @@ async def test_stale_memory_semantic_write_is_skipped(monkeypatch):lock_manager = _FakeLockManager()viking_fs = _FakeVikingFS()processor = SemanticProcessor()- coalesce_key = f"memory|acc|u|a|viking://user/default/memories/preferences/{uuid4().hex}"+ coalesce_key = f"memory|acc|u|p|viking://user/default/memories/preferences/{uuid4().hex}"with patch.object(NamedQueue, "enqueue", new_callable=AsyncMock):q = SemanticQueue(MagicMock(), "/queue", "semantic")diff --git a/tests/test_config_loader.py b/tests/test_config_loader.pyindex 050723ca8..bbb6b9a3a 100644--- a/tests/test_config_loader.py+++ b/tests/test_config_loader.py@@ -171,7 +171,7 @@ def test_openviking_config_rejects_unknown_top_level_section_with_suggestion(monOpenVikingConfigSingleton.reset_instance()-def test_openviking_config_warns_when_agent_scope_mode_is_configured(monkeypatch, caplog):+def test_openviking_config_rejects_unknown_memory_field(monkeypatch):monkeypatch.setenv("OPENVIKING_CONFIG_FILE", "/tmp/codex-no-config.json")from openviking_cli.utils.config.open_viking_config import (@@ -179,11 +179,8 @@ def test_openviking_config_warns_when_agent_scope_mode_is_configured(monkeypatchOpenVikingConfigSingleton,)- with caplog.at_level("WARNING"):- config = OpenVikingConfig.from_dict({"memory": {"agent_scope_mode": "agent"}})-- assert config.memory.agent_scope_mode == "agent"- assert "memory.agent_scope_mode is deprecated and ignored" in caplog.text+ with pytest.raises(ValueError, match="Unknown config field 'memory.unknown_memory_field'"):+ OpenVikingConfig.from_dict({"memory": {"unknown_memory_field": "value"}})OpenVikingConfigSingleton.reset_instance()@@ -202,21 +199,6 @@ def test_openviking_config_rejects_memory_v1(monkeypatch):OpenVikingConfigSingleton.reset_instance()-def test_openviking_config_accepts_role_id_memory_isolation_enabled(monkeypatch):- monkeypatch.setenv(OPENVIKING_CONFIG_ENV, "/tmp/codex-no-config.json")-- from openviking_cli.utils.config.open_viking_config import (- OpenVikingConfig,- OpenVikingConfigSingleton,- )-- config = OpenVikingConfig.from_dict({"memory": {"role_id_memory_isolation_enabled": True}})-- assert config.memory.role_id_memory_isolation_enabled is True-- OpenVikingConfigSingleton.reset_instance()--def test_openviking_config_memory_experimental_switch_defaults_agent_memory(monkeypatch):monkeypatch.setenv(OPENVIKING_CONFIG_ENV, "/tmp/codex-no-config.json")diff --git a/tests/test_link_renderer.py b/tests/test_link_renderer.pyindex 60874d7b7..e4c03c737 100644--- a/tests/test_link_renderer.py+++ b/tests/test_link_renderer.py@@ -1,5 +1,3 @@-import pytest-from openviking.session.memory.dataclass import MemoryFilefrom openviking.session.memory.utils.link_renderer import LinkRendererfrom openviking.session.memory.utils.memory_file_utils import MemoryFileUtils@@ -37,7 +35,7 @@ class TestRelativePath:def test_cross_scope_returns_none(self):result = LinkRenderer.relative_path("viking://user/Caroline/memories/profile.md",- "viking://agent/Bot/memories/skills/pdf.md",+ "viking://resources/skills/pdf.md",)assert result is None@@ -232,7 +230,7 @@ class TestRenderLinks:links = [{"from_uri": "viking://user/Caroline/memories/profile.md",- "to_uri": "viking://agent/Bot/memories/skills/research.md",+ "to_uri": "viking://resources/skills/research.md","weight": 1.0,"match_text": "skill",}@@ -242,7 +240,7 @@ class TestRenderLinks:"viking://user/Caroline/memories/profile.md",links,)- assert "viking://agent/Bot/memories/skills/research.md" in result+ assert "viking://resources/skills/research.md" in resultdef test_weight_priority(self):content = "She loves painting and painting is fun."@@ -292,10 +290,7 @@ class TestRenderLinks:"viking://user/Caroline/memories/profile.md",links,)- assert (- result- == "她喜欢[角色扮演游戏](entities/games/rpg.md),也喜欢开放世界游戏。"- )+ assert result == "她喜欢[角色扮演游戏](entities/games/rpg.md),也喜欢开放世界游戏。"class TestStripLinks:@@ -310,12 +305,12 @@ class TestStripLinks:assert result == contentdef test_keep_viking_uri_link(self):- content = "Check [skill](viking://agent/Bot/memories/skills/research.md)."+ content = "Check [skill](viking://user/Bot/skills/research.md)."result = LinkRenderer.strip_links(content)assert result == contentdef test_keep_viking_uri_link_when_target_uses_supported_scheme(self):- content = "Check [skill](viking://agent/Bot/memories/skills/research.md)."+ content = "Check [skill](viking://user/Bot/skills/research.md)."result = LinkRenderer.strip_links(content)assert result == content@@ -437,5 +432,8 @@ class TestRoundTrip:second_write = MemoryFileUtils.write(reparsed)assert "[Gina](events/2023/02/08/Gina与Jon的日常交流.md)" not in first_write- assert "[[Gina](events/2023/02/08/Gina与Jon的日常交流.md)](events/2023/02/08/Gina与Jon的日常交流.md)" not in second_write+ assert (+ "[[Gina](events/2023/02/08/Gina与Jon的日常交流.md)](events/2023/02/08/Gina与Jon的日常交流.md)"+ not in second_write+ )assert "Gina" in second_writediff --git a/tests/test_task_tracker.py b/tests/test_task_tracker.pyindex 37b4971fb..d418961cf 100644--- a/tests/test_task_tracker.py+++ b/tests/test_task_tracker.py@@ -47,7 +47,7 @@ def _owner_kwargs(account_id: str = "acme", user_id: str = "alice"):def _make_ctx(account_id: str = "acme", user_id: str = "alice") -> RequestContext:return RequestContext(- user=UserIdentifier(account_id, user_id, "agent-1"),+ user=UserIdentifier(account_id, user_id),role=Role.ADMIN,)diff --git a/tests/test_token_estimation.py b/tests/test_token_estimation.pyindex baf6f2f7f..82fba2e67 100644--- a/tests/test_token_estimation.py+++ b/tests/test_token_estimation.py@@ -3,13 +3,13 @@"""Shared token estimation tests."""-from openviking.message import Message+from openviking.message import Message, TextPartfrom openviking.session import Sessiondef test_message_estimated_tokens_is_cjk_aware():"""Chinese text should not be estimated with the ASCII chars/4 fallback."""- msg = Message.create_user("\u4f60\u597d\u4e16\u754c")+ msg = Message(id="msg-cjk", role="user", parts=[TextPart("\u4f60\u597d\u4e16\u754c")])assert msg.estimated_tokens == 6diff --git a/tests/unit/session/memory/test_extract_loop_match_text.py b/tests/unit/session/memory/test_extract_loop_match_text.pyindex 771d878fb..c88264cf8 100644--- a/tests/unit/session/memory/test_extract_loop_match_text.py+++ b/tests/unit/session/memory/test_extract_loop_match_text.py@@ -6,18 +6,22 @@ from unittest.mock import AsyncMock, Mock, patchimport pytest-from openviking.session.memory.dataclass import MemoryField, MemoryFile, MemoryTypeSchema, ResolvedOperation, WikiLink+from openviking.session.memory.dataclass import (+ MemoryField,+ MemoryFile,+ MemoryTypeSchema,+ ResolvedOperation,+ WikiLink,+)+from openviking.session.memory.extract_loop import ExtractLoopfrom openviking.session.memory.merge_op import FieldType, MergeOpfrom openviking.session.memory.page_id_map import PageIdMap-from openviking.session.memory.extract_loop import ExtractLoopclass AttrDict(dict):__getattr__ = dict.get--class TestResolveOperations:@pytest.mark.asyncioasync def test_existing_page_id_keeps_existing_uri_and_identity_fields(self):@@ -46,7 +50,7 @@ class TestResolveOperations:isolation_handler = Mock()isolation_handler.get_read_scope.return_value = None- isolation_handler.fill_role_ids.side_effect = lambda item, role_scope=None: item+ isolation_handler.fill_identity_fields.side_effect = lambda item, role_scope=None: itemloop = ExtractLoop(vlm=Mock(model="test-model"),@@ -77,25 +81,26 @@ class TestResolveOperations:loop._extract_context = Mock()loop._extract_context.page_id_map = Mock()loop._extract_context.page_id_map._id_to_uri = {- 100: "viking://agent/agent_sample_0/memories/trajectories/a.md"+ 100: "viking://user/user_sample_0/memories/trajectories/a.md"}loop._extract_context.page_id_map.resolve.side_effect = lambda page_id: {- 100: "viking://agent/agent_sample_0/memories/trajectories/a.md"+ 100: "viking://user/user_sample_0/memories/trajectories/a.md"}.get(page_id)loop._extract_context.page_id_map.register_new_page_id = Mock()raw_links = [WikiLink(f=100, t=102, match_text="trip")]- with patch("openviking.session.memory.extract_loop.tracer.info") as mock_info, patch(- "openviking.session.memory.extract_loop.tracer.error"- ) as mock_error:+ with (+ patch("openviking.session.memory.extract_loop.tracer.info") as mock_info,+ patch("openviking.session.memory.extract_loop.tracer.error") as mock_error,+ ):resolved = loop._resolve_links(raw_links, upsert_operations=[])assert resolved == []mock_error.assert_not_called()mock_info.assert_any_call("Skipping link with unresolved page_ids: f=100, t=102, "- "from_uri=viking://agent/agent_sample_0/memories/trajectories/a.md, to_uri=None, "+ "from_uri=viking://user/user_sample_0/memories/trajectories/a.md, to_uri=None, ""op_page_map_keys=[]")@@ -149,7 +154,9 @@ class TestPageIdInstruction:@pytest.mark.asyncioasync def test_run_always_includes_page_id_rules_when_links_disabled(self):context_provider = Mock()- context_provider.get_memory_schemas.return_value = [SimpleNamespace(memory_type="experiences")]+ context_provider.get_memory_schemas.return_value = [+ SimpleNamespace(memory_type="experiences")+ ]context_provider.get_output_language.return_value = "zh-CN"context_provider.get_tools.return_value = []extract_context = Mock()@@ -162,7 +169,7 @@ class TestPageIdInstruction:isolation_handler = Mock()isolation_handler.get_read_scope.return_value = None- isolation_handler.fill_role_ids.side_effect = lambda item, role_scope=None: item+ isolation_handler.fill_identity_fields.side_effect = lambda item, role_scope=None: itemisolation_handler.calculate_memory_uris.return_value = ["viking://user/alice/memories/experiences/chat.md"]@@ -209,9 +216,15 @@ class TestPageIdInstruction:assert "## Page ID Rules" in system_contentassert "## Read Format Rules" in system_contentassert 'Every memory item you create or edit MUST include "page_id".' in system_content- assert "The read tool accepts `uri`, optional `offset` (0-indexed), and optional `limit`." in system_content+ assert (+ "The read tool accepts `uri`, optional `offset` (0-indexed), and optional `limit`."+ in system_content+ )assert "each visible line is prefixed with `line_number<TAB>`" in system_content- assert "Never include the line-number prefix itself in `search` or `replace`." in system_content+ assert (+ "Never include the line-number prefix itself in `search` or `replace`."+ in system_content+ )assert "For existing items, use the page_id shown in read/search results." in system_contentassert "For new items, assign a unique page_id >= 100." in system_contentassert "When editing an existing item, reuse its existing page_id." in system_content@@ -220,7 +233,9 @@ class TestPageIdInstruction:@pytest.mark.asyncioasync def test_run_includes_link_page_id_rule_when_links_enabled(self):context_provider = Mock()- context_provider.get_memory_schemas.return_value = [SimpleNamespace(memory_type="experiences")]+ context_provider.get_memory_schemas.return_value = [+ SimpleNamespace(memory_type="experiences")+ ]context_provider.get_output_language.return_value = "zh-CN"context_provider.get_tools.return_value = []extract_context = Mock()@@ -233,7 +248,7 @@ class TestPageIdInstruction:isolation_handler = Mock()isolation_handler.get_read_scope.return_value = None- isolation_handler.fill_role_ids.side_effect = lambda item, role_scope=None: item+ isolation_handler.fill_identity_fields.side_effect = lambda item, role_scope=None: itemisolation_handler.calculate_memory_uris.return_value = ["viking://user/alice/memories/experiences/chat.md"]@@ -289,7 +304,9 @@ class TestPageIdInstruction:class TestFinalOperationsHydration:@pytest.mark.asyncioasync def test_run_logs_final_operations_after_old_memory_file_is_hydrated(self):- old_file = MemoryFile(uri="viking://user/Caroline/memories/experiences/chat.md", content="old")+ old_file = MemoryFile(+ uri="viking://user/Caroline/memories/experiences/chat.md", content="old"+ )context_provider = Mock()schema = SimpleNamespace(memory_type="experiences", fields=[])@@ -307,7 +324,7 @@ class TestFinalOperationsHydration:isolation_handler = Mock()isolation_handler.get_read_scope.return_value = "user://Caroline"- isolation_handler.fill_role_ids.side_effect = lambda item, role_scope=None: item+ isolation_handler.fill_identity_fields.side_effect = lambda item, role_scope=None: itemloop = ExtractLoop(vlm=Mock(model="test-model"),@@ -349,5 +366,7 @@ class TestFinalOperationsHydration:assert op.old_memory_file_content is old_fileassert final_operations.resolved_links == []logged_messages = [call.args[0] for call in mock_tracer_info.call_args_list]- final_log = next(message for message in logged_messages if message.startswith("final_operations="))+ final_log = next(+ message for message in logged_messages if message.startswith("final_operations=")+ )assert '"old_memory_file_content":null' not in final_logdiff --git a/tests/unit/test_context.py b/tests/unit/test_context.pyindex f70e68350..8734b3ef3 100644--- a/tests/unit/test_context.py+++ b/tests/unit/test_context.py@@ -175,7 +175,7 @@ class TestContextContextType:def test_derive_skill(self):"""Test deriving skill type from URI."""- ctx = Context(uri="viking://agent/test/skills/my-skill/")+ ctx = Context(uri="viking://user/test/skills/my-skill/")assert ctx.context_type == "skill"@@ -408,7 +408,6 @@ class TestContextFromDict:"user": {"account_id": "account-123","user_id": "user-123",- "agent_id": "agent-456",},}@@ -477,45 +476,33 @@ class TestContextWithUser:def test_user_account_id_inheritance(self):"""Test account_id inherited from user."""- user = UserIdentifier(account_id="account-123", user_id="user-123", agent_id="agent-456")+ user = UserIdentifier(account_id="account-123", user_id="user-123")ctx = Context(uri="viking://test/", user=user)assert ctx.account_id == user.account_id- def test_owner_fields_agent(self):- """Test owner fields for canonical agent URI."""- user = UserIdentifier(account_id="account-123", user_id="user-123", agent_id="agent-456")- ctx = Context(uri="viking://agent/test/skills/my-skill/", user=user)-- assert ctx.owner_user_id is None- assert ctx.owner_agent_id == "test"- assert ctx.owner_space == user.agent_id-def test_owner_fields_user(self):"""Test owner fields for canonical user URI."""- user = UserIdentifier(account_id="account-123", user_id="user-123", agent_id="agent-456")+ user = UserIdentifier(account_id="account-123", user_id="user-123")ctx = Context(uri="viking://user/test/memories/test.md", user=user)assert ctx.owner_user_id == "test"- assert ctx.owner_agent_id is Noneassert ctx.owner_space == user.user_iddef test_owner_fields_session(self):"""Test owner fields for session URI."""- user = UserIdentifier(account_id="account-123", user_id="user-123", agent_id="agent-456")+ user = UserIdentifier(account_id="account-123", user_id="user-123")ctx = Context(uri="viking://session/test/msg/1.md", user=user)assert ctx.owner_user_id is None- assert ctx.owner_agent_id is Noneassert ctx.owner_space == user.user_iddef test_owner_fields_resource_default(self):"""Test owner fields default for resource URI."""- user = UserIdentifier(account_id="account-123", user_id="user-123", agent_id="agent-456")+ user = UserIdentifier(account_id="account-123", user_id="user-123")ctx = Context(uri="viking://resources/docs/test.md", user=user)assert ctx.owner_user_id is None- assert ctx.owner_agent_id is Noneassert ctx.owner_space == ""diff --git a/tests/unit/test_langchain_integration.py b/tests/unit/test_langchain_integration.pyindex 382062db0..6b186f163 100644--- a/tests/unit/test_langchain_integration.py+++ b/tests/unit/test_langchain_integration.py@@ -83,6 +83,21 @@ def test_retriever_returns_langchain_documents():assert all(doc.page_content for doc in docs)+def test_retriever_passes_peer_id_to_retrieval():+ client = InMemoryOpenVikingClient(+ {"viking://user/memories/preferences.md": "The peer prefers azure deploys."}+ )+ retriever = OpenVikingRetriever(+ client=client,+ target_uri="viking://user/memories",+ peer_id="peer-1",+ )++ retriever.invoke("azure")++ assert client.find_calls[-1]["peer_id"] == "peer-1"++def test_create_openviking_tools_exposes_common_viking_primitives():client = InMemoryOpenVikingClient({"viking://user/memories/profile.md": "The user likes LangGraph agents."}@@ -137,6 +152,33 @@ def test_create_openviking_tools_exposes_common_viking_primitives():assert "VikingDB is internal vector/index storage" in health+def test_create_openviking_tools_passes_peer_id_without_exposing_tool_arg():+ client = InMemoryOpenVikingClient(+ {"viking://user/memories/profile.md": "The peer likes LangGraph agents."}+ )+ tools = {+ tool.name: tool for tool in create_openviking_tools(client=client, peer_id="peer-tools")+ }++ assert "peer_id" not in _tool_schema(tools["viking_find"]).get("properties", {})++ tools["viking_find"].invoke({"query": "LangGraph"})+ tools["viking_search"].invoke({"query": "LangGraph", "session_id": "tool-session"})+ tools["viking_store"].invoke(+ {+ "messages": [{"role": "user", "content": "Remember peer tools."}],+ "commit": False,+ }+ )++ assert client.find_calls[-1]["peer_id"] == "peer-tools"+ assert client.search_calls[-1]["peer_id"] == "peer-tools"+ assert any(+ messages and messages[0].get("peer_id") == "peer-tools"+ for messages in client.sessions.values()+ )++def test_create_openviking_tools_profiles_control_destructive_tools():client = InMemoryOpenVikingClient()@@ -308,7 +350,6 @@ def test_ensure_client_defaults_to_http_client(monkeypatch):OpenVikingConnection(api_key="test-key",user_id="test-user",- agent_id="test-agent",))@@ -316,7 +357,6 @@ def test_ensure_client_defaults_to_http_client(monkeypatch):assert isinstance(client.get(), FakeHTTPClient)assert created["api_key"] == "test-key"assert created["user_id"] == "test-user"- assert created["agent_id"] == "test-agent"assert created["url"] is None@@ -498,7 +538,7 @@ def test_in_memory_openviking_client_batch_add_messages_records_messages():{"role": "assistant","parts": [{"type": "text", "text": "hi"}],- "role_id": "agent-1",+ "peer_id": "agent-1","created_at": "2026-05-26T00:00:00+00:00",},],@@ -511,7 +551,7 @@ def test_in_memory_openviking_client_batch_add_messages_records_messages():]assert client.sessions["batch-session"][0]["parts"][0]["text"] == "hello"assert client.sessions["batch-session"][1]["parts"][0]["text"] == "hi"- assert client.sessions["batch-session"][1]["role_id"] == "agent-1"+ assert client.sessions["batch-session"][1]["peer_id"] == "agent-1"assert client.sessions["batch-session"][1]["created_at"] == "2026-05-26T00:00:00+00:00"@@ -552,6 +592,27 @@ def test_chat_message_history_preserves_tool_parts():assert len(restored_tool_messages) == 1+def test_chat_message_history_writes_peer_id_to_messages():+ client = InMemoryOpenVikingClient()+ history = OpenVikingChatMessageHistory(+ session_id="peer-history-session",+ client=client,+ peer_id="peer-history",+ )++ history.add_messages(+ [+ HumanMessage(content="Remember peer history."),+ AIMessage(content="Stored."),+ ]+ )++ assert [message.get("peer_id") for message in client.sessions["peer-history-session"]] == [+ "peer-history",+ "peer-history",+ ]++def test_openviking_tool_result_restores_without_duplicate_ai_tool_call():restored = openviking_message_to_langchain({@@ -612,6 +673,21 @@ def test_session_context_assembler_uses_archive_active_messages_and_recall():assert assembled.context_parts[0]["type"] == "context"+def test_session_context_assembler_passes_peer_id_to_recall():+ client = InMemoryOpenVikingClient(+ {"viking://user/memories/peer.md": "Peer memory mentions azure."}+ )+ assembler = OpenVikingSessionContextAssembler(+ client=client,+ target_uri="viking://user/memories",+ peer_id="peer-assembler",+ )++ assembler.assemble(session_id="assembler-peer-session", query="azure")++ assert client.search_calls[-1]["peer_id"] == "peer-assembler"++def test_with_openviking_context_wraps_runnable_with_history():client = InMemoryOpenVikingClient({"viking://resources/runbooks/deploy.md": "Azure is the deployment color."}@@ -694,6 +770,31 @@ def test_with_openviking_context_dynamic_session_can_use_thread_id_key():assert len(client.sessions["thread-session"]) == 2+def test_with_openviking_context_dynamic_peer_uses_config_for_recall_and_history():+ client = InMemoryOpenVikingClient(+ {"viking://resources/runbooks/deploy.md": "Thread peer dynamic context."}+ )+ runnable = with_openviking_context(+ RunnableLambda(lambda _messages: AIMessage(content="peer ok")),+ client=client,+ target_uri="viking://resources",+ session_id_config_key="thread_id",+ )++ result = runnable.invoke(+ [HumanMessage(content="What peer context?")],+ config={"configurable": {"thread_id": "thread-peer-session", "peer_id": "peer-dynamic"}},+ )++ assert result.content == "peer ok"+ assert client.search_calls[-1]["session_id"] == "thread-peer-session"+ assert client.search_calls[-1]["peer_id"] == "peer-dynamic"+ assert [message.get("peer_id") for message in client.sessions["thread-peer-session"]] == [+ "peer-dynamic",+ "peer-dynamic",+ ]++def test_with_openviking_context_clears_pending_context_after_failure():client = InMemoryOpenVikingClient({"viking://resources/runbooks/deploy.md": "Azure failure context."}@@ -913,6 +1014,16 @@ def test_langgraph_store_round_trip_and_semantic_search():assert store.list_namespaces(prefix=("users",)) == [("users", "ada")]+def test_langgraph_store_semantic_search_passes_peer_id():+ client = InMemoryOpenVikingClient()+ store = OpenVikingStore(client=client, peer_id="peer-store")++ store.put(("users",), "ada", {"color": "azure"})+ store.search(("users",), query="azure", limit=5)++ assert client.find_calls[-1]["peer_id"] == "peer-store"++def test_langgraph_store_rejects_ttl_writes():store = OpenVikingStore(client=InMemoryOpenVikingClient())@@ -944,33 +1055,9 @@ def test_langgraph_store_batch_rejects_ttl_writes():"viking://user/memories","viking://user/default/memories",),- (- "viking://user/memories/langgraph_store",- "viking://user/memories",- "viking://user/default/agent/support/memories",- ),- (- "viking://agent/memories/langgraph_store",- "viking://agent/memories",- "viking://agent/support/memories",- ),- (- "viking://agent/memories/langgraph_store",- "viking://agent/memories",- "viking://agent/support/user/default/memories",- ),- (- "viking://agent/skills/langgraph_store",- "viking://agent/skills",- "viking://agent/support/user/default/skills",- ),],ids=["user-memory",- "user-memory-isolated-by-agent",- "agent-memory",- "agent-memory-isolated-by-user",- "agent-skills-isolated-by-user",],)def test_langgraph_store_accepts_canonical_result_uris_for_shorthand_root(@@ -1026,9 +1113,7 @@ def test_langgraph_store_ignores_unrelated_canonical_result_uris():is None)assert (- store._parse_index_uri(- "viking://agent/support/user/default/memories/langgraph_store/index/users/ada.md"- )+ store._parse_index_uri("viking://user/support/memories/other_store/index/users/ada.md")is None)@@ -1145,6 +1230,47 @@ def test_langgraph_middleware_injects_recall_and_captures_messages():assert any(part["type"] == "context" for part in assistant_parts)+def test_langgraph_middleware_passes_peer_id_to_recall_and_capture():+ client = InMemoryOpenVikingClient(+ {"viking://user/memories/profile.md": "The middleware peer prefers azure."}+ )+ middleware = OpenVikingContextMiddleware(+ client=client,+ target_uri="viking://user/memories",+ session_id_resolver=lambda state, runtime: "middleware-peer-session",+ )++ class Request:+ state = {"peer_id": "peer-middleware"}+ messages = [HumanMessage(content="What peer color?")]+ system_message = None++ def override(self, **overrides):+ new_request = Request()+ new_request.messages = overrides.get("messages", self.messages)+ new_request.system_message = overrides.get("system_message", self.system_message)+ new_request.state = self.state+ return new_request++ middleware.wrap_model_call(Request(), lambda request: AIMessage(content="ok"))+ middleware.after_agent(+ {+ "peer_id": "peer-middleware",+ "messages": [+ HumanMessage(content="Remember middleware peer."),+ AIMessage(content="Stored."),+ ],+ },+ runtime=None,+ )++ assert client.search_calls[-1]["peer_id"] == "peer-middleware"+ assert [message.get("peer_id") for message in client.sessions["middleware-peer-session"]] == [+ "peer-middleware",+ "peer-middleware",+ ]++def test_langgraph_middleware_does_not_duplicate_active_messages_in_context():client = InMemoryOpenVikingClient({"viking://user/memories/profile.md": "Middleware recall uses green context."}diff --git a/tests/unit/test_message.py b/tests/unit/test_message.pyindex 895dcb9b7..30d803c1f 100644--- a/tests/unit/test_message.py+++ b/tests/unit/test_message.py@@ -136,7 +136,7 @@ class TestToolPart:tool_id="call-123",tool_name="search",tool_uri="viking://session/test/tools/call-123",- skill_uri="viking://agent/test/skills/search",+ skill_uri="viking://user/test/skills/search",tool_input={"query": "test"},tool_output="Result",tool_status="completed",@@ -155,7 +155,7 @@ class TestToolPart:assert part.tool_id == "call-123"assert part.tool_name == "search"assert part.tool_uri == "viking://session/test/tools/call-123"- assert part.skill_uri == "viking://agent/test/skills/search"+ assert part.skill_uri == "viking://user/test/skills/search"assert part.tool_input == {"query": "test"}assert part.tool_output == "Result"assert part.tool_status == "completed"@@ -232,7 +232,7 @@ class TestPartFromDict:"tool_id": "call-123","tool_name": "search","tool_uri": "viking://session/test/tools/call-123",- "skill_uri": "viking://agent/test/skills/search",+ "skill_uri": "viking://user/test/skills/search","tool_input": {"query": "test"},"tool_output": "Result","tool_status": "completed",@@ -607,7 +607,7 @@ class TestMessageFromDict:"content": "Legacy message","created_at": "2026-03-26T10:30:00Z",}- fresh = Message.create_user("Fresh message", msg_id="msg-fresh")+ fresh = Message(id="msg-fresh", role="user", parts=[TextPart("Fresh message")])reloaded_messages = [Message.from_dict(legacy_row), Message.from_dict(fresh.to_dict())]@@ -623,87 +623,9 @@ class TestMessageFromDict:]-class TestMessageFactoryMethods:- """Test Message factory methods."""-- def test_create_user(self):- """Test create_user factory method."""- msg = Message.create_user("Hello, assistant!")-- assert msg.role == "user"- assert msg.content == "Hello, assistant!"- assert len(msg.parts) == 1- assert msg.id.startswith("msg_")-- def test_create_user_with_id(self):- """Test create_user with custom ID."""- msg = Message.create_user("Hello", msg_id="custom-id")-- assert msg.id == "custom-id"-- def test_create_assistant(self):- """Test create_assistant factory method."""- msg = Message.create_assistant("Hello, user!")-- assert msg.role == "assistant"- assert msg.content == "Hello, user!"- assert len(msg.parts) == 1-- def test_create_assistant_with_context_refs(self):- """Test create_assistant with context references."""- msg = Message.create_assistant(- content="Here's what I found:",- context_refs=[- {"uri": "viking://test/1.md", "context_type": "memory"},- {"uri": "viking://test/2.md", "context_type": "resource"},- ],- )-- assert msg.role == "assistant"- assert len(msg.parts) == 3 # 1 text + 2 context-- def test_create_assistant_with_tool_calls(self):- """Test create_assistant with tool calls."""- msg = Message.create_assistant(- content="Let me search for that.",- tool_calls=[- {"id": "call-1", "name": "search", "uri": "viking://tools/1"},- ],- )-- assert msg.role == "assistant"- assert len(msg.parts) == 2 # 1 text + 1 tool-- def test_create_assistant_empty(self):- """Test create_assistant with no content."""- msg = Message.create_assistant()-- assert msg.role == "assistant"- assert msg.content == ""- assert len(msg.parts) == 0--class TestMessageMethods:"""Test Message methods."""- def test_get_context_parts(self):- """Test get_context_parts method."""- msg = Message(- id="msg-1",- role="assistant",- parts=[- TextPart(text="Hello"),- ContextPart(uri="viking://test/1.md"),- TextPart(text="More text"),- ContextPart(uri="viking://test/2.md"),- ],- )-- context_parts = msg.get_context_parts()-- assert len(context_parts) == 2- assert all(isinstance(p, ContextPart) for p in context_parts)-def test_get_tool_parts(self):"""Test get_tool_parts method."""msg = Message(diff --git a/tests/unit/test_namespace_uri_classification.py b/tests/unit/test_namespace_uri_classification.pyindex bce4f39db..55a2dc02b 100644--- a/tests/unit/test_namespace_uri_classification.py+++ b/tests/unit/test_namespace_uri_classification.py@@ -7,24 +7,23 @@ from openviking.core.namespace import (context_type_for_uri,owner_space_for_uri,)-from openviking.server.identity import AccountNamespacePolicy, RequestContext, Role+from openviking.server.identity import RequestContext, Rolefrom openviking_cli.session.user_id import UserIdentifierdef test_context_type_for_uri_uses_path_segments():assert context_type_for_uri("viking://user/alice/memories/entities/m1.md") == "memory"assert context_type_for_uri("viking://user/memories/entities/m1.md") == "memory"- assert context_type_for_uri("viking://agent/memories/cases/m1.md") == "memory"- assert context_type_for_uri("viking://agent/skills/demo") == "skill"- assert context_type_for_uri("viking://agent/default/memories/cases/m1.md") == "memory"+ assert context_type_for_uri("viking://user/alice/skills/demo") == "skill"+ assert context_type_for_uri("viking://user/skills/demo") == "skill"assert (- context_type_for_uri("viking://user/alice/agent/default/memories/entities/m1.md")+ context_type_for_uri(+ "viking://user/support_bot/peers/web:visitor:alice/memories/profile.md"+ )== "memory")- assert context_type_for_uri("viking://agent/default/skills/demo") == "skill"- assert context_type_for_uri("viking://agent/default/user/alice/skills/demo") == "skill"assert context_type_for_uri("viking://resources/memories-report.md") == "resource"- assert context_type_for_uri("viking://agent/default/resources/skills-report.md") == "resource"+ assert context_type_for_uri("viking://user/alice/resources/skills-report.md") == "resource"def test_exact_memory_and_skill_root_detection():@@ -33,27 +32,19 @@ def test_exact_memory_and_skill_root_detection():assert classify_uri("viking://user/memories").is_memory_rootassert not classify_uri("viking://user/alice/memories/preferences").is_memory_root- assert classify_uri("viking://agent/default/skills/demo/SKILL.md").is_skill- assert classify_uri("viking://agent/default/skills/demo").is_skill_root- assert classify_uri("viking://agent/skills/demo").is_skill_root- assert not classify_uri("viking://agent/default/skills").is_skill_root- assert not classify_uri("viking://agent/default/skills/demo/assets").is_skill_root+ assert classify_uri("viking://user/alice/skills/demo/SKILL.md").is_skill+ assert classify_uri("viking://user/alice/skills/demo").is_skill_root+ assert classify_uri("viking://user/skills/demo").is_skill_root+ assert not classify_uri("viking://user/alice/skills").is_skill_root+ assert not classify_uri("viking://user/alice/skills/demo/assets").is_skill_root-def test_owner_space_for_uri_respects_namespace_policy():+def test_owner_space_for_uri_uses_user_only():ctx = RequestContext(- user=UserIdentifier(account_id="acct", user_id="alice", agent_id="planner"),+ user=UserIdentifier(account_id="acct", user_id="alice"),role=Role.ROOT,- namespace_policy=AccountNamespacePolicy(- isolate_user_scope_by_agent=True,- isolate_agent_scope_by_user=True,- ),)- assert owner_space_for_uri("viking://user/alice/agent/planner/memories", ctx) == (- "alice/agent/planner"- )- assert owner_space_for_uri("viking://agent/planner/user/alice/skills/demo", ctx) == (- "planner/user/alice"- )+ assert owner_space_for_uri("viking://user/alice/memories", ctx) == "alice"+ assert owner_space_for_uri("viking://user/alice/skills/demo", ctx) == "alice"assert owner_space_for_uri("viking://resources/readme.md", ctx) == ""diff --git a/tests/unit/test_summarizer_context_type.py b/tests/unit/test_summarizer_context_type.pyindex 1b424909a..1b5d6a378 100644--- a/tests/unit/test_summarizer_context_type.py+++ b/tests/unit/test_summarizer_context_type.py@@ -17,9 +17,9 @@ class TestSummarizerContextType:uri = "viking://user/default/memories/entities/mem_abc123.md"assert context_type_for_uri(uri) == "memory"- def test_agent_memory_uri(self):- """Agent memory URIs should classify as 'memory'."""- uri = "viking://agent/default/memories/cases/mem_xyz789.md"+ def test_peer_memory_uri(self):+ """Peer memory URIs should classify as 'memory'."""+ uri = "viking://user/default/peers/support-bot/memories/cases/mem_xyz789.md"assert context_type_for_uri(uri) == "memory"def test_memory_profile_uri(self):@@ -34,7 +34,7 @@ class TestSummarizerContextType:def test_skill_uri(self):"""Skill URIs should classify as 'skill'."""- uri = "viking://agent/default/skills/search.md"+ uri = "viking://user/default/skills/search.md"assert context_type_for_uri(uri) == "skill"def test_resource_uri(self):@@ -62,7 +62,7 @@ class TestSummarizerContextType:# These real memory URIs do NOT start with "viking://memory/"real_uris = ["viking://user/default/memories/entities/mem_001.md",- "viking://agent/default/memories/patterns/mem_002.md",+ "viking://user/default/peers/support-bot/memories/patterns/mem_002.md","viking://user/john/memories/events/mem_003.md",]for uri in real_uris:diff --git a/tests/unit/test_uri_short_format.py b/tests/unit/test_uri_short_format.pyindex 35b28e027..38bac8876 100644--- a/tests/unit/test_uri_short_format.py+++ b/tests/unit/test_uri_short_format.py@@ -35,10 +35,10 @@ class TestVikingURIShortFormat:assert uri.scope == "user"def test_bare_nested_path(self):- """'agent/skills/pdf' should normalize correctly."""- uri = VikingURI("agent/skills/pdf")- assert uri.uri == "viking://agent/skills/pdf"- assert uri.scope == "agent"+ """'user/skills/pdf' should normalize correctly."""+ uri = VikingURI("user/skills/pdf")+ assert uri.uri == "viking://user/skills/pdf"+ assert uri.scope == "user"def test_full_format_unchanged(self):"""Full-format URIs should pass through unchanged."""@@ -93,7 +93,7 @@ class TestVikingURIShortFormat:[("/resources", "viking://resources"),("/user", "viking://user"),- ("/agent/skills", "viking://agent/skills"),+ ("/user/skills", "viking://user/skills"),("/session/abc123", "viking://session/abc123"),("/queue", "viking://queue"),("/temp", "viking://temp"),diff --git a/tests/unit/test_vectorize_file_strategy.py b/tests/unit/test_vectorize_file_strategy.pyindex 89b5af47f..538937963 100644--- a/tests/unit/test_vectorize_file_strategy.py+++ b/tests/unit/test_vectorize_file_strategy.py@@ -41,23 +41,15 @@ class DummyFS:class DummyUser:account_id = "default"user_id = "default"- agent_id = "default-agent"def user_space_name(self):- return "user/default"-- def agent_space_name(self):- return "agent/default"+ return "default"class DummyReq:def __init__(self):self.user = DummyUser()self.account_id = "default"- self.namespace_policy = types.SimpleNamespace(- isolate_user_scope_by_agent=False,- isolate_agent_scope_by_user=False,- )@pytest.mark.asynciodiff --git a/tests/unit/tool_skill/test_tool_skill_utils.py b/tests/unit/tool_skill/test_tool_skill_utils.pyindex 6f54883cd..aa6ca444d 100644--- a/tests/unit/tool_skill/test_tool_skill_utils.py+++ b/tests/unit/tool_skill/test_tool_skill_utils.py@@ -47,7 +47,7 @@ class TestToolSkillUtils:assert stats["completion_tokens"] == 9def test_calibrate_skill_name_matches_by_skill_uri_suffix(self):- tool_parts = [ToolPart(skill_uri="viking://agent/skills/weather", tool_status="error")]+ tool_parts = [ToolPart(skill_uri="viking://user/skills/weather", tool_status="error")]tool_name, status = calibrate_skill_name("weather", tool_parts)assert tool_name == "weather"assert status == "error"@@ -55,14 +55,14 @@ class TestToolSkillUtils:def test_collect_skill_stats_aggregates_by_skill_name(self):tool_parts = [ToolPart(- skill_uri="viking://agent/skills/weather",+ skill_uri="viking://user/skills/weather",tool_status="completed",duration_ms=3,prompt_tokens=2,completion_tokens=4,),ToolPart(- skill_uri="viking://agent/skills/weather",+ skill_uri="viking://user/skills/weather",tool_status="error",duration_ms=7,prompt_tokens=1,diff --git a/tests/utils/mock_context.py b/tests/utils/mock_context.pyindex 0b3971274..c3ff55939 100644--- a/tests/utils/mock_context.py+++ b/tests/utils/mock_context.py@@ -10,10 +10,9 @@ from openviking_cli.session.user_id import UserIdentifierdef make_test_user(account_id: str = "acc1",user_id: str = "test_user",- agent_id: str = "test_agent",) -> UserIdentifier:"""Create a test UserIdentifier"""- return UserIdentifier(account_id, user_id, agent_id)+ return UserIdentifier(account_id, user_id)def make_test_ctx(@@ -21,9 +20,8 @@ def make_test_ctx(role: Role = Role.ROOT,account_id: str = "acc1",user_id: str = "test_user",- agent_id: str = "test_agent",) -> RequestContext:"""Create a test RequestContext"""if user is None:- user = make_test_user(account_id, user_id, agent_id)+ user = make_test_user(account_id, user_id)return RequestContext(user=user, role=role)diff --git a/uv.lock b/uv.lockindex 2a87ad92f..fd1d9c03a 100644--- a/uv.lock+++ b/uv.lock@@ -1559,6 +1559,7 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/38/3f/9859f655d11901e7b2996c6e3d33e0caa9a1d4572c3bc61ed0faa64b2f4c/greenlet-3.3.2-cp310-cp310-macosx_11_0_universal2.whl", hash = "sha256:9bc885b89709d901859cf95179ec9f6bb67a3d2bb1f0e88456461bd4b7f8fd0d", size = 277747, upload-time = "2026-02-20T20:16:21.325Z" },{ url = "https://files.pythonhosted.org/packages/fb/07/cb284a8b5c6498dbd7cba35d31380bb123d7dceaa7907f606c8ff5993cbf/greenlet-3.3.2-cp310-cp310-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b568183cf65b94919be4438dc28416b234b678c608cafac8874dfeeb2a9bbe13", size = 579202, upload-time = "2026-02-20T20:47:28.955Z" },{ url = "https://files.pythonhosted.org/packages/ed/45/67922992b3a152f726163b19f890a85129a992f39607a2a53155de3448b8/greenlet-3.3.2-cp310-cp310-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:527fec58dc9f90efd594b9b700662ed3fb2493c2122067ac9c740d98080a620e", size = 590620, upload-time = "2026-02-20T20:55:55.581Z" },+ { url = "https://files.pythonhosted.org/packages/03/5f/6e2a7d80c353587751ef3d44bb947f0565ec008a2e0927821c007e96d3a7/greenlet-3.3.2-cp310-cp310-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:508c7f01f1791fbc8e011bd508f6794cb95397fdb198a46cb6635eb5b78d85a7", size = 602132, upload-time = "2026-02-20T21:02:43.261Z" },{ url = "https://files.pythonhosted.org/packages/ad/55/9f1ebb5a825215fadcc0f7d5073f6e79e3007e3282b14b22d6aba7ca6cb8/greenlet-3.3.2-cp310-cp310-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ad0c8917dd42a819fe77e6bdfcb84e3379c0de956469301d9fd36427a1ca501f", size = 591729, upload-time = "2026-02-20T20:20:58.395Z" },{ url = "https://files.pythonhosted.org/packages/24/b4/21f5455773d37f94b866eb3cf5caed88d6cea6dd2c6e1f9c34f463cba3ec/greenlet-3.3.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:97245cc10e5515dbc8c3104b2928f7f02b6813002770cfaffaf9a6e0fc2b94ef", size = 1551946, upload-time = "2026-02-20T20:49:31.102Z" },{ url = "https://files.pythonhosted.org/packages/00/68/91f061a926abead128fe1a87f0b453ccf07368666bd59ffa46016627a930/greenlet-3.3.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:8c1fdd7d1b309ff0da81d60a9688a8bd044ac4e18b250320a96fc68d31c209ca", size = 1618494, upload-time = "2026-02-20T20:21:06.541Z" },@@ -1566,6 +1567,7 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/f3/47/16400cb42d18d7a6bb46f0626852c1718612e35dcb0dffa16bbaffdf5dd2/greenlet-3.3.2-cp311-cp311-macosx_11_0_universal2.whl", hash = "sha256:c56692189a7d1c7606cb794be0a8381470d95c57ce5be03fb3d0ef57c7853b86", size = 278890, upload-time = "2026-02-20T20:19:39.263Z" },{ url = "https://files.pythonhosted.org/packages/a3/90/42762b77a5b6aa96cd8c0e80612663d39211e8ae8a6cd47c7f1249a66262/greenlet-3.3.2-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1ebd458fa8285960f382841da585e02201b53a5ec2bac6b156fc623b5ce4499f", size = 581120, upload-time = "2026-02-20T20:47:30.161Z" },{ url = "https://files.pythonhosted.org/packages/bf/6f/f3d64f4fa0a9c7b5c5b3c810ff1df614540d5aa7d519261b53fba55d4df9/greenlet-3.3.2-cp311-cp311-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a443358b33c4ec7b05b79a7c8b466f5d275025e750298be7340f8fc63dff2a55", size = 594363, upload-time = "2026-02-20T20:55:56.965Z" },+ { url = "https://files.pythonhosted.org/packages/9c/8b/1430a04657735a3f23116c2e0d5eb10220928846e4537a938a41b350bed6/greenlet-3.3.2-cp311-cp311-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4375a58e49522698d3e70cc0b801c19433021b5c37686f7ce9c65b0d5c8677d2", size = 605046, upload-time = "2026-02-20T21:02:45.234Z" },{ url = "https://files.pythonhosted.org/packages/72/83/3e06a52aca8128bdd4dcd67e932b809e76a96ab8c232a8b025b2850264c5/greenlet-3.3.2-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8e2cd90d413acbf5e77ae41e5d3c9b3ac1d011a756d7284d7f3f2b806bbd6358", size = 594156, upload-time = "2026-02-20T20:20:59.955Z" },{ url = "https://files.pythonhosted.org/packages/70/79/0de5e62b873e08fe3cef7dbe84e5c4bc0e8ed0c7ff131bccb8405cd107c8/greenlet-3.3.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:442b6057453c8cb29b4fb36a2ac689382fc71112273726e2423f7f17dc73bf99", size = 1554649, upload-time = "2026-02-20T20:49:32.293Z" },{ url = "https://files.pythonhosted.org/packages/5a/00/32d30dee8389dc36d42170a9c66217757289e2afb0de59a3565260f38373/greenlet-3.3.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:45abe8eb6339518180d5a7fa47fa01945414d7cca5ecb745346fc6a87d2750be", size = 1619472, upload-time = "2026-02-20T20:21:07.966Z" },@@ -1574,6 +1576,7 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/ea/ab/1608e5a7578e62113506740b88066bf09888322a311cff602105e619bd87/greenlet-3.3.2-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:ac8d61d4343b799d1e526db579833d72f23759c71e07181c2d2944e429eb09cd", size = 280358, upload-time = "2026-02-20T20:17:43.971Z" },{ url = "https://files.pythonhosted.org/packages/a5/23/0eae412a4ade4e6623ff7626e38998cb9b11e9ff1ebacaa021e4e108ec15/greenlet-3.3.2-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3ceec72030dae6ac0c8ed7591b96b70410a8be370b6a477b1dbc072856ad02bd", size = 601217, upload-time = "2026-02-20T20:47:31.462Z" },{ url = "https://files.pythonhosted.org/packages/f8/16/5b1678a9c07098ecb9ab2dd159fafaf12e963293e61ee8d10ecb55273e5e/greenlet-3.3.2-cp312-cp312-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a2a5be83a45ce6188c045bcc44b0ee037d6a518978de9a5d97438548b953a1ac", size = 611792, upload-time = "2026-02-20T20:55:58.423Z" },+ { url = "https://files.pythonhosted.org/packages/5c/c5/cc09412a29e43406eba18d61c70baa936e299bc27e074e2be3806ed29098/greenlet-3.3.2-cp312-cp312-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ae9e21c84035c490506c17002f5c8ab25f980205c3e61ddb3a2a2a2e6c411fcb", size = 626250, upload-time = "2026-02-20T21:02:46.596Z" },{ url = "https://files.pythonhosted.org/packages/50/1f/5155f55bd71cabd03765a4aac9ac446be129895271f73872c36ebd4b04b6/greenlet-3.3.2-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:43e99d1749147ac21dde49b99c9abffcbc1e2d55c67501465ef0930d6e78e070", size = 613875, upload-time = "2026-02-20T20:21:01.102Z" },{ url = "https://files.pythonhosted.org/packages/fc/dd/845f249c3fcd69e32df80cdab059b4be8b766ef5830a3d0aa9d6cad55beb/greenlet-3.3.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4c956a19350e2c37f2c48b336a3afb4bff120b36076d9d7fb68cb44e05d95b79", size = 1571467, upload-time = "2026-02-20T20:49:33.495Z" },{ url = "https://files.pythonhosted.org/packages/2a/50/2649fe21fcc2b56659a452868e695634722a6655ba245d9f77f5656010bf/greenlet-3.3.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:6c6f8ba97d17a1e7d664151284cb3315fc5f8353e75221ed4324f84eb162b395", size = 1640001, upload-time = "2026-02-20T20:21:09.154Z" },@@ -1582,6 +1585,7 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/ac/48/f8b875fa7dea7dd9b33245e37f065af59df6a25af2f9561efa8d822fde51/greenlet-3.3.2-cp313-cp313-macosx_11_0_universal2.whl", hash = "sha256:aa6ac98bdfd716a749b84d4034486863fd81c3abde9aa3cf8eff9127981a4ae4", size = 279120, upload-time = "2026-02-20T20:19:01.9Z" },{ url = "https://files.pythonhosted.org/packages/49/8d/9771d03e7a8b1ee456511961e1b97a6d77ae1dea4a34a5b98eee706689d3/greenlet-3.3.2-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ab0c7e7901a00bc0a7284907273dc165b32e0d109a6713babd04471327ff7986", size = 603238, upload-time = "2026-02-20T20:47:32.873Z" },{ url = "https://files.pythonhosted.org/packages/59/0e/4223c2bbb63cd5c97f28ffb2a8aee71bdfb30b323c35d409450f51b91e3e/greenlet-3.3.2-cp313-cp313-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:d248d8c23c67d2291ffd47af766e2a3aa9fa1c6703155c099feb11f526c63a92", size = 614219, upload-time = "2026-02-20T20:55:59.817Z" },+ { url = "https://files.pythonhosted.org/packages/94/2b/4d012a69759ac9d77210b8bfb128bc621125f5b20fc398bce3940d036b1c/greenlet-3.3.2-cp313-cp313-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ccd21bb86944ca9be6d967cf7691e658e43417782bce90b5d2faeda0ff78a7dd", size = 628268, upload-time = "2026-02-20T21:02:48.024Z" },{ url = "https://files.pythonhosted.org/packages/7a/34/259b28ea7a2a0c904b11cd36c79b8cef8019b26ee5dbe24e73b469dea347/greenlet-3.3.2-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b6997d360a4e6a4e936c0f9625b1c20416b8a0ea18a8e19cabbefc712e7397ab", size = 616774, upload-time = "2026-02-20T20:21:02.454Z" },{ url = "https://files.pythonhosted.org/packages/0a/03/996c2d1689d486a6e199cb0f1cf9e4aa940c500e01bdf201299d7d61fa69/greenlet-3.3.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:64970c33a50551c7c50491671265d8954046cb6e8e2999aacdd60e439b70418a", size = 1571277, upload-time = "2026-02-20T20:49:34.795Z" },{ url = "https://files.pythonhosted.org/packages/d9/c4/2570fc07f34a39f2caf0bf9f24b0a1a0a47bc2e8e465b2c2424821389dfc/greenlet-3.3.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:1a9172f5bf6bd88e6ba5a84e0a68afeac9dc7b6b412b245dd64f52d83c81e55b", size = 1640455, upload-time = "2026-02-20T20:21:10.261Z" },@@ -1590,6 +1594,7 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/3f/ae/8bffcbd373b57a5992cd077cbe8858fff39110480a9d50697091faea6f39/greenlet-3.3.2-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:8d1658d7291f9859beed69a776c10822a0a799bc4bfe1bd4272bb60e62507dab", size = 279650, upload-time = "2026-02-20T20:18:00.783Z" },{ url = "https://files.pythonhosted.org/packages/d1/c0/45f93f348fa49abf32ac8439938726c480bd96b2a3c6f4d949ec0124b69f/greenlet-3.3.2-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:18cb1b7337bca281915b3c5d5ae19f4e76d35e1df80f4ad3c1a7be91fadf1082", size = 650295, upload-time = "2026-02-20T20:47:34.036Z" },{ url = "https://files.pythonhosted.org/packages/b3/de/dd7589b3f2b8372069ab3e4763ea5329940fc7ad9dcd3e272a37516d7c9b/greenlet-3.3.2-cp314-cp314-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c2e47408e8ce1c6f1ceea0dffcdf6ebb85cc09e55c7af407c99f1112016e45e9", size = 662163, upload-time = "2026-02-20T20:56:01.295Z" },+ { url = "https://files.pythonhosted.org/packages/cd/ac/85804f74f1ccea31ba518dcc8ee6f14c79f73fe36fa1beba38930806df09/greenlet-3.3.2-cp314-cp314-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:e3cb43ce200f59483eb82949bf1835a99cf43d7571e900d7c8d5c62cdf25d2f9", size = 675371, upload-time = "2026-02-20T21:02:49.664Z" },{ url = "https://files.pythonhosted.org/packages/d2/d8/09bfa816572a4d83bccd6750df1926f79158b1c36c5f73786e26dbe4ee38/greenlet-3.3.2-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:63d10328839d1973e5ba35e98cccbca71b232b14051fd957b6f8b6e8e80d0506", size = 664160, upload-time = "2026-02-20T20:21:04.015Z" },{ url = "https://files.pythonhosted.org/packages/48/cf/56832f0c8255d27f6c35d41b5ec91168d74ec721d85f01a12131eec6b93c/greenlet-3.3.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:8e4ab3cfb02993c8cc248ea73d7dae6cec0253e9afa311c9b37e603ca9fad2ce", size = 1619181, upload-time = "2026-02-20T20:49:36.052Z" },{ url = "https://files.pythonhosted.org/packages/0a/23/b90b60a4aabb4cec0796e55f25ffbfb579a907c3898cd2905c8918acaa16/greenlet-3.3.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:94ad81f0fd3c0c0681a018a976e5c2bd2ca2d9d94895f23e7bb1af4e8af4e2d5", size = 1687713, upload-time = "2026-02-20T20:21:11.684Z" },@@ -1598,6 +1603,7 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/98/6d/8f2ef704e614bcf58ed43cfb8d87afa1c285e98194ab2cfad351bf04f81e/greenlet-3.3.2-cp314-cp314t-macosx_11_0_universal2.whl", hash = "sha256:e26e72bec7ab387ac80caa7496e0f908ff954f31065b0ffc1f8ecb1338b11b54", size = 286617, upload-time = "2026-02-20T20:19:29.856Z" },{ url = "https://files.pythonhosted.org/packages/5e/0d/93894161d307c6ea237a43988f27eba0947b360b99ac5239ad3fe09f0b47/greenlet-3.3.2-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8b466dff7a4ffda6ca975979bab80bdadde979e29fc947ac3be4451428d8b0e4", size = 655189, upload-time = "2026-02-20T20:47:35.742Z" },{ url = "https://files.pythonhosted.org/packages/f5/2c/d2d506ebd8abcb57386ec4f7ba20f4030cbe56eae541bc6fd6ef399c0b41/greenlet-3.3.2-cp314-cp314t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b8bddc5b73c9720bea487b3bffdb1840fe4e3656fba3bd40aa1489e9f37877ff", size = 658225, upload-time = "2026-02-20T20:56:02.527Z" },+ { url = "https://files.pythonhosted.org/packages/d1/67/8197b7e7e602150938049d8e7f30de1660cfb87e4c8ee349b42b67bdb2e1/greenlet-3.3.2-cp314-cp314t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:59b3e2c40f6706b05a9cd299c836c6aa2378cabe25d021acd80f13abf81181cf", size = 666581, upload-time = "2026-02-20T21:02:51.526Z" },{ url = "https://files.pythonhosted.org/packages/8e/30/3a09155fbf728673a1dea713572d2d31159f824a37c22da82127056c44e4/greenlet-3.3.2-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b26b0f4428b871a751968285a1ac9648944cea09807177ac639b030bddebcea4", size = 657907, upload-time = "2026-02-20T20:21:05.259Z" },{ url = "https://files.pythonhosted.org/packages/f3/fd/d05a4b7acd0154ed758797f0a43b4c0962a843bedfe980115e842c5b2d08/greenlet-3.3.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:1fb39a11ee2e4d94be9a76671482be9398560955c9e568550de0224e41104727", size = 1618857, upload-time = "2026-02-20T20:49:37.309Z" },{ url = "https://files.pythonhosted.org/packages/6f/e1/50ee92a5db521de8f35075b5eff060dd43d39ebd46c2181a2042f7070385/greenlet-3.3.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:20154044d9085151bc309e7689d6f7ba10027f8f5a8c0676ad398b951913d89e", size = 1680010, upload-time = "2026-02-20T20:21:13.427Z" },@@ -3696,6 +3702,9 @@ local-embed = [ocr = [{ name = "pytesseract" },]+opengauss = [+ { name = "psycopg2-binary" },+]test = [{ name = "boto3" },{ name = "datasets" },@@ -3755,7 +3764,7 @@ requires-dist = [{ name = "langgraph", marker = "extra == 'langgraph'", specifier = ">=1.0.0,<2.0.0" },{ name = "lark-oapi", specifier = ">=1.5.3" },{ name = "lark-oapi", marker = "extra == 'bot-feishu'", specifier = ">=1.0.0" },- { name = "litellm", specifier = ">=1.83.7,<1.85.2" },+ { name = "litellm", specifier = ">=1.83.7,<1.86.3" },{ name = "llama-cpp-python", marker = "extra == 'local-embed'", specifier = ">=0.3.0" },{ name = "loguru", specifier = ">=0.7.3" },{ name = "markdownify", specifier = ">=0.11.0" },@@ -3784,6 +3793,7 @@ requires-dist = [{ name = "pdfplumber", specifier = ">=0.10.0" },{ name = "prompt-toolkit", marker = "extra == 'bot'", specifier = ">=3.0.0" },{ name = "protobuf", specifier = ">=6.33.5" },+ { name = "psycopg2-binary", marker = "extra == 'opengauss'", specifier = ">=2.9" },{ name = "py-machineid", marker = "extra == 'bot'", specifier = ">=1.0.0" },{ name = "pydantic", specifier = ">=2.0.0" },{ name = "pydantic-settings", marker = "extra == 'bot'", specifier = ">=2.0.0" },@@ -3841,7 +3851,7 @@ requires-dist = [{ name = "xlrd", specifier = ">=2.0.1" },{ name = "xxhash", specifier = ">=3.0.0" },]-provides-extras = ["test", "dev", "doc", "eval", "gemini", "gemini-async", "ocr", "build", "bot", "bot-langfuse", "bot-telegram", "bot-feishu", "bot-dingtalk", "bot-slack", "bot-qq", "bot-sandbox", "bot-fuse", "bot-opencode", "bot-full", "benchmark", "langchain", "langgraph", "local-embed"]+provides-extras = ["test", "opengauss", "dev", "doc", "eval", "gemini", "gemini-async", "ocr", "build", "bot", "bot-langfuse", "bot-telegram", "bot-feishu", "bot-dingtalk", "bot-slack", "bot-qq", "bot-sandbox", "bot-fuse", "bot-opencode", "bot-full", "benchmark", "langchain", "langgraph", "local-embed"][package.metadata.requires-dev]dev = [{ name = "pytest", specifier = ">=9.0.2" }]@@ -4452,6 +4462,69 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/57/bf/2086963c69bdac3d7cff1cc7ff79b8ce5ea0bec6797a017e1be338a46248/protobuf-6.33.5-py3-none-any.whl", hash = "sha256:69915a973dd0f60f31a08b8318b73eab2bd6a392c79184b3612226b0a3f8ec02", size = 170687, upload-time = "2026-01-29T21:51:32.557Z" },]+[[package]]+name = "psycopg2-binary"+version = "2.9.12"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/2a/60/a3624f79acea344c16fbef3a94d28b89a8042ddfb8f3e4ca83f538671409/psycopg2_binary-2.9.12.tar.gz", hash = "sha256:5ac9444edc768c02a6b6a591f070b8aae28ff3a99be57560ac996001580f294c", size = 379686, upload-time = "2026-04-21T09:40:34.304Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/78/80/49bacf9e51617d8309f6f0123e29edc793f6f5f6700c7d1f1b20782fbb37/psycopg2_binary-2.9.12-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:9b818ceff717f98851a64bffd4c5eb5b3059ae280276dcecc52ac658dcf006a4", size = 3712314, upload-time = "2026-04-20T23:33:31.363Z" },+ { url = "https://files.pythonhosted.org/packages/d3/f2/98eeac7d60c43df9338287834edf9b3e69be68a2db78a57b1b81d705e735/psycopg2_binary-2.9.12-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:d2fa0d7caca8635c56e373055094eeda3208d901d55dd0ff5abc1d4e47f82b56", size = 3822389, upload-time = "2026-04-20T23:33:34.178Z" },+ { url = "https://files.pythonhosted.org/packages/9f/7c/30575e75f14d5351a56a1971bb43fe7f8bf7edf1b654fb1bec65c42a8812/psycopg2_binary-2.9.12-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:864c261b3690e1207d14bbfe0a61e27567981b80c47a778561e49f676f7ce433", size = 4578448, upload-time = "2026-04-20T23:33:37.073Z" },+ { url = "https://files.pythonhosted.org/packages/65/9b/4df366d89f28c527dc39d0b6c98a5ca74e30d37ac097b73f3352147568ae/psycopg2_binary-2.9.12-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c5ee5213445dd45312459029b8c4c0a695461eb517b753d2582315bd07995f5e", size = 4273705, upload-time = "2026-04-20T23:33:39.291Z" },+ { url = "https://files.pythonhosted.org/packages/4e/8a/c566803818eb03161ba869b6ba612bf7ad56816d98b9e5121e0a22ad6b0b/psycopg2_binary-2.9.12-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6f9cae1f848779b5b01f417e762c40d026ea93eb0648249a604728cda991dde3", size = 5893784, upload-time = "2026-04-20T23:33:41.658Z" },+ { url = "https://files.pythonhosted.org/packages/63/fe/0dfa5797e0b229e0567bc378695224caf14d547f73b05be0c80549089772/psycopg2_binary-2.9.12-cp310-cp310-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:63a3ebbd543d3d1eda088ac99164e8c5bac15293ee91f20281fd17d050aee1c4", size = 4109306, upload-time = "2026-04-20T23:33:43.953Z" },+ { url = "https://files.pythonhosted.org/packages/3c/89/28063adf17a4ba501eedd9890feab0c649ee4d8bd0a97df0ff1e9584feab/psycopg2_binary-2.9.12-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:d6fcbba8c9fed08a73b8ac61ea79e4821e45b1e92bb466230c5e746bbf3d5256", size = 3654400, upload-time = "2026-04-20T23:33:46.115Z" },+ { url = "https://files.pythonhosted.org/packages/84/94/5a01de0aa4ead0b8d8d1aa4ec18cec0bd36d03fa714eaa5bb8a0b1b50020/psycopg2_binary-2.9.12-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:36512911ebb2b60a0c3e44d0bb5048c1980aced91235d133b7874f3d1d93487c", size = 3299215, upload-time = "2026-04-20T23:33:48.202Z" },+ { url = "https://files.pythonhosted.org/packages/7a/85/723bb085a61c6ac2dc0a0043f375f2fe7365363e27b073bad56ca5bda979/psycopg2_binary-2.9.12-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:8ffdb59fe88f99589e34354a130217aa1fd2d615612402d6edc8b3dbc7a44463", size = 3047724, upload-time = "2026-04-20T23:33:50.74Z" },+ { url = "https://files.pythonhosted.org/packages/b4/67/4d8b1e0d2fc4166677380eac0edf9cdff91013aca2546e8ef7bc04b56158/psycopg2_binary-2.9.12-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:a46fe069b65255df410f856d842bc235f90e22ffdf532dda625fd4213d3fd9b1", size = 3349183, upload-time = "2026-04-20T23:33:59.635Z" },+ { url = "https://files.pythonhosted.org/packages/73/99/21af7a5498637ea4dc91a17c281a53bc1d632fbafe00f6689fbfb32a9fed/psycopg2_binary-2.9.12-cp310-cp310-win_amd64.whl", hash = "sha256:ab29414b25dcb698bf26bf213e3348abdcd07bbd5de032a5bec15bd75b298b03", size = 2757036, upload-time = "2026-04-20T23:34:01.606Z" },+ { url = "https://files.pythonhosted.org/packages/d5/19/d4ce60954f3bb9d8e3bc5e5c4d1f2487de2d3851bf2391d54954c9df12a6/psycopg2_binary-2.9.12-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:5c8ce6c61bd1b1f6b9c24ee32211599f6166af2c55abb19456090a21fd16554b", size = 3712338, upload-time = "2026-04-20T23:34:03.961Z" },+ { url = "https://files.pythonhosted.org/packages/53/71/c85409ee0d78890f0660eff262e815e7dd2bb741a17611d82e9e8cd9dc5e/psycopg2_binary-2.9.12-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:b4a9eaa6e7f4ff91bec10aa3fb296878e75187bced5cc4bafe17dc40915e1326", size = 3822407, upload-time = "2026-04-20T23:34:05.977Z" },+ { url = "https://files.pythonhosted.org/packages/3c/ed/60486c2c7f0d4d1ede2bfb1ed27e2498477ce646bc7f6b2759906303117e/psycopg2_binary-2.9.12-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:c6528cefc8e50fcc6f4a107e27a672058b36cc5736d665476aeb413ba88dbb06", size = 4578425, upload-time = "2026-04-20T23:34:08.246Z" },+ { url = "https://files.pythonhosted.org/packages/0b/b9/656cb03fad9f4f49f2145c334b1126ee75189929ca4e6187d485a2d59951/psycopg2_binary-2.9.12-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e4e184b1fb6072bf05388aa41c697e1b2d01b3473f107e7ec44f186a32cfd0b8", size = 4273709, upload-time = "2026-04-20T23:34:10.974Z" },+ { url = "https://files.pythonhosted.org/packages/99/66/08cf0da0e25cc6fb142c89be45fc8418792858f0c4cbff5e24530ff02cd6/psycopg2_binary-2.9.12-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4766ab678563054d3f1d064a4db19cc4b5f9e3a8d9018592a8285cf200c248f3", size = 5893779, upload-time = "2026-04-20T23:34:13.905Z" },+ { url = "https://files.pythonhosted.org/packages/17/d7/eecd9ce8e146d3721115d82d3836efdbb712187e4590325df549989d18f4/psycopg2_binary-2.9.12-cp311-cp311-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5a0253224780c978746cb9be55a946bcdaf40fe3519c0f622924cdabdafe2c39", size = 4109308, upload-time = "2026-04-20T23:34:16.761Z" },+ { url = "https://files.pythonhosted.org/packages/b6/2e/b1dc289b362cc8d45697b57eefbd673186f49a4ea0906928988e3affcc98/psycopg2_binary-2.9.12-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:0dc9228d47c46bda253d2ecd6bb93b56a9f2d7ad33b684a1fa3622bf74ffe30c", size = 3654405, upload-time = "2026-04-20T23:34:19.303Z" },+ { url = "https://files.pythonhosted.org/packages/eb/e4/4c4aea6473214dbdbd0fbba11aa4691e76dc01722c55724c5951719865ff/psycopg2_binary-2.9.12-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:f921f3cd87035ef7df233383011d7a53ea1d346224752c1385f1edfd790ceb6a", size = 3299187, upload-time = "2026-04-20T23:34:21.206Z" },+ { url = "https://files.pythonhosted.org/packages/ba/5d/b03b99986446a4f57b170ed9a2579fb7ff9783ca0fa5226b19db99737fee/psycopg2_binary-2.9.12-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:3d999bd982a723113c1a45b55a7a6a90d64d0ed2278020ed625c490ff7bef96c", size = 3047716, upload-time = "2026-04-20T23:34:23.077Z" },+ { url = "https://files.pythonhosted.org/packages/14/86/382ee4afbd1d97500c9d2862b20c2fdeddf4b7335e984df3fb4309f64108/psycopg2_binary-2.9.12-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:29d4d134bd0ab46ffb04e94aa3c5fa3ef582e9026609165e2f758ff76fc3a3be", size = 3349237, upload-time = "2026-04-20T23:34:25.211Z" },+ { url = "https://files.pythonhosted.org/packages/a8/16/9a57c75ba1eda7165c017342f526810d5f5a12647dde749c99ae9a7141d7/psycopg2_binary-2.9.12-cp311-cp311-win_amd64.whl", hash = "sha256:cb4a1dacdd48077150dc762a9e5ddbf32c256d66cb46f80839391aa458774936", size = 2757036, upload-time = "2026-04-20T23:34:27.77Z" },+ { url = "https://files.pythonhosted.org/packages/e2/9f/ef4ef3c8e15083df90ca35265cfd1a081a2f0cc07bb229c6314c6af817f4/psycopg2_binary-2.9.12-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:5cdc05117180c5fa9c40eea8ea559ce64d73824c39d928b7da9fb5f6a9392433", size = 3712459, upload-time = "2026-04-20T23:34:30.549Z" },+ { url = "https://files.pythonhosted.org/packages/b5/01/3dd14e46ba48c1e1a6ec58ee599fa1b5efa00c246d5046cd903d0eeb1af1/psycopg2_binary-2.9.12-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d3227a3bc228c10d21011a99245edca923e4e8bf461857e869a507d9a41fe9f6", size = 3822936, upload-time = "2026-04-20T23:34:32.77Z" },+ { url = "https://files.pythonhosted.org/packages/a6/f7/0640e4901119d8a9f7a1784b927f494e2198e213ceb593753d1f2c8b1b30/psycopg2_binary-2.9.12-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:995ce929eede89db6254b50827e2b7fd61e50d11f0b116b29fffe4a2e53c4580", size = 4578676, upload-time = "2026-04-20T23:34:35.18Z" },+ { url = "https://files.pythonhosted.org/packages/b0/55/44df3965b5f297c50cc0b1b594a31c67d6127a9d133045b8a66611b14dfb/psycopg2_binary-2.9.12-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:9fe06d93e72f1c048e731a2e3e7854a5bfaa58fc736068df90b352cefe66f03f", size = 4274917, upload-time = "2026-04-20T23:34:37.982Z" },+ { url = "https://files.pythonhosted.org/packages/b0/4b/74535248b1eac0c9336862e8617c765ac94dac76f9e25d7c4a79588c8907/psycopg2_binary-2.9.12-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:40e7b28b63aaf737cb3a1edc3a9bbc9a9f4ad3dcb7152e8c1130e4050eddcb7d", size = 5894843, upload-time = "2026-04-20T23:34:40.856Z" },+ { url = "https://files.pythonhosted.org/packages/f2/ba/f1bf8d2ae71868ad800b661099086ee52bc0f8d9f05be1acd8ebb06757cc/psycopg2_binary-2.9.12-cp312-cp312-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:89d19a9f7899e8eb0656a2b3a08e0da04c720a06db6e0033eab5928aabe60fa9", size = 4110556, upload-time = "2026-04-20T23:34:44.016Z" },+ { url = "https://files.pythonhosted.org/packages/45/46/c15706c338403b7c420bcc0c2905aad116cc064545686d8bf85f1999ea00/psycopg2_binary-2.9.12-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:612b965daee295ae2da8f8218ce1d274645dc76ef3f1abf6a0a94fd57eff876d", size = 3655714, upload-time = "2026-04-20T23:34:46.233Z" },+ { url = "https://files.pythonhosted.org/packages/b3/7c/a2d5dc09b64a4564db242a0fe418fde7d33f6f8259dd2c5b9d7def00fb5a/psycopg2_binary-2.9.12-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:b9a339b79d37c1b45f3235265f07cdeb0cb5ad7acd2ac7720a5920989c17c24e", size = 3301154, upload-time = "2026-04-20T23:34:49.528Z" },+ { url = "https://files.pythonhosted.org/packages/c0/e8/cc8c9a4ce71461f9ec548d38cadc41dc184b34c73e6455450775a9334ccd/psycopg2_binary-2.9.12-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:3471336e1acfd9c7fe507b8bad5af9317b6a89294f9eb37bd9a030bb7bebcdc6", size = 3048882, upload-time = "2026-04-20T23:34:51.86Z" },+ { url = "https://files.pythonhosted.org/packages/19/6a/31e2296bc0787c5ab75d3d118e40b239db8151b5192b90b77c72bc9256e9/psycopg2_binary-2.9.12-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:7af18183109e23502c8b2ae7f6926c0882766f35b5175a4cd737ad825e4d7a1b", size = 3351298, upload-time = "2026-04-20T23:34:54.124Z" },+ { url = "https://files.pythonhosted.org/packages/5f/a8/75f4e3e11203b590150abed2cf7794b9c9c9f7eceddae955191138b44dde/psycopg2_binary-2.9.12-cp312-cp312-win_amd64.whl", hash = "sha256:398fcd4db988c7d7d3713e2b8e18939776fd3fb447052daae4f24fa39daede4c", size = 2757230, upload-time = "2026-04-20T23:34:56.242Z" },+ { url = "https://files.pythonhosted.org/packages/91/bb/4608c96f970f6e0c56572e87027ef4404f709382a3503e9934526d7ba051/psycopg2_binary-2.9.12-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7c729a73c7b1b84de3582f73cdd27d905121dc2c531f3d9a3c32a3011033b965", size = 3712419, upload-time = "2026-04-20T23:34:58.754Z" },+ { url = "https://files.pythonhosted.org/packages/5e/af/48f76af9d50d61cf390f8cd657b503168b089e2e9298e48465d029fcc713/psycopg2_binary-2.9.12-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:4413d0caef93c5cf50b96863df4c2efe8c269bf2267df353225595e7e15e8df7", size = 3822990, upload-time = "2026-04-20T23:35:00.821Z" },+ { url = "https://files.pythonhosted.org/packages/7a/df/aba0f99397cd811d32e06fc0cc781f1f3ce98bc0e729cb423925085d781a/psycopg2_binary-2.9.12-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4dfcf8e45ebb0c663be34a3442f65e17311f3367089cd4e5e3a3e8e62c978777", size = 4578696, upload-time = "2026-04-20T23:35:03.409Z" },+ { url = "https://files.pythonhosted.org/packages/95/9c/eaa74021ac4e4d5c2f83d82fc6615a63f4fe6c94dc4e94c3990427053f67/psycopg2_binary-2.9.12-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c41321a14dd74aceb6a9a643b9253a334521babfa763fa873e33d89cfa122fb5", size = 4274982, upload-time = "2026-04-20T23:35:05.583Z" },+ { url = "https://files.pythonhosted.org/packages/35/ed/c25deff98bd26187ba48b3b250a3ffc3037c46c5b89362534a15d200e0db/psycopg2_binary-2.9.12-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:83946ba43979ebfdc99a3cd0ee775c89f221df026984ba19d46133d8d75d3cd9", size = 5894867, upload-time = "2026-04-20T23:35:07.902Z" },+ { url = "https://files.pythonhosted.org/packages/9a/81/8d0e21ca77373c6c9589e5c4528f6e8f0c08c62cafc76fb0bddb7a2cee22/psycopg2_binary-2.9.12-cp313-cp313-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:411e85815652d13560fbe731878daa5d92378c4995a22302071890ec3397d019", size = 4110578, upload-time = "2026-04-20T23:35:10.149Z" },+ { url = "https://files.pythonhosted.org/packages/00/fc/f481e2435bd8f742d0123309174aae4165160ad3ef17c1b99c3622c241d2/psycopg2_binary-2.9.12-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:1c8ad4c08e00f7679559eaed7aff1edfffc60c086b976f93972f686384a95e2c", size = 3655816, upload-time = "2026-04-20T23:35:12.56Z" },+ { url = "https://files.pythonhosted.org/packages/53/79/b9f46466bdbe9f239c96cde8be33c1aace4842f06013b47b730dc9759187/psycopg2_binary-2.9.12-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:00814e40fa23c2b37ef0a1e3c749d89982c73a9cb5046137f0752a22d432e82f", size = 3301307, upload-time = "2026-04-20T23:35:15.029Z" },+ { url = "https://files.pythonhosted.org/packages/3f/19/7dc003b32fe35024df89b658104f7c8538a8b2dcbde7a4e746ce929742e7/psycopg2_binary-2.9.12-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:98062447aebc20ed20add1f547a364fd0ef8933640d5372ff1873f8deb9b61be", size = 3048968, upload-time = "2026-04-20T23:35:16.757Z" },+ { url = "https://files.pythonhosted.org/packages/91/58/2dbd7db5c604d45f4950d988506aae672a14126ec22998ced5021cbb76bb/psycopg2_binary-2.9.12-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:66a7685d7e548f10fb4ce32fb01a7b7f4aa702134de92a292c7bd9e0d3dbd290", size = 3351369, upload-time = "2026-04-20T23:35:18.933Z" },+ { url = "https://files.pythonhosted.org/packages/42/ee/dee8dcaad07f735824de3d6563bc67119fa6c28257b17977a8d624f02fab/psycopg2_binary-2.9.12-cp313-cp313-win_amd64.whl", hash = "sha256:b6937f5fe4e180aeee87de907a2fa982ded6f7f15d7218f78a083e4e1d68f2a0", size = 2757347, upload-time = "2026-04-20T23:35:21.283Z" },+ { url = "https://files.pythonhosted.org/packages/13/1b/708c0dca874acfad6d65314271859899a79007686f3a1f74e82a2ed4b645/psycopg2_binary-2.9.12-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:6f3b3de8a74ef8db215f22edffb19e32dc6fa41340456de7ec99efdc8a7b3ec2", size = 3712428, upload-time = "2026-04-20T23:35:23.453Z" },+ { url = "https://files.pythonhosted.org/packages/d6/39/ddbea9d4b4de6aca9431b6ed253f530f8a02d3b8f9bcfd0dbfe2b3de6fe4/psycopg2_binary-2.9.12-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1006fb62f0f0bc5ce256a832356c6262e91be43f5e4eb15b5eaf38079464caf2", size = 3823184, upload-time = "2026-04-20T23:35:25.92Z" },+ { url = "https://files.pythonhosted.org/packages/bf/a0/bc2fef74b106fa345567122a0659e6d94512ed7dc0131ec44c9e5aba3725/psycopg2_binary-2.9.12-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:840066105706cd2eb29b9a1c2329620056582a4bf3e8169dec5c447042d0869f", size = 4579157, upload-time = "2026-04-20T23:35:28.542Z" },+ { url = "https://files.pythonhosted.org/packages/57/d7/d4e3b2005d3de607ca4fbb0e8742e248056e52184a6b94ebda3c1c2c329b/psycopg2_binary-2.9.12-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:863f5d12241ebe1c76a72a04c2113b6dc905f90b9cef0e9be0efd994affd9354", size = 4274970, upload-time = "2026-04-20T23:35:30.418Z" },+ { url = "https://files.pythonhosted.org/packages/2e/42/c9853f8db3967fe08bcde11f53d53b85d351750cae726ce001cb68afa9c1/psycopg2_binary-2.9.12-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a99eaab34a9010f1a086b126de467466620a750634d114d20455f3a824aae033", size = 5895175, upload-time = "2026-04-20T23:35:33.584Z" },+ { url = "https://files.pythonhosted.org/packages/eb/fd/b82b5601a97630308bef079f545ffec481bbbc795c2ba5ec416a01d03f60/psycopg2_binary-2.9.12-cp314-cp314-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ffdd7dc5463ccd61845ac37b7012d0f35a1548df9febe14f8dd549be4a0bc81e", size = 4110658, upload-time = "2026-04-20T23:35:35.638Z" },+ { url = "https://files.pythonhosted.org/packages/62/8c/32ca69b0389ef25dd22937bf9e8fbe2ce27aea20b05ded48c4ce4cb42475/psycopg2_binary-2.9.12-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:54a0dfecab1b48731f934e06139dfe11e24219fb6d0ceb32177cf0375f14c7b5", size = 3656251, upload-time = "2026-04-20T23:35:37.854Z" },+ { url = "https://files.pythonhosted.org/packages/c4/29/96992a2b59e3b9d730fcf9612d0a387305025dc867a9fc490a9e496e074e/psycopg2_binary-2.9.12-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:96937c9c5d891f772430f418a7a8b4691a90c3e6b93cf72b5bd7cad8cbca32a5", size = 3301810, upload-time = "2026-04-20T23:35:39.927Z" },+ { url = "https://files.pythonhosted.org/packages/56/ad/44b06659949b243ae10112cd3b20a197f9bf3e81d5651379b9eb889bfaad/psycopg2_binary-2.9.12-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:77b348775efd4cdab410ec6609d81ccecd1139c90265fa583a7255c8064bc03d", size = 3048977, upload-time = "2026-04-20T23:35:41.806Z" },+ { url = "https://files.pythonhosted.org/packages/1d/f2/10a1bcebadb6aa55e280e1f58975c36a7b560ea525184c7aa4064c466633/psycopg2_binary-2.9.12-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:527e6342b3e44c2f0544f6b8e927d60de7f163f5723b8f1dfa7d2a84298738cd", size = 3351466, upload-time = "2026-04-20T23:35:43.993Z" },+ { url = "https://files.pythonhosted.org/packages/20/be/b732c8418ffa5bcfda002890f5dc4c869fc17db66ff11f53b17cfe44afc0/psycopg2_binary-2.9.12-cp314-cp314-win_amd64.whl", hash = "sha256:f12ae41fcafadb39b2785e64a40f9db05d6de2ac114077457e0e7c597f3af980", size = 2848762, upload-time = "2026-04-20T23:35:46.421Z" },+]+[[package]]name = "py"version = "1.11.0"diff --git a/web-studio/README.md b/web-studio/README.mdindex 633785acf..7eb395a37 100644--- a/web-studio/README.md+++ b/web-studio/README.md@@ -99,7 +99,6 @@ Request headers injected by the adapter:- `X-API-Key`- `X-OpenViking-Account`- `X-OpenViking-User`-- `X-OpenViking-Agent: web-studio`For production or multi-tenant deployments, configure a real `server.root_api_key` or user key in OpenViking Server and enter the matching connection settings in Web Studio.diff --git a/web-studio/README_CN.md b/web-studio/README_CN.mdindex d33e39f57..6a2f540e7 100644--- a/web-studio/README_CN.md+++ b/web-studio/README_CN.md@@ -99,7 +99,6 @@ VITE_OV_BASE_URL=http://127.0.0.1:1933 npm run dev- `X-API-Key`- `X-OpenViking-Account`- `X-OpenViking-User`-- `X-OpenViking-Agent: web-studio`生产或多租户部署应在 OpenViking Server 中配置真实的 `server.root_api_key` 或 user key,并在 Web Studio 中填写匹配的连接信息。diff --git a/web-studio/src/components/connection-dialog.tsx b/web-studio/src/components/connection-dialog.tsxindex 547a03289..dfaeae0f4 100644--- a/web-studio/src/components/connection-dialog.tsx+++ b/web-studio/src/components/connection-dialog.tsx@@ -136,26 +136,6 @@ export function ConnectionDialog() {/></FieldContent></Field>- <Field>- <FieldLabel htmlFor="ov-agent-id">- {t('fields.agentId.label', { ns: 'connection' })}- </FieldLabel>- <FieldContent>- <Input- id="ov-agent-id"- placeholder={t('fields.agentId.placeholder', {- ns: 'connection',- })}- value={draft.agentId}- onChange={(event) =>- setDraft((current) => ({- ...current,- agentId: event.target.value,- }))- }- />- </FieldContent>- </Field></div><Field>diff --git a/web-studio/src/gen/ov-client/index.ts b/web-studio/src/gen/ov-client/index.tsindex 359e96c08..d0e7faafd 100644--- a/web-studio/src/gen/ov-client/index.ts+++ b/web-studio/src/gen/ov-client/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-ts-export { deleteAdminAccountByAccountId, deleteAdminAccountIdUserByUserId, deleteFs, deleteRelationsLink, deleteSessionBySessionId, deleteWebdavResourceByResourcePath, deleteWebdavResources, getAdminAccountIdAgents, getAdminAccountIdUsers, getAdminAccounts, getBotV1Health, getConsoleAudit, getConsoleContextCommits, getConsoleDashboardSummary, getConsoleTokens, getContentAbstract, getContentDownload, getContentOverview, getContentRead, getDebugHealth, getDebugVectorCount, getDebugVectorScroll, getFsLs, getFsStat, getFsTree, getHealth, getMetrics, getObserverFilesystem, getObserverLock, getObserverModels, getObserverQueue, getObserverRetrieval, getObserverSystem, getObserverVikingdb, getPrivacyConfigs, getPrivacyConfigsByCategory, getPrivacyConfigsByCategoryAndTargetKey, getPrivacyConfigsVersionByCategoryAndTargetKeyAndVersion, getPrivacyConfigsVersionsByCategoryAndTargetKey, getReady, getRelations, getSessionBySessionId, getSessionIdArchiveByArchiveId, getSessionIdContext, getSessions, getStatsMemories, getStatsSessionBySessionId, getSystemStatus, getTaskByTaskId, getTasks, getWebdavResourceByResourcePath, getWebdavResources, headWebdavResourceByResourcePath, headWebdavResources, type Options, optionsWebdavResourceByResourcePath, optionsWebdavResources, postAdminAccountIdUserIdKey, postAdminAccountIdUsers, postAdminAccounts, postBotV1Chat, postBotV1ChatStream, postBotV1Feedback, postContentReindex, postContentWrite, postFsMkdir, postFsMv, postPackBackup, postPackExport, postPackImport, postPackRestore, postPrivacyConfigsActivateByCategoryAndTargetKey, postPrivacyConfigsByCategoryAndTargetKey, postRelationsLink, postResources, postResourcesTempUpload, postSearchFind, postSearchGlob, postSearchGrep, postSearchSearch, postSessionIdCommit, postSessionIdExtract, postSessionIdMessages, postSessionIdUsed, postSessions, postSkills, postSystemConsistency, postSystemWait, putAdminAccountIdUserIdRole, putWebdavResourceByResourcePath, putWebdavResources } from './sdk.gen';-export type { ActivatePrivacyConfigVersionRequest, AddMessageRequest, AddResourceRequest, AddSkillRequest, BackupRequest, BodyTempUploadApiV1ResourcesTempUploadPost, ClientOptions, CommitRequest, ConsistencyRequest, CreateAccountRequest, CreateSessionRequest, DeleteAdminAccountByAccountIdData, DeleteAdminAccountByAccountIdError, DeleteAdminAccountByAccountIdErrors, DeleteAdminAccountByAccountIdResponses, DeleteAdminAccountIdUserByUserIdData, DeleteAdminAccountIdUserByUserIdError, DeleteAdminAccountIdUserByUserIdErrors, DeleteAdminAccountIdUserByUserIdResponses, DeleteFsData, DeleteFsError, DeleteFsErrors, DeleteFsResponses, DeleteRelationsLinkData, DeleteRelationsLinkError, DeleteRelationsLinkErrors, DeleteRelationsLinkResponses, DeleteSessionBySessionIdData, DeleteSessionBySessionIdError, DeleteSessionBySessionIdErrors, DeleteSessionBySessionIdResponses, DeleteWebdavResourceByResourcePathData, DeleteWebdavResourceByResourcePathError, DeleteWebdavResourceByResourcePathErrors, DeleteWebdavResourceByResourcePathResponses, DeleteWebdavResourcesData, DeleteWebdavResourcesError, DeleteWebdavResourcesErrors, DeleteWebdavResourcesResponses, ExportRequest, FindRequest, GetAdminAccountIdAgentsData, GetAdminAccountIdAgentsError, GetAdminAccountIdAgentsErrors, GetAdminAccountIdAgentsResponses, GetAdminAccountIdUsersData, GetAdminAccountIdUsersError, GetAdminAccountIdUsersErrors, GetAdminAccountIdUsersResponses, GetAdminAccountsData, GetAdminAccountsError, GetAdminAccountsErrors, GetAdminAccountsResponses, GetBotV1HealthData, GetBotV1HealthResponses, GetConsoleAuditData, GetConsoleAuditError, GetConsoleAuditErrors, GetConsoleAuditResponses, GetConsoleContextCommitsData, GetConsoleContextCommitsError, GetConsoleContextCommitsErrors, GetConsoleContextCommitsResponses, GetConsoleDashboardSummaryData, GetConsoleDashboardSummaryError, GetConsoleDashboardSummaryErrors, GetConsoleDashboardSummaryResponses, GetConsoleTokensData, GetConsoleTokensError, GetConsoleTokensErrors, GetConsoleTokensResponses, GetContentAbstractData, GetContentAbstractError, GetContentAbstractErrors, GetContentAbstractResponses, GetContentDownloadData, GetContentDownloadError, GetContentDownloadErrors, GetContentDownloadResponses, GetContentOverviewData, GetContentOverviewError, GetContentOverviewErrors, GetContentOverviewResponses, GetContentReadData, GetContentReadError, GetContentReadErrors, GetContentReadResponses, GetDebugHealthData, GetDebugHealthError, GetDebugHealthErrors, GetDebugHealthResponses, GetDebugVectorCountData, GetDebugVectorCountError, GetDebugVectorCountErrors, GetDebugVectorCountResponses, GetDebugVectorScrollData, GetDebugVectorScrollError, GetDebugVectorScrollErrors, GetDebugVectorScrollResponses, GetFsLsData, GetFsLsError, GetFsLsErrors, GetFsLsResponses, GetFsStatData, GetFsStatError, GetFsStatErrors, GetFsStatResponses, GetFsTreeData, GetFsTreeError, GetFsTreeErrors, GetFsTreeResponses, GetHealthData, GetHealthResponses, GetMetricsData, GetMetricsResponses, GetObserverFilesystemData, GetObserverFilesystemError, GetObserverFilesystemErrors, GetObserverFilesystemResponses, GetObserverLockData, GetObserverLockError, GetObserverLockErrors, GetObserverLockResponses, GetObserverModelsData, GetObserverModelsError, GetObserverModelsErrors, GetObserverModelsResponses, GetObserverQueueData, GetObserverQueueError, GetObserverQueueErrors, GetObserverQueueResponses, GetObserverRetrievalData, GetObserverRetrievalError, GetObserverRetrievalErrors, GetObserverRetrievalResponses, GetObserverSystemData, GetObserverSystemError, GetObserverSystemErrors, GetObserverSystemResponses, GetObserverVikingdbData, GetObserverVikingdbError, GetObserverVikingdbErrors, GetObserverVikingdbResponses, GetPrivacyConfigsByCategoryAndTargetKeyData, GetPrivacyConfigsByCategoryAndTargetKeyError, GetPrivacyConfigsByCategoryAndTargetKeyErrors, GetPrivacyConfigsByCategoryAndTargetKeyResponses, GetPrivacyConfigsByCategoryData, GetPrivacyConfigsByCategoryError, GetPrivacyConfigsByCategoryErrors, GetPrivacyConfigsByCategoryResponses, GetPrivacyConfigsData, GetPrivacyConfigsError, GetPrivacyConfigsErrors, GetPrivacyConfigsResponses, GetPrivacyConfigsVersionByCategoryAndTargetKeyAndVersionData, GetPrivacyConfigsVersionByCategoryAndTargetKeyAndVersionError, GetPrivacyConfigsVersionByCategoryAndTargetKeyAndVersionErrors, GetPrivacyConfigsVersionByCategoryAndTargetKeyAndVersionResponses, GetPrivacyConfigsVersionsByCategoryAndTargetKeyData, GetPrivacyConfigsVersionsByCategoryAndTargetKeyError, GetPrivacyConfigsVersionsByCategoryAndTargetKeyErrors, GetPrivacyConfigsVersionsByCategoryAndTargetKeyResponses, GetReadyData, GetReadyResponses, GetRelationsData, GetRelationsError, GetRelationsErrors, GetRelationsResponses, GetSessionBySessionIdData, GetSessionBySessionIdError, GetSessionBySessionIdErrors, GetSessionBySessionIdResponses, GetSessionIdArchiveByArchiveIdData, GetSessionIdArchiveByArchiveIdError, GetSessionIdArchiveByArchiveIdErrors, GetSessionIdArchiveByArchiveIdResponses, GetSessionIdContextData, GetSessionIdContextError, GetSessionIdContextErrors, GetSessionIdContextResponses, GetSessionsData, GetSessionsError, GetSessionsErrors, GetSessionsResponses, GetStatsMemoriesData, GetStatsMemoriesError, GetStatsMemoriesErrors, GetStatsMemoriesResponses, GetStatsSessionBySessionIdData, GetStatsSessionBySessionIdError, GetStatsSessionBySessionIdErrors, GetStatsSessionBySessionIdResponses, GetSystemStatusData, GetSystemStatusError, GetSystemStatusErrors, GetSystemStatusResponses, GetTaskByTaskIdData, GetTaskByTaskIdError, GetTaskByTaskIdErrors, GetTaskByTaskIdResponses, GetTasksData, GetTasksError, GetTasksErrors, GetTasksResponses, GetWebdavResourceByResourcePathData, GetWebdavResourceByResourcePathError, GetWebdavResourceByResourcePathErrors, GetWebdavResourceByResourcePathResponses, GetWebdavResourcesData, GetWebdavResourcesError, GetWebdavResourcesErrors, GetWebdavResourcesResponses, GlobRequest, GrepRequest, HeadWebdavResourceByResourcePathData, HeadWebdavResourceByResourcePathError, HeadWebdavResourceByResourcePathErrors, HeadWebdavResourceByResourcePathResponses, HeadWebdavResourcesData, HeadWebdavResourcesError, HeadWebdavResourcesErrors, HeadWebdavResourcesResponses, HttpValidationError, ImportRequest, LinkRequest, MkdirRequest, MvRequest, OptionsWebdavResourceByResourcePathData, OptionsWebdavResourceByResourcePathError, OptionsWebdavResourceByResourcePathErrors, OptionsWebdavResourceByResourcePathResponses, OptionsWebdavResourcesData, OptionsWebdavResourcesError, OptionsWebdavResourcesErrors, OptionsWebdavResourcesResponses, PostAdminAccountIdUserIdKeyData, PostAdminAccountIdUserIdKeyError, PostAdminAccountIdUserIdKeyErrors, PostAdminAccountIdUserIdKeyResponses, PostAdminAccountIdUsersData, PostAdminAccountIdUsersError, PostAdminAccountIdUsersErrors, PostAdminAccountIdUsersResponses, PostAdminAccountsData, PostAdminAccountsError, PostAdminAccountsErrors, PostAdminAccountsResponses, PostBotV1ChatData, PostBotV1ChatError, PostBotV1ChatErrors, PostBotV1ChatResponses, PostBotV1ChatStreamData, PostBotV1ChatStreamError, PostBotV1ChatStreamErrors, PostBotV1ChatStreamResponses, PostBotV1FeedbackData, PostBotV1FeedbackError, PostBotV1FeedbackErrors, PostBotV1FeedbackResponses, PostContentReindexData, PostContentReindexError, PostContentReindexErrors, PostContentReindexResponses, PostContentWriteData, PostContentWriteError, PostContentWriteErrors, PostContentWriteResponses, PostFsMkdirData, PostFsMkdirError, PostFsMkdirErrors, PostFsMkdirResponses, PostFsMvData, PostFsMvError, PostFsMvErrors, PostFsMvResponses, PostPackBackupData, PostPackBackupError, PostPackBackupErrors, PostPackBackupResponses, PostPackExportData, PostPackExportError, PostPackExportErrors, PostPackExportResponses, PostPackImportData, PostPackImportError, PostPackImportErrors, PostPackImportResponses, PostPackRestoreData, PostPackRestoreError, PostPackRestoreErrors, PostPackRestoreResponses, PostPrivacyConfigsActivateByCategoryAndTargetKeyData, PostPrivacyConfigsActivateByCategoryAndTargetKeyError, PostPrivacyConfigsActivateByCategoryAndTargetKeyErrors, PostPrivacyConfigsActivateByCategoryAndTargetKeyResponses, PostPrivacyConfigsByCategoryAndTargetKeyData, PostPrivacyConfigsByCategoryAndTargetKeyError, PostPrivacyConfigsByCategoryAndTargetKeyErrors, PostPrivacyConfigsByCategoryAndTargetKeyResponses, PostRelationsLinkData, PostRelationsLinkError, PostRelationsLinkErrors, PostRelationsLinkResponses, PostResourcesData, PostResourcesError, PostResourcesErrors, PostResourcesResponses, PostResourcesTempUploadData, PostResourcesTempUploadError, PostResourcesTempUploadErrors, PostResourcesTempUploadResponses, PostSearchFindData, PostSearchFindError, PostSearchFindErrors, PostSearchFindResponses, PostSearchGlobData, PostSearchGlobError, PostSearchGlobErrors, PostSearchGlobResponses, PostSearchGrepData, PostSearchGrepError, PostSearchGrepErrors, PostSearchGrepResponses, PostSearchSearchData, PostSearchSearchError, PostSearchSearchErrors, PostSearchSearchResponses, PostSessionIdCommitData, PostSessionIdCommitError, PostSessionIdCommitErrors, PostSessionIdCommitResponses, PostSessionIdExtractData, PostSessionIdExtractError, PostSessionIdExtractErrors, PostSessionIdExtractResponses, PostSessionIdMessagesData, PostSessionIdMessagesError, PostSessionIdMessagesErrors, PostSessionIdMessagesResponses, PostSessionIdUsedData, PostSessionIdUsedError, PostSessionIdUsedErrors, PostSessionIdUsedResponses, PostSessionsData, PostSessionsError, PostSessionsErrors, PostSessionsResponses, PostSkillsData, PostSkillsError, PostSkillsErrors, PostSkillsResponses, PostSystemConsistencyData, PostSystemConsistencyError, PostSystemConsistencyErrors, PostSystemConsistencyResponses, PostSystemWaitData, PostSystemWaitError, PostSystemWaitErrors, PostSystemWaitResponses, PutAdminAccountIdUserIdRoleData, PutAdminAccountIdUserIdRoleError, PutAdminAccountIdUserIdRoleErrors, PutAdminAccountIdUserIdRoleResponses, PutWebdavResourceByResourcePathData, PutWebdavResourceByResourcePathError, PutWebdavResourceByResourcePathErrors, PutWebdavResourceByResourcePathResponses, PutWebdavResourcesData, PutWebdavResourcesError, PutWebdavResourcesErrors, PutWebdavResourcesResponses, RegisterUserRequest, ReindexRequest, RestoreRequest, SearchRequest, SetRoleRequest, UnlinkRequest, UpsertPrivacyConfigRequest, UsedRequest, ValidationError, WaitRequest, WriteContentRequest } from './types.gen';+export { deleteAdminAccountByAccountId, deleteAdminAccountIdUserByUserId, deleteFs, deleteRelationsLink, deleteSessionBySessionId, deleteWebdavResourceByResourcePath, deleteWebdavResources, getAdminAccountIdUsers, getAdminAccounts, getBotV1Health, getConsoleAudit, getConsoleContextCommits, getConsoleDashboardSummary, getConsoleTokens, getContentAbstract, getContentDownload, getContentOverview, getContentRead, getDebugHealth, getDebugVectorCount, getDebugVectorScroll, getFsLs, getFsStat, getFsTree, getHealth, getMetrics, getObserverFilesystem, getObserverLock, getObserverModels, getObserverQueue, getObserverRetrieval, getObserverSystem, getObserverVikingdb, getPrivacyConfigs, getPrivacyConfigsByCategory, getPrivacyConfigsByCategoryAndTargetKey, getPrivacyConfigsVersionByCategoryAndTargetKeyAndVersion, getPrivacyConfigsVersionsByCategoryAndTargetKey, getReady, getRelations, getSessionBySessionId, getSessionIdArchiveByArchiveId, getSessionIdContext, getSessions, getStatsMemories, getStatsSessionBySessionId, getSystemStatus, getTaskByTaskId, getTasks, getWebdavResourceByResourcePath, getWebdavResources, headWebdavResourceByResourcePath, headWebdavResources, type Options, optionsWebdavResourceByResourcePath, optionsWebdavResources, postAdminAccountIdUserIdKey, postAdminAccountIdUsers, postAdminAccounts, postBotV1Chat, postBotV1ChatStream, postBotV1Feedback, postContentReindex, postContentWrite, postFsMkdir, postFsMv, postPackBackup, postPackExport, postPackImport, postPackRestore, postPrivacyConfigsActivateByCategoryAndTargetKey, postPrivacyConfigsByCategoryAndTargetKey, postRelationsLink, postResources, postResourcesTempUpload, postSearchFind, postSearchGlob, postSearchGrep, postSearchSearch, postSessionIdCommit, postSessionIdExtract, postSessionIdMessages, postSessionIdUsed, postSessions, postSkills, postSystemConsistency, postSystemWait, putAdminAccountIdUserIdRole, putWebdavResourceByResourcePath, putWebdavResources } from './sdk.gen';+export type { ActivatePrivacyConfigVersionRequest, AddMessageRequest, AddResourceRequest, AddSkillRequest, BackupRequest, BodyTempUploadApiV1ResourcesTempUploadPost, ClientOptions, CommitRequest, ConsistencyRequest, CreateAccountRequest, CreateSessionRequest, DeleteAdminAccountByAccountIdData, DeleteAdminAccountByAccountIdError, DeleteAdminAccountByAccountIdErrors, DeleteAdminAccountByAccountIdResponses, DeleteAdminAccountIdUserByUserIdData, DeleteAdminAccountIdUserByUserIdError, DeleteAdminAccountIdUserByUserIdErrors, DeleteAdminAccountIdUserByUserIdResponses, DeleteFsData, DeleteFsError, DeleteFsErrors, DeleteFsResponses, DeleteRelationsLinkData, DeleteRelationsLinkError, DeleteRelationsLinkErrors, DeleteRelationsLinkResponses, DeleteSessionBySessionIdData, DeleteSessionBySessionIdError, DeleteSessionBySessionIdErrors, DeleteSessionBySessionIdResponses, DeleteWebdavResourceByResourcePathData, DeleteWebdavResourceByResourcePathError, DeleteWebdavResourceByResourcePathErrors, DeleteWebdavResourceByResourcePathResponses, DeleteWebdavResourcesData, DeleteWebdavResourcesError, DeleteWebdavResourcesErrors, DeleteWebdavResourcesResponses, ExportRequest, FindRequests, GetAdminAccountIdUsersData, GetAdminAccountIdUsersError, GetAdminAccountIdUsersErrors, GetAdminAccountIdUsersResponses, GetAdminAccountsData, GetAdminAccountsError, GetAdminAccountsErrors, GetAdminAccountsResponses, GetBotV1HealthData, GetBotV1HealthResponses, GetConsoleAuditData, GetConsoleAuditError, GetConsoleAuditErrors, GetConsoleAuditResponses, GetConsoleContextCommitsData, GetConsoleContextCommitsError, GetConsoleContextCommitsErrors, GetConsoleContextCommitsResponses, GetConsoleDashboardSummaryData, GetConsoleDashboardSummaryError, GetConsoleDashboardSummaryErrors, GetConsoleDashboardSummaryResponses, GetConsoleTokensData, GetConsoleTokensError, GetConsoleTokensErrors, GetConsoleTokensResponses, GetContentAbstractData, GetContentAbstractError, GetContentAbstractErrors, GetContentAbstractResponses, GetContentDownloadData, GetContentDownloadError, GetContentDownloadErrors, GetContentDownloadResponses, GetContentOverviewData, GetContentOverviewError, GetContentOverviewErrors, GetContentOverviewResponses, GetContentReadData, GetContentReadError, GetContentReadErrors, GetContentReadResponses, GetDebugHealthData, GetDebugHealthError, GetDebugHealthErrors, GetDebugHealthResponses, GetDebugVectorCountData, GetDebugVectorCountError, GetDebugVectorCountErrors, GetDebugVectorCountResponses, GetDebugVectorScrollData, GetDebugVectorScrollError, GetDebugVectorScrollErrors, GetDebugVectorScrollResponses, GetFsLsData, GetFsLsError, GetFsLsErrors, GetFsLsResponses, GetFsStatData, GetFsStatError, GetFsStatErrors, GetFsStatResponses, GetFsTreeData, GetFsTreeError, GetFsTreeErrors, GetFsTreeResponses, GetHealthData, GetHealthResponses, GetMetricsData, GetMetricsResponses, GetObserverFilesystemData, GetObserverFilesystemError, GetObserverFilesystemErrors, GetObserverFilesystemResponses, GetObserverLockData, GetObserverLockError, GetObserverLockErrors, GetObserverLockResponses, GetObserverModelsData, GetObserverModelsError, GetObserverModelsErrors, GetObserverModelsResponses, GetObserverQueueData, GetObserverQueueError, GetObserverQueueErrors, GetObserverQueueResponses, GetObserverRetrievalData, GetObserverRetrievalError, GetObserverRetrievalErrors, GetObserverRetrievalResponses, GetObserverSystemData, GetObserverSystemError, GetObserverSystemErrors, GetObserverSystemResponses, GetObserverVikingdbData, GetObserverVikingdbError, GetObserverVikingdbErrors, GetObserverVikingdbResponses, GetPrivacyConfigsByCategoryAndTargetKeyData, GetPrivacyConfigsByCategoryAndTargetKeyError, GetPrivacyConfigsByCategoryAndTargetKeyErrors, GetPrivacyConfigsByCategoryAndTargetKeyResponses, GetPrivacyConfigsByCategoryData, GetPrivacyConfigsByCategoryError, GetPrivacyConfigsByCategoryErrors, GetPrivacyConfigsByCategoryResponses, GetPrivacyConfigsData, GetPrivacyConfigsError, GetPrivacyConfigsErrors, GetPrivacyConfigsResponses, GetPrivacyConfigsVersionByCategoryAndTargetKeyAndVersionData, GetPrivacyConfigsVersionByCategoryAndTargetKeyAndVersionError, GetPrivacyConfigsVersionByCategoryAndTargetKeyAndVersionErrors, GetPrivacyConfigsVersionByCategoryAndTargetKeyAndVersionResponses, GetPrivacyConfigsVersionsByCategoryAndTargetKeyData, GetPrivacyConfigsVersionsByCategoryAndTargetKeyError, GetPrivacyConfigsVersionsByCategoryAndTargetKeyErrors, GetPrivacyConfigsVersionsByCategoryAndTargetKeyResponses, GetReadyData, GetReadyResponses, GetRelationsData, GetRelationsError, GetRelationsErrors, GetRelationsResponses, GetSessionBySessionIdData, GetSessionBySessionIdError, GetSessionBySessionIdErrors, GetSessionBySessionIdResponses, GetSessionIdArchiveByArchiveIdData, GetSessionIdArchiveByArchiveIdError, GetSessionIdArchiveByArchiveIdErrors, GetSessionIdArchiveByArchiveIdResponses, GetSessionIdContextData, GetSessionIdContextError, GetSessionIdContextErrors, GetSessionIdContextResponses, GetSessionsData, GetSessionsError, GetSessionsErrors, GetSessionsResponses, GetStatsMemoriesData, GetStatsMemoriesError, GetStatsMemoriesErrors, GetStatsMemoriesResponses, GetStatsSessionBySessionIdData, GetStatsSessionBySessionIdError, GetStatsSessionBySessionIdErrors, GetStatsSessionBySessionIdResponses, GetSystemStatusData, GetSystemStatusError, GetSystemStatusErrors, GetSystemStatusResponses, GetTaskByTaskIdData, GetTaskByTaskIdError, GetTaskByTaskIdErrors, GetTaskByTaskIdResponses, GetTasksData, GetTasksError, GetTasksErrors, GetTasksResponses, GetWebdavResourceByResourcePathData, GetWebdavResourceByResourcePathError, GetWebdavResourceByResourcePathErrors, GetWebdavResourceByResourcePathResponses, GetWebdavResourcesData, GetWebdavResourcesError, GetWebdavResourcesErrors, GetWebdavResourcesResponses, GlobRequest, GrepRequest, HeadWebdavResourceByResourcePathData, HeadWebdavResourceByResourcePathError, HeadWebdavResourceByResourcePathErrors, HeadWebdavResourceByResourcePathResponses, HeadWebdavResourcesData, HeadWebdavResourcesError, HeadWebdavResourcesErrors, HeadWebdavResourcesResponses, HttpValidationError, ImportRequest, LinkRequest, MkdirRequest, MvRequest, OptionsWebdavResourceByResourcePathData, OptionsWebdavResourceByResourcePathError, OptionsWebdavResourceByResourcePathErrors, OptionsWebdavResourceByResourcePathResponses, OptionsWebdavResourcesData, OptionsWebdavResourcesError, OptionsWebdavResourcesErrors, OptionsWebdavResourcesResponses, PostAdminAccountIdUserIdKeyData, PostAdminAccountIdUserIdKeyError, PostAdminAccountIdUserIdKeyErrors, PostAdminAccountIdUserIdKeyResponses, PostAdminAccountIdUsersData, PostAdminAccountIdUsersError, PostAdminAccountIdUsersErrors, PostAdminAccountIdUsersResponses, PostAdminAccountsData, PostAdminAccountsError, PostAdminAccountsErrors, PostAdminAccountsResponses, PostBotV1ChatData, PostBotV1ChatError, PostBotV1ChatErrors, PostBotV1ChatResponses, PostBotV1ChatStreamData, PostBotV1ChatStreamError, PostBotV1ChatStreamErrors, PostBotV1ChatStreamResponses, PostBotV1FeedbackData, PostBotV1FeedbackError, PostBotV1FeedbackErrors, PostBotV1FeedbackResponses, PostContentReindexData, PostContentReindexError, PostContentReindexErrors, PostContentReindexResponses, PostContentWriteData, PostContentWriteError, PostContentWriteErrors, PostContentWriteResponses, PostFsMkdirData, PostFsMkdirError, PostFsMkdirErrors, PostFsMkdirResponses, PostFsMvData, PostFsMvError, PostFsMvErrors, PostFsMvResponses, PostPackBackupData, PostPackBackupError, PostPackBackupErrors, PostPackBackupResponses, PostPackExportData, PostPackExportError, PostPackExportErrors, PostPackExportResponses, PostPackImportData, PostPackImportError, PostPackImportErrors, PostPackImportResponses, PostPackRestoreData, PostPackRestoreError, PostPackRestoreErrors, PostPackRestoreResponses, PostPrivacyConfigsActivateByCategoryAndTargetKeyData, PostPrivacyConfigsActivateByCategoryAndTargetKeyError, PostPrivacyConfigsActivateByCategoryAndTargetKeyErrors, PostPrivacyConfigsActivateByCategoryAndTargetKeyResponses, PostPrivacyConfigsByCategoryAndTargetKeyData, PostPrivacyConfigsByCategoryAndTargetKeyError, PostPrivacyConfigsByCategoryAndTargetKeyErrors, PostPrivacyConfigsByCategoryAndTargetKeyResponses, PostRelationsLinkData, PostRelationsLinkError, PostRelationsLinkErrors, PostRelationsLinkResponses, PostResourcesData, PostResourcesError, PostResourcesErrors, PostResourcesResponses, PostResourcesTempUploadData, PostResourcesTempUploadError, PostResourcesTempUploadErrors, PostResourcesTempUploadResponses, PostSearchFindData, PostSearchFindError, PostSearchFindErrors, PostSearchFindResponses, PostSearchGlobData, PostSearchGlobError, PostSearchGlobErrors, PostSearchGlobResponses, PostSearchGrepData, PostSearchGrepError, PostSearchGrepErrors, PostSearchGrepResponses, PostSearchSearchData, PostSearchSearchError, PostSearchSearchErrors, PostSearchSearchResponses, PostSessionIdCommitData, PostSessionIdCommitError, PostSessionIdCommitErrors, PostSessionIdCommitResponses, PostSessionIdExtractData, PostSessionIdExtractError, PostSessionIdExtractErrors, PostSessionIdExtractResponses, PostSessionIdMessagesData, PostSessionIdMessagesError, PostSessionIdMessagesErrors, PostSessionIdMessagesResponses, PostSessionIdUsedData, PostSessionIdUsedError, PostSessionIdUsedErrors, PostSessionIdUsedResponses, PostSessionsData, PostSessionsError, PostSessionsErrors, PostSessionsResponses, PostSkillsData, PostSkillsError, PostSkillsErrors, PostSkillsResponses, PostSystemConsistencyData, PostSystemConsistencyError, PostSystemConsistencyErrors, PostSystemConsistencyResponses, PostSystemWaitData, PostSystemWaitError, PostSystemWaitErrors, PostSystemWaitResponses, PutAdminAccountIdUserIdRoleData, PutAdminAccountIdUserIdRoleError, PutAdminAccountIdUserIdRoleErrors, PutAdminAccountIdUserIdRoleResponses, PutWebdavResourceByResourcePathData, PutWebdavResourceByResourcePathError, PutWebdavResourceByResourcePathErrors, PutWebdavResourceByResourcePathResponses, PutWebdavResourcesData, PutWebdavResourcesError, PutWebdavResourcesErrors, PutWebdavResourcesResponses, RegisterUserRequest, ReindexRequest, RestoreRequest, SearchRequest, SetRoleRequest, UnlinkRequest, UpsertPrivacyConfigRequest, UsedRequest, ValidationError, WaitRequest, WriteContentRequest } from './types.gen';diff --git a/web-studio/src/gen/ov-client/sdk.gen.ts b/web-studio/src/gen/ov-client/sdk.gen.tsindex a30d29794..8fd54b3c5 100644--- a/web-studio/src/gen/ov-client/sdk.gen.ts+++ b/web-studio/src/gen/ov-client/sdk.gen.ts@@ -2,7 +2,7 @@import { type Client, formDataBodySerializer, type Options as Options2, type TDataShape } from './client';import { client } from './client.gen';-import type { DeleteAdminAccountByAccountIdData, DeleteAdminAccountByAccountIdErrors, DeleteAdminAccountByAccountIdResponses, DeleteAdminAccountIdUserByUserIdData, DeleteAdminAccountIdUserByUserIdErrors, DeleteAdminAccountIdUserByUserIdResponses, DeleteFsData, DeleteFsErrors, DeleteFsResponses, DeleteRelationsLinkData, DeleteRelationsLinkErrors, DeleteRelationsLinkResponses, DeleteSessionBySessionIdData, DeleteSessionBySessionIdErrors, DeleteSessionBySessionIdResponses, DeleteWebdavResourceByResourcePathData, DeleteWebdavResourceByResourcePathErrors, DeleteWebdavResourceByResourcePathResponses, DeleteWebdavResourcesData, DeleteWebdavResourcesErrors, DeleteWebdavResourcesResponses, GetAdminAccountIdAgentsData, GetAdminAccountIdAgentsErrors, GetAdminAccountIdAgentsResponses, GetAdminAccountIdUsersData, GetAdminAccountIdUsersErrors, GetAdminAccountIdUsersResponses, GetAdminAccountsData, GetAdminAccountsErrors, GetAdminAccountsResponses, GetBotV1HealthData, GetBotV1HealthResponses, GetConsoleAuditData, GetConsoleAuditErrors, GetConsoleAuditResponses, GetConsoleContextCommitsData, GetConsoleContextCommitsErrors, GetConsoleContextCommitsResponses, GetConsoleDashboardSummaryData, GetConsoleDashboardSummaryErrors, GetConsoleDashboardSummaryResponses, GetConsoleTokensData, GetConsoleTokensErrors, GetConsoleTokensResponses, GetContentAbstractData, GetContentAbstractErrors, GetContentAbstractResponses, GetContentDownloadData, GetContentDownloadErrors, GetContentDownloadResponses, GetContentOverviewData, GetContentOverviewErrors, GetContentOverviewResponses, GetContentReadData, GetContentReadErrors, GetContentReadResponses, GetDebugHealthData, GetDebugHealthErrors, GetDebugHealthResponses, GetDebugVectorCountData, GetDebugVectorCountErrors, GetDebugVectorCountResponses, GetDebugVectorScrollData, GetDebugVectorScrollErrors, GetDebugVectorScrollResponses, GetFsLsData, GetFsLsErrors, GetFsLsResponses, GetFsStatData, GetFsStatErrors, GetFsStatResponses, GetFsTreeData, GetFsTreeErrors, GetFsTreeResponses, GetHealthData, GetHealthResponses, GetMetricsData, GetMetricsResponses, GetObserverFilesystemData, GetObserverFilesystemErrors, GetObserverFilesystemResponses, GetObserverLockData, GetObserverLockErrors, GetObserverLockResponses, GetObserverModelsData, GetObserverModelsErrors, GetObserverModelsResponses, GetObserverQueueData, GetObserverQueueErrors, GetObserverQueueResponses, GetObserverRetrievalData, GetObserverRetrievalErrors, GetObserverRetrievalResponses, GetObserverSystemData, GetObserverSystemErrors, GetObserverSystemResponses, GetObserverVikingdbData, GetObserverVikingdbErrors, GetObserverVikingdbResponses, GetPrivacyConfigsByCategoryAndTargetKeyData, GetPrivacyConfigsByCategoryAndTargetKeyErrors, GetPrivacyConfigsByCategoryAndTargetKeyResponses, GetPrivacyConfigsByCategoryData, GetPrivacyConfigsByCategoryErrors, GetPrivacyConfigsByCategoryResponses, GetPrivacyConfigsData, GetPrivacyConfigsErrors, GetPrivacyConfigsResponses, GetPrivacyConfigsVersionByCategoryAndTargetKeyAndVersionData, GetPrivacyConfigsVersionByCategoryAndTargetKeyAndVersionErrors, GetPrivacyConfigsVersionByCategoryAndTargetKeyAndVersionResponses, GetPrivacyConfigsVersionsByCategoryAndTargetKeyData, GetPrivacyConfigsVersionsByCategoryAndTargetKeyErrors, GetPrivacyConfigsVersionsByCategoryAndTargetKeyResponses, GetReadyData, GetReadyResponses, GetRelationsData, GetRelationsErrors, GetRelationsResponses, GetSessionBySessionIdData, GetSessionBySessionIdErrors, GetSessionBySessionIdResponses, GetSessionIdArchiveByArchiveIdData, GetSessionIdArchiveByArchiveIdErrors, GetSessionIdArchiveByArchiveIdResponses, GetSessionIdContextData, GetSessionIdContextErrors, GetSessionIdContextResponses, GetSessionsData, GetSessionsErrors, GetSessionsResponses, GetStatsMemoriesData, GetStatsMemoriesErrors, GetStatsMemoriesResponses, GetStatsSessionBySessionIdData, GetStatsSessionBySessionIdErrors, GetStatsSessionBySessionIdResponses, GetSystemStatusData, GetSystemStatusErrors, GetSystemStatusResponses, GetTaskByTaskIdData, GetTaskByTaskIdErrors, GetTaskByTaskIdResponses, GetTasksData, GetTasksErrors, GetTasksResponses, GetWebdavResourceByResourcePathData, GetWebdavResourceByResourcePathErrors, GetWebdavResourceByResourcePathResponses, GetWebdavResourcesData, GetWebdavResourcesErrors, GetWebdavResourcesResponses, HeadWebdavResourceByResourcePathData, HeadWebdavResourceByResourcePathErrors, HeadWebdavResourceByResourcePathResponses, HeadWebdavResourcesData, HeadWebdavResourcesErrors, HeadWebdavResourcesResponses, OptionsWebdavResourceByResourcePathData, OptionsWebdavResourceByResourcePathErrors, OptionsWebdavResourceByResourcePathResponses, OptionsWebdavResourcesData, OptionsWebdavResourcesErrors, OptionsWebdavResourcesResponses, PostAdminAccountIdUserIdKeyData, PostAdminAccountIdUserIdKeyErrors, PostAdminAccountIdUserIdKeyResponses, PostAdminAccountIdUsersData, PostAdminAccountIdUsersErrors, PostAdminAccountIdUsersResponses, PostAdminAccountsData, PostAdminAccountsErrors, PostAdminAccountsResponses, PostBotV1ChatData, PostBotV1ChatErrors, PostBotV1ChatResponses, PostBotV1ChatStreamData, PostBotV1ChatStreamErrors, PostBotV1ChatStreamResponses, PostBotV1FeedbackData, PostBotV1FeedbackErrors, PostBotV1FeedbackResponses, PostContentReindexData, PostContentReindexErrors, PostContentReindexResponses, PostContentWriteData, PostContentWriteErrors, PostContentWriteResponses, PostFsMkdirData, PostFsMkdirErrors, PostFsMkdirResponses, PostFsMvData, PostFsMvErrors, PostFsMvResponses, PostPackBackupData, PostPackBackupErrors, PostPackBackupResponses, PostPackExportData, PostPackExportErrors, PostPackExportResponses, PostPackImportData, PostPackImportErrors, PostPackImportResponses, PostPackRestoreData, PostPackRestoreErrors, PostPackRestoreResponses, PostPrivacyConfigsActivateByCategoryAndTargetKeyData, PostPrivacyConfigsActivateByCategoryAndTargetKeyErrors, PostPrivacyConfigsActivateByCategoryAndTargetKeyResponses, PostPrivacyConfigsByCategoryAndTargetKeyData, PostPrivacyConfigsByCategoryAndTargetKeyErrors, PostPrivacyConfigsByCategoryAndTargetKeyResponses, PostRelationsLinkData, PostRelationsLinkErrors, PostRelationsLinkResponses, PostResourcesData, PostResourcesErrors, PostResourcesResponses, PostResourcesTempUploadData, PostResourcesTempUploadErrors, PostResourcesTempUploadResponses, PostSearchFindData, PostSearchFindErrors, PostSearchFindResponses, PostSearchGlobData, PostSearchGlobErrors, PostSearchGlobResponses, PostSearchGrepData, PostSearchGrepErrors, PostSearchGrepResponses, PostSearchSearchData, PostSearchSearchErrors, PostSearchSearchResponses, PostSessionIdCommitData, PostSessionIdCommitErrors, PostSessionIdCommitResponses, PostSessionIdExtractData, PostSessionIdExtractErrors, PostSessionIdExtractResponses, PostSessionIdMessagesData, PostSessionIdMessagesErrors, PostSessionIdMessagesResponses, PostSessionIdUsedData, PostSessionIdUsedErrors, PostSessionIdUsedResponses, PostSessionsData, PostSessionsErrors, PostSessionsResponses, PostSkillsData, PostSkillsErrors, PostSkillsResponses, PostSystemConsistencyData, PostSystemConsistencyErrors, PostSystemConsistencyResponses, PostSystemWaitData, PostSystemWaitErrors, PostSystemWaitResponses, PutAdminAccountIdUserIdRoleData, PutAdminAccountIdUserIdRoleErrors, PutAdminAccountIdUserIdRoleResponses, PutWebdavResourceByResourcePathData, PutWebdavResourceByResourcePathErrors, PutWebdavResourceByResourcePathResponses, PutWebdavResourcesData, PutWebdavResourcesErrors, PutWebdavResourcesResponses } from './types.gen';+import type { DeleteAdminAccountByAccountIdData, DeleteAdminAccountByAccountIdErrors, DeleteAdminAccountByAccountIdResponses, DeleteAdminAccountIdUserByUserIdData, DeleteAdminAccountIdUserByUserIdErrors, DeleteAdminAccountIdUserByUserIdResponses, DeleteFsData, DeleteFsErrors, DeleteFsResponses, DeleteRelationsLinkData, DeleteRelationsLinkErrors, DeleteRelationsLinkResponses, DeleteSessionBySessionIdData, DeleteSessionBySessionIdErrors, DeleteSessionBySessionIdResponses, DeleteWebdavResourceByResourcePathData, DeleteWebdavResourceByResourcePathErrors, DeleteWebdavResourceByResourcePathResponses, DeleteWebdavResourcesData, DeleteWebdavResourcesErrors, DeleteWebdavResourcesResponsess, GetAdminAccountIdUsersData, GetAdminAccountIdUsersErrors, GetAdminAccountIdUsersResponses, GetAdminAccountsData, GetAdminAccountsErrors, GetAdminAccountsResponses, GetBotV1HealthData, GetBotV1HealthResponses, GetConsoleAuditData, GetConsoleAuditErrors, GetConsoleAuditResponses, GetConsoleContextCommitsData, GetConsoleContextCommitsErrors, GetConsoleContextCommitsResponses, GetConsoleDashboardSummaryData, GetConsoleDashboardSummaryErrors, GetConsoleDashboardSummaryResponses, GetConsoleTokensData, GetConsoleTokensErrors, GetConsoleTokensResponses, GetContentAbstractData, GetContentAbstractErrors, GetContentAbstractResponses, GetContentDownloadData, GetContentDownloadErrors, GetContentDownloadResponses, GetContentOverviewData, GetContentOverviewErrors, GetContentOverviewResponses, GetContentReadData, GetContentReadErrors, GetContentReadResponses, GetDebugHealthData, GetDebugHealthErrors, GetDebugHealthResponses, GetDebugVectorCountData, GetDebugVectorCountErrors, GetDebugVectorCountResponses, GetDebugVectorScrollData, GetDebugVectorScrollErrors, GetDebugVectorScrollResponses, GetFsLsData, GetFsLsErrors, GetFsLsResponses, GetFsStatData, GetFsStatErrors, GetFsStatResponses, GetFsTreeData, GetFsTreeErrors, GetFsTreeResponses, GetHealthData, GetHealthResponses, GetMetricsData, GetMetricsResponses, GetObserverFilesystemData, GetObserverFilesystemErrors, GetObserverFilesystemResponses, GetObserverLockData, GetObserverLockErrors, GetObserverLockResponses, GetObserverModelsData, GetObserverModelsErrors, GetObserverModelsResponses, GetObserverQueueData, GetObserverQueueErrors, GetObserverQueueResponses, GetObserverRetrievalData, GetObserverRetrievalErrors, GetObserverRetrievalResponses, GetObserverSystemData, GetObserverSystemErrors, GetObserverSystemResponses, GetObserverVikingdbData, GetObserverVikingdbErrors, GetObserverVikingdbResponses, GetPrivacyConfigsByCategoryAndTargetKeyData, GetPrivacyConfigsByCategoryAndTargetKeyErrors, GetPrivacyConfigsByCategoryAndTargetKeyResponses, GetPrivacyConfigsByCategoryData, GetPrivacyConfigsByCategoryErrors, GetPrivacyConfigsByCategoryResponses, GetPrivacyConfigsData, GetPrivacyConfigsErrors, GetPrivacyConfigsResponses, GetPrivacyConfigsVersionByCategoryAndTargetKeyAndVersionData, GetPrivacyConfigsVersionByCategoryAndTargetKeyAndVersionErrors, GetPrivacyConfigsVersionByCategoryAndTargetKeyAndVersionResponses, GetPrivacyConfigsVersionsByCategoryAndTargetKeyData, GetPrivacyConfigsVersionsByCategoryAndTargetKeyErrors, GetPrivacyConfigsVersionsByCategoryAndTargetKeyResponses, GetReadyData, GetReadyResponses, GetRelationsData, GetRelationsErrors, GetRelationsResponses, GetSessionBySessionIdData, GetSessionBySessionIdErrors, GetSessionBySessionIdResponses, GetSessionIdArchiveByArchiveIdData, GetSessionIdArchiveByArchiveIdErrors, GetSessionIdArchiveByArchiveIdResponses, GetSessionIdContextData, GetSessionIdContextErrors, GetSessionIdContextResponses, GetSessionsData, GetSessionsErrors, GetSessionsResponses, GetStatsMemoriesData, GetStatsMemoriesErrors, GetStatsMemoriesResponses, GetStatsSessionBySessionIdData, GetStatsSessionBySessionIdErrors, GetStatsSessionBySessionIdResponses, GetSystemStatusData, GetSystemStatusErrors, GetSystemStatusResponses, GetTaskByTaskIdData, GetTaskByTaskIdErrors, GetTaskByTaskIdResponses, GetTasksData, GetTasksErrors, GetTasksResponses, GetWebdavResourceByResourcePathData, GetWebdavResourceByResourcePathErrors, GetWebdavResourceByResourcePathResponses, GetWebdavResourcesData, GetWebdavResourcesErrors, GetWebdavResourcesResponses, HeadWebdavResourceByResourcePathData, HeadWebdavResourceByResourcePathErrors, HeadWebdavResourceByResourcePathResponses, HeadWebdavResourcesData, HeadWebdavResourcesErrors, HeadWebdavResourcesResponses, OptionsWebdavResourceByResourcePathData, OptionsWebdavResourceByResourcePathErrors, OptionsWebdavResourceByResourcePathResponses, OptionsWebdavResourcesData, OptionsWebdavResourcesErrors, OptionsWebdavResourcesResponses, PostAdminAccountIdUserIdKeyData, PostAdminAccountIdUserIdKeyErrors, PostAdminAccountIdUserIdKeyResponses, PostAdminAccountIdUsersData, PostAdminAccountIdUsersErrors, PostAdminAccountIdUsersResponses, PostAdminAccountsData, PostAdminAccountsErrors, PostAdminAccountsResponses, PostBotV1ChatData, PostBotV1ChatErrors, PostBotV1ChatResponses, PostBotV1ChatStreamData, PostBotV1ChatStreamErrors, PostBotV1ChatStreamResponses, PostBotV1FeedbackData, PostBotV1FeedbackErrors, PostBotV1FeedbackResponses, PostContentReindexData, PostContentReindexErrors, PostContentReindexResponses, PostContentWriteData, PostContentWriteErrors, PostContentWriteResponses, PostFsMkdirData, PostFsMkdirErrors, PostFsMkdirResponses, PostFsMvData, PostFsMvErrors, PostFsMvResponses, PostPackBackupData, PostPackBackupErrors, PostPackBackupResponses, PostPackExportData, PostPackExportErrors, PostPackExportResponses, PostPackImportData, PostPackImportErrors, PostPackImportResponses, PostPackRestoreData, PostPackRestoreErrors, PostPackRestoreResponses, PostPrivacyConfigsActivateByCategoryAndTargetKeyData, PostPrivacyConfigsActivateByCategoryAndTargetKeyErrors, PostPrivacyConfigsActivateByCategoryAndTargetKeyResponses, PostPrivacyConfigsByCategoryAndTargetKeyData, PostPrivacyConfigsByCategoryAndTargetKeyErrors, PostPrivacyConfigsByCategoryAndTargetKeyResponses, PostRelationsLinkData, PostRelationsLinkErrors, PostRelationsLinkResponses, PostResourcesData, PostResourcesErrors, PostResourcesResponses, PostResourcesTempUploadData, PostResourcesTempUploadErrors, PostResourcesTempUploadResponses, PostSearchFindData, PostSearchFindErrors, PostSearchFindResponses, PostSearchGlobData, PostSearchGlobErrors, PostSearchGlobResponses, PostSearchGrepData, PostSearchGrepErrors, PostSearchGrepResponses, PostSearchSearchData, PostSearchSearchErrors, PostSearchSearchResponses, PostSessionIdCommitData, PostSessionIdCommitErrors, PostSessionIdCommitResponses, PostSessionIdExtractData, PostSessionIdExtractErrors, PostSessionIdExtractResponses, PostSessionIdMessagesData, PostSessionIdMessagesErrors, PostSessionIdMessagesResponses, PostSessionIdUsedData, PostSessionIdUsedErrors, PostSessionIdUsedResponses, PostSessionsData, PostSessionsErrors, PostSessionsResponses, PostSkillsData, PostSkillsErrors, PostSkillsResponses, PostSystemConsistencyData, PostSystemConsistencyErrors, PostSystemConsistencyResponses, PostSystemWaitData, PostSystemWaitErrors, PostSystemWaitResponses, PutAdminAccountIdUserIdRoleData, PutAdminAccountIdUserIdRoleErrors, PutAdminAccountIdUserIdRoleResponses, PutWebdavResourceByResourcePathData, PutWebdavResourceByResourcePathErrors, PutWebdavResourceByResourcePathResponses, PutWebdavResourcesData, PutWebdavResourcesErrors, PutWebdavResourcesResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -151,17 +151,6 @@ export const postAdminAccountIdUsers = <ThrowOnError extends boolean = false>(op}});-/**- * List Agents- *- * List agent namespaces that have data under an account.- */-export const getAdminAccountIdAgents = <ThrowOnError extends boolean = false>(options: Options<GetAdminAccountIdAgentsData, ThrowOnError>) => (options.client ?? client).get<GetAdminAccountIdAgentsResponses, GetAdminAccountIdAgentsErrors, ThrowOnError>({- responseType: 'json',- url: '/api/v1/admin/accounts/{account_id}/agents',- ...options-});-/*** Remove User*diff --git a/web-studio/src/gen/ov-client/types.gen.ts b/web-studio/src/gen/ov-client/types.gen.tsindex b91e12b36..b6a848810 100644--- a/web-studio/src/gen/ov-client/types.gen.ts+++ b/web-studio/src/gen/ov-client/types.gen.ts@@ -31,9 +31,9 @@ export type AddMessageRequest = {*/role: string;/**- * Role Id+ * Peer Id*/- role_id?: string | null;+ peer_id?: string | null;/*** Content*/@@ -289,14 +289,6 @@ export type CreateAccountRequest = {* Admin User Id*/admin_user_id: string;- /**- * Isolate User Scope By Agent- */- isolate_user_scope_by_agent?: boolean;- /**- * Isolate Agent Scope By User- */- isolate_agent_scope_by_user?: boolean;};/**@@ -347,6 +339,10 @@ export type FindRequest = {* Target Uri*/target_uri?: string | Array<string>;+ /**+ * Peer Id+ */+ peer_id?: string | null;/*** Limit*/@@ -602,6 +598,10 @@ export type SearchRequest = {* Target Uri*/target_uri?: string | Array<string>;+ /**+ * Peer Id+ */+ peer_id?: string | null;/*** Session Id*/@@ -842,7 +842,6 @@ export type GetSystemStatusData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -887,7 +886,6 @@ export type PostSystemWaitData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -932,7 +930,6 @@ export type PostSystemConsistencyData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -977,7 +974,6 @@ export type GetAdminAccountsData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -1022,7 +1018,6 @@ export type PostAdminAccountsData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -1067,7 +1062,6 @@ export type DeleteAdminAccountByAccountIdData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -1119,7 +1113,6 @@ export type GetAdminAccountIdUsersData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -1184,7 +1177,6 @@ export type PostAdminAccountIdUsersData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -1214,58 +1206,6 @@ export type PostAdminAccountIdUsersResponses = {200: unknown;};-export type GetAdminAccountIdAgentsData = {- body?: never;- headers?: {- /**- * X-Api-Key- */- 'x-api-key'?: string | null;- /**- * Authorization- */- authorization?: string | null;- /**- * X-Openviking-Account- */- 'X-OpenViking-Account'?: string | null;- /**- * X-Openviking-User- */- 'X-OpenViking-User'?: string | null;- /**- * X-Openviking-Agent- */- 'X-OpenViking-Agent'?: string | null;- };- path: {- /**- * Account Id- *- * Account ID- */- account_id: string;- };- query?: never;- url: '/api/v1/admin/accounts/{account_id}/agents';-};--export type GetAdminAccountIdAgentsErrors = {- /**- * Validation Error- */- 422: HttpValidationError;-};--export type GetAdminAccountIdAgentsError = GetAdminAccountIdAgentsErrors[keyof GetAdminAccountIdAgentsErrors];--export type GetAdminAccountIdAgentsResponses = {- /**- * Successful Response- */- 200: unknown;-};-export type DeleteAdminAccountIdUserByUserIdData = {body?: never;headers?: {@@ -1288,7 +1228,6 @@ export type DeleteAdminAccountIdUserByUserIdData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -1346,7 +1285,6 @@ export type PutAdminAccountIdUserIdRoleData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -1404,7 +1342,6 @@ export type PostAdminAccountIdUserIdKeyData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -1462,7 +1399,6 @@ export type PostResourcesTempUploadData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -1507,7 +1443,6 @@ export type PostResourcesData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -1552,7 +1487,6 @@ export type PostSkillsData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -1597,7 +1531,6 @@ export type GetFsLsData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query: {@@ -1691,7 +1624,6 @@ export type GetFsTreeData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query: {@@ -1779,7 +1711,6 @@ export type GetFsStatData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query: {@@ -1831,7 +1762,6 @@ export type PostFsMkdirData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -1876,7 +1806,6 @@ export type DeleteFsData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query: {@@ -1934,7 +1863,6 @@ export type PostFsMvData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -1979,7 +1907,6 @@ export type GetContentReadData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query: {@@ -2043,7 +1970,6 @@ export type GetContentAbstractData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query: {@@ -2095,7 +2021,6 @@ export type GetContentOverviewData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query: {@@ -2147,7 +2072,6 @@ export type GetContentDownloadData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query: {@@ -2199,7 +2123,6 @@ export type PostContentWriteData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -2244,7 +2167,6 @@ export type PostContentReindexData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -2289,7 +2211,6 @@ export type GetConsoleDashboardSummaryData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: {@@ -2341,7 +2262,6 @@ export type GetConsoleTokensData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query: {@@ -2409,7 +2329,6 @@ export type GetConsoleContextCommitsData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query: {@@ -2477,7 +2396,6 @@ export type GetConsoleAuditData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: {@@ -2543,7 +2461,6 @@ export type PostSearchFindData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -2588,7 +2505,6 @@ export type PostSearchSearchData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -2633,7 +2549,6 @@ export type PostSearchGrepData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -2678,7 +2593,6 @@ export type PostSearchGlobData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -2723,7 +2637,6 @@ export type GetRelationsData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query: {@@ -2775,7 +2688,6 @@ export type DeleteRelationsLinkData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -2820,7 +2732,6 @@ export type PostRelationsLinkData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -2865,7 +2776,6 @@ export type GetPrivacyConfigsData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -2910,7 +2820,6 @@ export type GetPrivacyConfigsByCategoryData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -2962,7 +2871,6 @@ export type GetPrivacyConfigsByCategoryAndTargetKeyData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -3020,7 +2928,6 @@ export type PostPrivacyConfigsByCategoryAndTargetKeyData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -3078,7 +2985,6 @@ export type GetPrivacyConfigsVersionsByCategoryAndTargetKeyData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -3136,7 +3042,6 @@ export type GetPrivacyConfigsVersionByCategoryAndTargetKeyAndVersionData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -3200,7 +3105,6 @@ export type PostPrivacyConfigsActivateByCategoryAndTargetKeyData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -3258,7 +3162,6 @@ export type GetSessionsData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -3303,7 +3206,6 @@ export type PostSessionsData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -3348,7 +3250,6 @@ export type DeleteSessionBySessionIdData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -3400,7 +3301,6 @@ export type GetSessionBySessionIdData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -3459,7 +3359,6 @@ export type GetSessionIdContextData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -3518,7 +3417,6 @@ export type GetSessionIdArchiveByArchiveIdData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -3576,7 +3474,6 @@ export type PostSessionIdCommitData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -3628,7 +3525,6 @@ export type PostSessionIdExtractData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -3680,7 +3576,6 @@ export type PostSessionIdMessagesData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -3732,7 +3627,6 @@ export type PostSessionIdUsedData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -3784,7 +3678,6 @@ export type GetStatsMemoriesData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: {@@ -3836,7 +3729,6 @@ export type GetStatsSessionBySessionIdData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -3888,7 +3780,6 @@ export type PostPackExportData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -3936,7 +3827,6 @@ export type PostPackBackupData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -3981,7 +3871,6 @@ export type PostPackImportData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -4026,7 +3915,6 @@ export type PostPackRestoreData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -4071,7 +3959,6 @@ export type GetDebugHealthData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -4116,7 +4003,6 @@ export type GetDebugVectorScrollData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: {@@ -4174,7 +4060,6 @@ export type GetDebugVectorCountData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: {@@ -4228,7 +4113,6 @@ export type GetObserverQueueData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -4273,7 +4157,6 @@ export type GetObserverVikingdbData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -4318,7 +4201,6 @@ export type GetObserverModelsData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -4363,7 +4245,6 @@ export type GetObserverLockData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -4408,7 +4289,6 @@ export type GetObserverRetrievalData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -4453,7 +4333,6 @@ export type GetObserverFilesystemData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -4498,7 +4377,6 @@ export type GetObserverSystemData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -4557,7 +4435,6 @@ export type GetTaskByTaskIdData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -4607,7 +4484,6 @@ export type GetTasksData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: {@@ -4677,7 +4553,6 @@ export type DeleteWebdavResourceByResourcePathData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -4727,7 +4602,6 @@ export type GetWebdavResourceByResourcePathData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -4777,7 +4651,6 @@ export type HeadWebdavResourceByResourcePathData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -4855,7 +4728,6 @@ export type PutWebdavResourceByResourcePathData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path: {/**@@ -4905,7 +4777,6 @@ export type DeleteWebdavResourcesData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: {@@ -4955,7 +4826,6 @@ export type GetWebdavResourcesData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: {@@ -5005,7 +4875,6 @@ export type HeadWebdavResourcesData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: {@@ -5083,7 +4952,6 @@ export type PutWebdavResourcesData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: {@@ -5147,7 +5015,6 @@ export type PostBotV1ChatData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -5192,7 +5059,6 @@ export type PostBotV1FeedbackData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;@@ -5237,7 +5103,6 @@ export type PostBotV1ChatStreamData = {/*** X-Openviking-Agent*/- 'X-OpenViking-Agent'?: string | null;};path?: never;query?: never;diff --git a/web-studio/src/hooks/use-app-connection.tsx b/web-studio/src/hooks/use-app-connection.tsxindex 7f2fbce96..ac5948927 100644--- a/web-studio/src/hooks/use-app-connection.tsx+++ b/web-studio/src/hooks/use-app-connection.tsx@@ -8,7 +8,6 @@ import type { ServerMode } from './use-server-mode'export type ConnectionDraft = {accountId: string- agentId: stringapiKey: stringbaseUrl: stringuserId: string@@ -44,10 +43,6 @@ const ENV_ACCOUNT =typeof import.meta.env.VITE_OV_ACCOUNT === 'string'? import.meta.env.VITE_OV_ACCOUNT.trim(): ''-const ENV_AGENT =- typeof import.meta.env.VITE_OV_AGENT === 'string'- ? import.meta.env.VITE_OV_AGENT.trim()- : ''const ENV_USER =typeof import.meta.env.VITE_OV_USER === 'string'? import.meta.env.VITE_OV_USER.trim()@@ -55,7 +50,6 @@ const ENV_USER =const DEFAULT_CONNECTION: ConnectionDraft = {accountId: ENV_ACCOUNT || 'default',- agentId: ENV_AGENT || 'web-playground',apiKey: ENV_API_KEY,baseUrl: ovClient.getOptions().baseUrl,userId: ENV_USER || 'default',@@ -107,7 +101,6 @@ function normalizeConnectionDraft(): ConnectionDraft {return {accountId: connection.accountId.trim(),- agentId: connection.agentId.trim() || DEFAULT_CONNECTION.agentId,apiKey: connection.apiKey.trim(),baseUrl: normalizeBaseUrl(connection.baseUrl),userId: connection.userId.trim(),@@ -131,7 +124,6 @@ function applyConnection(connection: ConnectionDraft): void {})ovClient.setConnection({accountId: connection.accountId,- agentId: connection.agentId,apiKey: connection.apiKey,userId: connection.userId,})@@ -152,8 +144,6 @@ function readInitialConnection(): ConnectionDraft {storedConnection.accountId,DEFAULT_CONNECTION.accountId,),- agentId:- ENV_AGENT || storedConnection.agentId || DEFAULT_CONNECTION.agentId,apiKey,baseUrl:ENV_BASE_URL || storedConnection.baseUrl || DEFAULT_CONNECTION.baseUrl,@@ -176,7 +166,6 @@ export function summarizeConnectionIdentity(const segments = [connection.accountId,connection.userId,- connection.agentId,].filter(Boolean)if (!segments.length) {return { labelKey: 'identitySummary.unset' }diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.tsindex b84673f63..ee6d29150 100644--- a/web-studio/src/i18n/locales/en.ts+++ b/web-studio/src/i18n/locales/en.ts@@ -80,10 +80,6 @@ const en = {label: 'Account',placeholder: 'default',},- agentId: {- label: 'Agent',- placeholder: 'web-playground',- },apiKey: {label: 'API Key',placeholder: 'Enter X-API-Key or Bearer token',@@ -160,7 +156,6 @@ const en = {fields: {account: 'Account',adminUser: 'Admin user',- agent: 'Agent',apiKey: 'API key',baseUrl: 'Server URL',role: 'Role',@@ -186,7 +181,6 @@ const en = {},placeholders: {account: 'team-account',- agent: 'web-playground',apiKey: 'Enter X-API-Key or Bearer token',baseUrl: 'http://127.0.0.1:1933',user: 'default',@@ -231,12 +225,6 @@ const en = {},},home: {- agentAccess: {- description:- 'Deduplicates agents that accessed OpenViking today and shows the latest visit time.',- empty: 'No agent visits today',- title: 'Agent Visits',- },contextCommits: {description:'Groups resource, skill, session message, and session commit writes into 4-hour buckets. Hover a cell for details.',@@ -271,7 +259,7 @@ const en = {},contextData: {description:- 'Includes files, skills, user memories, and agent memories to show the current context resource scale.',+ 'Includes files, skills, and user memories to show the current context resource scale.',files: 'Files',memories: 'Memories',skills: 'Skills',@@ -798,7 +786,6 @@ const en = {namespaces: {user: 'Personalized user memories',session: 'Raw sessions between the user and the Agent',- agent: "The Agent's capabilities, tools and experience",resources: 'External resources the Agent can reference',},},diff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.tsindex 823224eaf..c7fc9e821 100644--- a/web-studio/src/i18n/locales/zh-CN.ts+++ b/web-studio/src/i18n/locales/zh-CN.ts@@ -80,10 +80,6 @@ const zhCN = {label: 'Account',placeholder: 'default',},- agentId: {- label: 'Agent',- placeholder: 'web-playground',- },apiKey: {label: 'API Key',placeholder: '输入 X-API-Key 或 Bearer token',@@ -160,7 +156,6 @@ const zhCN = {fields: {account: 'Account',adminUser: 'Admin user',- agent: 'Agent',apiKey: 'API key',baseUrl: '服务地址',role: '角色',@@ -186,7 +181,6 @@ const zhCN = {},placeholders: {account: 'team-account',- agent: 'web-playground',apiKey: '输入 X-API-Key 或 Bearer token',baseUrl: 'http://127.0.0.1:1933',user: 'default',@@ -231,12 +225,6 @@ const zhCN = {},},home: {- agentAccess: {- description:- '去重统计今日访问过 OpenViking 的 Agent,并展示最近访问时间。',- empty: '今日暂无 Agent 访问',- title: 'Agent 访问数',- },contextCommits: {description:'按 4 小时聚合资源、技能、会话消息和提交写入,鼠标悬停可查看明细。',@@ -271,7 +259,7 @@ const zhCN = {},contextData: {description:- '包含文件、技能、用户记忆与 Agent 记忆,用于衡量当前上下文资源规模。',+ '包含文件、技能与用户记忆,用于衡量当前上下文资源规模。',files: '文件',memories: '记忆',skills: '技能',@@ -780,7 +768,6 @@ const zhCN = {namespaces: {user: '用户个性化记忆',session: '用户与 Agent 的原始会话',- agent: 'Agent 的能力、工具和经验',resources: 'Agent 可引用的外部资源',},},diff --git a/web-studio/src/lib/ov-client/client.ts b/web-studio/src/lib/ov-client/client.tsindex a169fa44f..0a7ca7b17 100644--- a/web-studio/src/lib/ov-client/client.ts+++ b/web-studio/src/lib/ov-client/client.ts@@ -19,7 +19,6 @@ const DEFAULT_TELEMETRY_PATHS = new Set(['/api/v1/resources',])const SESSION_COMMIT_PATH = /^\/api\/v1\/sessions\/[^/]+\/commit$/-const WEB_PLAYGROUND_AGENT_ID = 'web-playground'function isBrowser(): boolean {return typeof window !== 'undefined'@@ -157,7 +156,6 @@ export function createOvClient(options: OvClientOptions = {}): OvClientAdapter {options.connection?.apiKey ??readSessionStorage(runtimeOptions.apiKeyStorageKey),accountId: options.connection?.accountId ?? '',- agentId: options.connection?.agentId ?? WEB_PLAYGROUND_AGENT_ID,userId: options.connection?.userId ?? '',}@@ -180,10 +178,6 @@ export function createOvClient(options: OvClientOptions = {}): OvClientAdapter {setOptionalHeader(headers, 'X-API-Key', connection.apiKey)setOptionalHeader(headers, 'X-OpenViking-Account', connection.accountId)setOptionalHeader(headers, 'X-OpenViking-User', connection.userId)- headers.set(- 'X-OpenViking-Agent',- connection.agentId || WEB_PLAYGROUND_AGENT_ID,- )config.headers = headersmaybeInjectTelemetry(config, runtimeOptions.defaultTelemetry)@@ -256,7 +250,6 @@ export function createOvClient(options: OvClientOptions = {}): OvClientAdapter {connection = {apiKey: '',accountId: '',- agentId: WEB_PLAYGROUND_AGENT_ID,userId: '',}persistApiKey()diff --git a/web-studio/src/lib/ov-client/types.ts b/web-studio/src/lib/ov-client/types.tsindex dfea95340..04a1ad37e 100644--- a/web-studio/src/lib/ov-client/types.ts+++ b/web-studio/src/lib/ov-client/types.ts@@ -7,7 +7,6 @@ export const DEFAULT_API_KEY_STORAGE_KEY = 'ov_console_api_key'export interface OvConnectionState {apiKey: stringaccountId: string- agentId: stringuserId: string}diff --git a/web-studio/src/lib/sessions/api.ts b/web-studio/src/lib/sessions/api.tsindex 7828afb12..99b6d9e01 100644--- a/web-studio/src/lib/sessions/api.ts+++ b/web-studio/src/lib/sessions/api.ts@@ -149,7 +149,6 @@ function buildFetchHeaders(): Record<string, string> {if (conn.apiKey) headers['X-API-Key'] = conn.apiKeyif (conn.accountId) headers['X-OpenViking-Account'] = conn.accountIdif (conn.userId) headers['X-OpenViking-User'] = conn.userId- headers['X-OpenViking-Agent'] = conn.agentId || 'web-playground'return headers}diff --git a/web-studio/src/routes/home/-components/metric-panels.tsx b/web-studio/src/routes/home/-components/metric-panels.tsxindex f72332107..5d7c55d5d 100644--- a/web-studio/src/routes/home/-components/metric-panels.tsx+++ b/web-studio/src/routes/home/-components/metric-panels.tsx@@ -1,19 +1,17 @@import { useEffect, useRef } from 'react'import type { ComponentType, CSSProperties, ReactNode } from 'react'-import { Coins, Database, Search, Users } from 'lucide-react'+import { Coins, Database, Search } from 'lucide-react'import { Skeleton } from '#/components/ui/skeleton'import { HOME_ACCENT_COLORS } from '../-constants/dashboard'import type {- AgentOverview,ContextCounts,HomeT,RetrievalCounts,TokenCounts,} from '../-types/dashboard'-import { asNumber, formatNumber, formatTimestamp } from '../-lib/format'-import { normalizeAgents } from '../-lib/normalize'+import { asNumber, formatNumber } from '../-lib/format'import { DetailRow, Panel } from './panel'function parseDisplayNumber(value: string): number | null {@@ -263,54 +261,3 @@ export function TodayRetrievalsPanel({</MetricPanel>)}--export function AgentAccessPanel({- data,- disabled,- isError,- isLoading,- t,-}: {- data: AgentOverview | undefined- disabled: boolean- isError: boolean- isLoading: boolean- t: HomeT-}) {- const agents = normalizeAgents(data?.items)- const total = asNumber(data?.total)- return (- <MetricPanel- description={t('agentAccess.description')}- icon={Users}- isError={isError}- isLoading={isLoading}- title={t('agentAccess.title')}- value={isError ? t('requestFailed') : formatNumber(total)}- >- {disabled ? (- <p className="text-xs text-muted-foreground">{t('usageDisabled')}</p>- ) : agents.length === 0 ? (- <p className="text-xs text-muted-foreground">- {t('agentAccess.empty')}- </p>- ) : (- <div className="grid gap-2">- {agents.slice(0, 3).map((agent) => (- <div- key={agent.agent_id}- className="flex min-h-8 items-center justify-between gap-2 rounded-lg border border-[oklch(0.68_0.12_232/0.1)] bg-background/55 px-2.5 py-1.5 text-xs shadow-xs dark:border-white/10 dark:bg-white/[0.05]"- >- <span className="min-w-0 truncate font-medium">- {agent.agent_id}- </span>- <span className="shrink-0 tabular-nums text-muted-foreground">- {formatTimestamp(agent.last_seen_at || '')}- </span>- </div>- ))}- </div>- )}- </MetricPanel>- )-}diff --git a/web-studio/src/routes/home/-lib/normalize.ts b/web-studio/src/routes/home/-lib/normalize.tsindex 942cd4772..d2423d032 100644--- a/web-studio/src/routes/home/-lib/normalize.ts+++ b/web-studio/src/routes/home/-lib/normalize.ts@@ -3,7 +3,6 @@ import {HEATMAP_EMPTY_COLOR,} from '../-constants/dashboard'import type {- ConsoleAgentVisit,ConsoleContextCommitItem,ConsoleTokenSeriesItem,} from '@ov-server/api/v1/console'@@ -172,15 +171,3 @@ export function normalizeCommitItems(}})}--export function normalizeAgents(items: unknown): ConsoleAgentVisit[] {- return asArray(items)- .map((raw) => {- const record = asRecord(raw)- return {- agent_id: asString(record.agent_id),- last_seen_at: asString(record.last_seen_at),- }- })- .filter((item) => item.agent_id)-}diff --git a/web-studio/src/routes/home/-types/dashboard.ts b/web-studio/src/routes/home/-types/dashboard.tsindex d13c8db4e..7ac5e75f4 100644--- a/web-studio/src/routes/home/-types/dashboard.ts+++ b/web-studio/src/routes/home/-types/dashboard.ts@@ -3,8 +3,6 @@ import type { ConsoleContextCommitItem } from '@ov-server/api/v1/console'export type HomeT = (key: string, options?: Record<string, unknown>) => stringexport type {- ConsoleAgentOverview as AgentOverview,- ConsoleAgentVisit as AgentVisit,ConsoleContextCommitItem as ContextCommitItem,ConsoleContextCounts as ContextCounts,ConsoleDashboardSummaryResult as ConsoleDashboardSummary,diff --git a/web-studio/src/routes/home/route.tsx b/web-studio/src/routes/home/route.tsxindex 0b1dcf5b3..cfa054bca 100644--- a/web-studio/src/routes/home/route.tsx+++ b/web-studio/src/routes/home/route.tsx@@ -4,7 +4,6 @@ import { createFileRoute } from '@tanstack/react-router'import { ContextCommitsPanel } from './-components/context-commits-panel'import {- AgentAccessPanel,ContextDataPanel,TodayRetrievalsPanel,TodayTokensPanel,@@ -47,7 +46,7 @@ function HomePage() {return (<div className="flex flex-col gap-5 pb-8">- <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">+ <div className="grid gap-4 md:grid-cols-3"><ContextDataPaneldata={summary?.context_counts}disabled={usageDisabled}@@ -69,13 +68,6 @@ function HomePage() {isLoading={dashboard.isLoading}t={t}/>- <AgentAccessPanel- data={summary?.agent_overview}- disabled={usageDisabled}- isError={dashboard.isError}- isLoading={dashboard.isLoading}- t={t}- /></div><TokenTrendPaneldiff --git a/web-studio/src/routes/playground/-components/context-explorer.tsx b/web-studio/src/routes/playground/-components/context-explorer.tsxindex 16345d4fb..9745b7a3c 100644--- a/web-studio/src/routes/playground/-components/context-explorer.tsx+++ b/web-studio/src/routes/playground/-components/context-explorer.tsx@@ -2,7 +2,6 @@ import { useCallback, useEffect, useMemo, useRef } from 'react'import type { PointerEvent as ReactPointerEvent } from 'react'import { useTranslation } from 'react-i18next'import {- BotIcon,ChevronRightIcon,CommandIcon,FileTextIcon,@@ -74,7 +73,7 @@ export function ContextExplorerHeader({}const NAMESPACES: Array<{- descriptionKey: 'agent' | 'resources' | 'session' | 'user'+ descriptionKey: 'resources' | 'session' | 'user'icon: typeof FolderIconlabel: stringuri: string@@ -91,12 +90,6 @@ const NAMESPACES: Array<{label: 'Session',uri: 'viking://session/',},- {- descriptionKey: 'agent',- icon: BotIcon,- label: 'Agent',- uri: 'viking://agent/',- },{descriptionKey: 'resources',icon: FolderTreeIcon,diff --git a/web-studio/src/routes/resources/-components/file-preview.tsx b/web-studio/src/routes/resources/-components/file-preview.tsxindex 2b3152569..9bad5a1f0 100644--- a/web-studio/src/routes/resources/-components/file-preview.tsx+++ b/web-studio/src/routes/resources/-components/file-preview.tsx@@ -619,7 +619,7 @@ function getJsonlMessage(record: JsonlRecord): JsonlMessage {kind,label: toolResult ? 'tool-result' : role,lineNo: index + 1,- roleId: String(parsed.role_id ?? source.role_id ?? ''),+ roleId: String(parsed.peer_id ?? source.peer_id ?? ''),text,time: String(parsed.timestamp ?? parsed.created_at ?? source.created_at ?? '',diff --git a/web-studio/src/routes/resources/-components/find-palette.tsx b/web-studio/src/routes/resources/-components/find-palette.tsxindex 816e83cfe..9cfc8dda9 100644--- a/web-studio/src/routes/resources/-components/find-palette.tsx+++ b/web-studio/src/routes/resources/-components/find-palette.tsx@@ -662,4 +662,3 @@ function DirResultList({</div>)}-diff --git a/web-studio/src/routes/settings/-lib/admin.ts b/web-studio/src/routes/settings/-lib/admin.tsindex b6ae5d879..c53458472 100644--- a/web-studio/src/routes/settings/-lib/admin.ts+++ b/web-studio/src/routes/settings/-lib/admin.ts@@ -12,7 +12,6 @@ import {export type AdminConnection = {accountId: string- agentId: stringapiKey: stringbaseUrl: stringuserId: string@@ -21,8 +20,6 @@ export type AdminConnection = {export type AdminAccount = {accountId: stringcreatedAt?: string- isolateAgentScopeByUser: boolean- isolateUserScopeByAgent: booleanuserCount: number}@@ -59,10 +56,6 @@ function asString(value: unknown): string | undefined {return typeof value === 'string' ? value : undefined}-function asBoolean(value: unknown): boolean {- return value === true-}-function asNumber(value: unknown): number {return typeof value === 'number' && Number.isFinite(value) ? value : 0}@@ -85,7 +78,6 @@ function setOptionalHeader(function createAdminClient(connection: AdminConnection) {const headers: Record<string, string> = {Accept: 'application/json',- 'X-OpenViking-Agent': connection.agentId.trim() || 'web-playground',}setOptionalHeader(headers, 'X-API-Key', connection.apiKey)setOptionalHeader(headers, 'X-OpenViking-Account', connection.accountId)@@ -112,8 +104,6 @@ function normalizeAccount(value: unknown): AdminAccount | null {return {accountId,createdAt: asString(value.created_at),- isolateAgentScopeByUser: asBoolean(value.isolate_agent_scope_by_user),- isolateUserScopeByAgent: asBoolean(value.isolate_user_scope_by_agent),userCount: asNumber(value.user_count),}}diff --git a/web-studio/src/routes/settings/route.tsx b/web-studio/src/routes/settings/route.tsxindex d9bc1ea4d..be8960a29 100644--- a/web-studio/src/routes/settings/route.tsx+++ b/web-studio/src/routes/settings/route.tsx@@ -533,12 +533,11 @@ function SettingsRoute() {const adminConnection = React.useMemo<AdminConnection>(() => ({accountId: draft.accountId || DEFAULT_ACCOUNT_ID,- agentId: draft.agentId || 'web-playground',apiKey: draft.apiKey,baseUrl: draft.baseUrl,userId: draft.userId || DEFAULT_USER_ID,}),- [draft.accountId, draft.agentId, draft.apiKey, draft.baseUrl, draft.userId],+ [draft.accountId, draft.apiKey, draft.baseUrl, draft.userId],)const accountsQuery = useQuery({@@ -550,7 +549,6 @@ function SettingsRoute() {adminConnection.apiKey,adminConnection.accountId,adminConnection.userId,- adminConnection.agentId,],retry: false,})@@ -567,7 +565,6 @@ function SettingsRoute() {adminConnection.apiKey,adminConnection.accountId,adminConnection.userId,- adminConnection.agentId,selectedAccountId,],retry: false,@@ -582,7 +579,6 @@ function SettingsRoute() {adminConnection.apiKey,adminConnection.accountId,adminConnection.userId,- adminConnection.agentId,managedAccountId,],retry: false,@@ -809,21 +805,6 @@ function SettingsRoute() {/></FieldContent></Field>- <Field>- <FieldLabel htmlFor="settings-agent-id">- {t('fields.agent')}- </FieldLabel>- <FieldContent>- <Input- id="settings-agent-id"- value={draft.agentId}- onChange={(event) =>- updateDraft({ agentId: event.target.value })- }- placeholder={t('placeholders.agent')}- />- </FieldContent>- </Field></div><div className="grid gap-3"><Field>diff --git a/web-studio/types/ov-server/api/v1/console.ts b/web-studio/types/ov-server/api/v1/console.tsindex 5c9ef6026..f22418eb2 100644--- a/web-studio/types/ov-server/api/v1/console.ts+++ b/web-studio/types/ov-server/api/v1/console.ts@@ -24,18 +24,7 @@ export type ConsoleRetrievalCounts = {total?: number}-export type ConsoleAgentVisit = {- agent_id?: string- last_seen_at?: string-}--export type ConsoleAgentOverview = {- items?: ConsoleAgentVisit[]- total?: number-}-export type ConsoleDashboardSummaryResult = OvMaybeDisabled & {- agent_overview?: ConsoleAgentOverviewcontext_counts?: ConsoleContextCountstoday_retrievals?: ConsoleRetrievalCountstoday_tokens?: ConsoleTokenCounts@@ -85,7 +74,6 @@ export type ConsoleContextCommitsResult = ConsoleSeriesResult<ConsoleContextCommexport type ConsoleAuditLogItem = {account_id?: string | null- agent_id?: string | nullapi_type?: stringcreated_at?: stringduration_ms?: number