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
fix: narrow legacy agent id compatibility (#2839)
Qin Haojief9c1a60658da
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex 5bce37493..dc7159756 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -71,7 +71,6 @@ pub enum SnapshotShowResult {#[derive(Clone)]pub struct HttpClient {base: BaseClient,- legacy_agent_id: Option<String>,}impl HttpClient {@@ -81,7 +80,6 @@ impl HttpClient {account: Option<String>,user: Option<String>,actor_peer_id: Option<String>,- legacy_agent_id: Option<String>,timeout_secs: f64,profile_enabled: bool,extra_headers: Option<std::collections::HashMap<String, String>>,@@ -97,7 +95,6 @@ impl HttpClient {profile_enabled,extra_headers,),- legacy_agent_id,}}@@ -109,10 +106,6 @@ impl HttpClient {self.base.actor_peer_id()}- pub fn legacy_agent_id(&self) -> Option<&str> {- self.legacy_agent_id.as_deref()- }-pub fn api_key(&self) -> Option<&str> {self.base.api_key()}@@ -498,7 +491,6 @@ impl HttpClient {"context_type": context_type,"tags": tags,});- self.attach_legacy_agent_scope(&mut body);compact_request_body(&mut body);self.post("/api/v1/search/find", &body).await}@@ -530,17 +522,10 @@ impl HttpClient {"context_type": context_type,"tags": tags,});- self.attach_legacy_agent_scope(&mut body);compact_request_body(&mut body);self.post("/api/v1/search/search", &body).await}- fn attach_legacy_agent_scope(&self, body: &mut Value) {- if let Some(agent_id) = self.legacy_agent_id() {- body["agent_id"] = serde_json::json!(agent_id);- }- }-pub async fn grep(&self,uri: &str,@@ -1766,7 +1751,7 @@ mod tests {#[tokio::test]async fn ls_does_not_send_display_time_query() {let (base_url, request_rx) = spawn_request_capture_server().await;- let client = HttpClient::new(base_url, None, None, None, None, None, 5.0, false, None);+ let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None);client.ls("viking://resources", false, false, "agent", 256, false, 1)@@ -1782,7 +1767,7 @@ mod tests {#[tokio::test]async fn tree_does_not_send_display_time_query() {let (base_url, request_rx) = spawn_request_capture_server().await;- let client = HttpClient::new(base_url, None, None, None, None, None, 5.0, false, None);+ let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None);client.tree("viking://resources", "agent", 256, false, 1, 3)@@ -1795,26 +1780,6 @@ mod tests {assert!(!request.contains("include_mod_time_iso="));}- #[test]- fn search_body_includes_legacy_agent_id() {- let client = HttpClient::new(- "http://localhost:1933",- None,- None,- None,- Some("legacy-agent".to_string()),- Some("legacy-agent".to_string()),- 5.0,- false,- None,- );- let mut body = json!({"query": "invoice"});-- client.attach_legacy_agent_scope(&mut body);-- assert_eq!(body["agent_id"], json!("legacy-agent"));- }-#[test]fn standard_error_envelope_formats_api_error() {let body = json!({diff --git a/crates/ov_cli/src/commands/session.rs b/crates/ov_cli/src/commands/session.rsindex 6746d6765..7a362c3d9 100644--- a/crates/ov_cli/src/commands/session.rs+++ b/crates/ov_cli/src/commands/session.rs@@ -288,17 +288,11 @@ fn parse_messages(input: &str) -> Result<Vec<(String, String)>> {Ok(vec![("user".to_string(), input.to_string())])}-fn message_body(client: &HttpClient, role: &str, content: &str) -> serde_json::Value {- let mut body = json!({+fn message_body(role: &str, content: &str) -> serde_json::Value {+ json!({"role": role,"content": content- });- if role == "assistant" {- if let Some(agent_id) = client.legacy_agent_id() {- body["agent_id"] = json!(agent_id);- }- }- body+ })}pub async fn add_message(@@ -316,16 +310,7 @@ pub async fn add_message("content": content});if let Some(peer_id) = peer_id {- if client.legacy_agent_id().is_some() {- return Err(Error::Client(- "peer_id cannot be used when client is configured with legacy agent_id".to_string(),- ));- }body["peer_id"] = json!(peer_id);- } else if role == "assistant" {- if let Some(agent_id) = client.legacy_agent_id() {- body["agent_id"] = json!(agent_id);- }}let response: serde_json::Value = client.post(&path, &body).await?;@@ -344,7 +329,7 @@ pub async fn add_messages(let path = format!("/api/v1/sessions/{}/messages/batch", url_encode(session_id));let messages_json: Vec<serde_json::Value> = messages.iter()- .map(|(role, content)| message_body(client, role, content))+ .map(|(role, content)| message_body(role, content)).collect();let body = json!({"messages": messages_json});let response: serde_json::Value = client.post(&path, &body).await?;@@ -389,7 +374,7 @@ pub async fn add_memory(let path = format!("/api/v1/sessions/{}/messages/batch", url_encode(session_id));let messages_json: Vec<serde_json::Value> = messages.iter()- .map(|(role, content)| message_body(client, role, content))+ .map(|(role, content)| message_body(role, content)).collect();let body = json!({"messages": messages_json});let response: serde_json::Value = client.post(&path, &body).await?;diff --git a/crates/ov_cli/src/config.rs b/crates/ov_cli/src/config.rsindex 29fbac6ef..48c241ace 100644--- a/crates/ov_cli/src/config.rs+++ b/crates/ov_cli/src/config.rs@@ -269,7 +269,7 @@ impl Config {fn validate_identity_mode(&self) -> Result<()> {if self.actor_peer_id.is_some() && self.agent_id.is_some() {return Err(Error::Config(- "actor_peer_id cannot be used with legacy agent_id".to_string(),+ "actor_peer_id cannot be used with agent_id".to_string(),));}Ok(())@@ -390,7 +390,7 @@ mod tests {}#[test]- fn config_deserializes_legacy_agent_id_as_effective_actor_peer() {+ fn config_deserializes_agent_id_as_effective_actor_peer() {let config: Config = serde_json::from_str(r#"{"url": "http://127.0.0.1:1933",@@ -408,7 +408,7 @@ mod tests {}#[test]- fn config_file_rejects_mixed_actor_peer_and_legacy_agent_id() {+ fn config_file_rejects_mixed_actor_peer_and_agent_id() {let dir = tempfile::tempdir().expect("tempdir should be created");let path = dir.path().join("ovcli.conf");std::fs::write(diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rsindex 15b5dba17..35e96de61 100644--- a/crates/ov_cli/src/handlers.rs+++ b/crates/ov_cli/src/handlers.rs@@ -87,7 +87,6 @@ pub async fn handle_add_resource(auth.account,auth.user,ctx.config.effective_actor_peer_id(),- ctx.config.agent_id.clone(),effective_timeout,ctx.profile.unwrap_or(ctx.config.profile),ctx.config.extra_headers.clone(),diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex 9bbb3e730..1258c8505 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -100,7 +100,6 @@ impl CliContext {auth.account,auth.user,self.config.effective_actor_peer_id(),- self.config.agent_id.clone(),timeout_secs.unwrap_or(self.config.timeout),self.profile.unwrap_or(self.config.profile),self.config.extra_headers.clone(),@@ -4224,7 +4223,7 @@ mod tests {}#[test]- fn cli_context_maps_legacy_agent_id_to_actor_peer_scope() {+ fn cli_context_maps_agent_id_to_actor_peer_scope() {let config = Config {url: DEFAULT_CUSTOM_URL.to_string(),api_key: Some("test-key".to_string()),@@ -4258,7 +4257,6 @@ mod tests {let client = ctx.get_client();assert_eq!(client.actor_peer_id(), Some("legacy-agent"));- assert_eq!(client.legacy_agent_id(), Some("legacy-agent"));}#[test]diff --git a/openviking/client/local.py b/openviking/client/local.pyindex 36f63c83c..9ae167d9f 100644--- a/openviking/client/local.py+++ b/openviking/client/local.py@@ -81,6 +81,7 @@ class LocalClient(BaseClient):path: Optional[str] = None,user: Optional[UserIdentifier] = None,actor_peer_id: Optional[str] = None,+ agent_id: Optional[str] = None,):"""Initialize LocalClient.@@ -88,7 +89,11 @@ class LocalClient(BaseClient):path: Local storage path (overrides ov.conf storage path)user: Explicit account/user identity for embedded modeactor_peer_id: Optional view filter for the current user's peer collection.+ agent_id: Legacy alias that marks the actor peer scope as legacy agent mode."""+ if actor_peer_id is not None and agent_id is not None:+ raise ValueError("actor_peer_id cannot be used with legacy agent_id")+ effective_actor_peer_id = actor_peer_id or agent_idself._service = OpenVikingService(path=path,user=user or UserIdentifier.the_default_user(),@@ -97,7 +102,8 @@ class LocalClient(BaseClient):self._ctx = RequestContext(user=self._user,role=Role.USER,- actor_peer_id=normalize_peer_id(actor_peer_id),+ actor_peer_id=normalize_peer_id(effective_actor_peer_id),+ legacy_agent_id=normalize_peer_id(agent_id),)@property@@ -1014,10 +1020,7 @@ class LocalClient(BaseClient):{"role": role,"parts": message_parts,- "peer_id": self._resolve_message_peer_id(- role,- message.get("peer_id"),- ),+ "peer_id": self._resolve_message_peer_id(role, message.get("peer_id")),"created_at": message.get("created_at"),})@@ -1029,8 +1032,18 @@ class LocalClient(BaseClient):"added": len(added),}- def _resolve_message_peer_id(self, role: str, peer_id: Optional[str]) -> Optional[str]:- return normalize_peer_id(peer_id)+ def _resolve_message_peer_id(+ self,+ role: str,+ peer_id: Optional[str],+ ) -> Optional[str]:+ normalized_peer_id = normalize_peer_id(peer_id)+ if normalized_peer_id is not None:+ return normalized_peer_id+ legacy_agent_id = getattr(self._ctx, "legacy_agent_id", None)+ if legacy_agent_id is not None and role == "assistant":+ return legacy_agent_id+ return None# ============= Pack =============diff --git a/openviking/server/auth/__init__.py b/openviking/server/auth/__init__.pyindex 43d3f0b4a..17ab2629c 100644--- a/openviking/server/auth/__init__.py+++ b/openviking/server/auth/__init__.py@@ -73,6 +73,19 @@ def normalize_actor_peer_header(value: Optional[str]) -> Optional[str]:raise InvalidArgumentError(str(exc)) from exc+def resolve_actor_peer_headers(+ actor_peer_header: Optional[str],+ legacy_agent_header: Optional[str],+) -> tuple[Optional[str], Optional[str]]:+ actor_peer_id = normalize_actor_peer_header(actor_peer_header)+ legacy_agent_id = normalize_actor_peer_header(legacy_agent_header)+ if actor_peer_id and legacy_agent_id and actor_peer_id != legacy_agent_id:+ raise InvalidArgumentError(+ "X-OpenViking-Agent and X-OpenViking-Actor-Peer must match when both are set."+ )+ return actor_peer_id or legacy_agent_id, legacy_agent_id++def _explicit_identity_from_request(request: Request) -> tuple[Optional[str], Optional[str]]:path_params = getattr(request, "path_params", {}) or {}query_params = request.query_params@@ -121,11 +134,16 @@ async def get_request_context(request: Request,identity: ResolvedIdentity = Depends(resolve_identity),x_openviking_actor_peer: Optional[str] = Header(None, alias="X-OpenViking-Actor-Peer"),+ x_openviking_agent: Optional[str] = Header(None, alias="X-OpenViking-Agent"),) -> RequestContext:"""Convert ResolvedIdentity to RequestContext."""path = request.url.pathplugin = _get_plugin(request)plugin.get_request_context_checks(path, identity)+ actor_peer_id, legacy_agent_id = resolve_actor_peer_headers(+ x_openviking_actor_peer,+ x_openviking_agent,+ )ctx = RequestContext(user=UserIdentifier(@@ -133,7 +151,8 @@ async def get_request_context(identity.user_id or "default",),role=identity.role,- actor_peer_id=normalize_actor_peer_header(x_openviking_actor_peer),+ actor_peer_id=actor_peer_id,+ legacy_agent_id=legacy_agent_id,from_oauth=identity.from_oauth,)# Update the unified root observability context after authentication succeeds.diff --git a/openviking/server/identity.py b/openviking/server/identity.pyindex f66bd3eda..87bb053ee 100644--- a/openviking/server/identity.py+++ b/openviking/server/identity.py@@ -97,6 +97,9 @@ class RequestContext:# Request-level view filter for the current user's peers collection. This does# not change tenant/user identity or session ownership.actor_peer_id: Optional[str] = None+ # Set only when the actor peer scope came from the historical+ # X-OpenViking-Agent header.+ legacy_agent_id: Optional[str] = None# 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-liveddiff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.pyindex eddca0385..fb8f0e1d3 100644--- a/openviking/server/mcp_endpoint.py+++ b/openviking/server/mcp_endpoint.py@@ -38,7 +38,7 @@ from openviking.parse.parsers.code.ast.code_tools import (outline_file,search_symbols,)-from openviking.server.auth import normalize_actor_peer_header, resolve_identity+from openviking.server.auth import resolve_actor_peer_headers, resolve_identityfrom openviking.server.dependencies import get_server_config, get_servicefrom openviking.server.identity import RequestContextfrom openviking.server.local_input_guard import (@@ -150,8 +150,9 @@ class _IdentityASGIMiddleware:x_openviking_account=request.headers.get("x-openviking-account"),x_openviking_user=request.headers.get("x-openviking-user"),)- actor_peer_id = normalize_actor_peer_header(- request.headers.get("x-openviking-actor-peer")+ actor_peer_id, legacy_agent_id = resolve_actor_peer_headers(+ request.headers.get("x-openviking-actor-peer"),+ request.headers.get("x-openviking-agent"),)except (UnauthenticatedError, PermissionDeniedError, InvalidArgumentError) as exc:status = (@@ -184,6 +185,7 @@ class _IdentityASGIMiddleware:),role=identity.role,actor_peer_id=actor_peer_id,+ legacy_agent_id=legacy_agent_id,from_oauth=identity.from_oauth,)url_info = {diff --git a/openviking/server/routers/sessions.py b/openviking/server/routers/sessions.pyindex adf3747bc..a7ba11628 100644--- a/openviking/server/routers/sessions.py+++ b/openviking/server/routers/sessions.py@@ -5,7 +5,7 @@from typing import Any, Dict, List, Literal, Optionalfrom fastapi import APIRouter, Body, Depends, HTTPException, Path, Query, Request-from pydantic import BaseModel, Field, model_validator+from pydantic import BaseModel, Field, field_validator, model_validatorfrom openviking.core.path_variables import resolve_path_variablesfrom openviking.core.peer_id import normalize_peer_id@@ -92,11 +92,15 @@ class AddMessageRequest(BaseModel):created_at: Optional[str] = Nonetelemetry: TelemetryRequest = False+ @field_validator("peer_id")+ @classmethod+ def validate_peer_id(cls, value: Optional[str]) -> Optional[str]:+ return normalize_peer_id(value)+@model_validator(mode="after")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@@ -129,6 +133,14 @@ def _resolve_message_parts(msg_request: AddMessageRequest) -> List[Part]:return [TextPart(text=msg_request.content or "")]+def _resolve_message_peer_id(msg_request: AddMessageRequest, ctx: RequestContext) -> Optional[str]:+ if msg_request.peer_id is not None:+ return msg_request.peer_id+ if ctx.legacy_agent_id is not None and msg_request.role == "assistant":+ return ctx.legacy_agent_id+ return None++def _part_request_to_part(raw_part: Dict[str, Any]) -> Part:"""Convert request part payload into an internal Part."""if not isinstance(raw_part, dict):@@ -447,7 +459,7 @@ async def add_message({"role": request.role,"parts": parts,- "peer_id": request.peer_id,+ "peer_id": _resolve_message_peer_id(request, _ctx),"created_at": request.created_at,}]@@ -487,7 +499,7 @@ async def batch_add_messages({"role": msg_request.role,"parts": parts,- "peer_id": msg_request.peer_id,+ "peer_id": _resolve_message_peer_id(msg_request, _ctx),"created_at": msg_request.created_at,})diff --git a/openviking_cli/utils/config/ovcli_config.py b/openviking_cli/utils/config/ovcli_config.pyindex 5461418d7..bc4c49d8b 100644--- a/openviking_cli/utils/config/ovcli_config.py+++ b/openviking_cli/utils/config/ovcli_config.py@@ -53,7 +53,7 @@ class OVCLIConfig(BaseModel):@model_validator(mode="after")def reject_mixed_actor_and_agent_identity(self) -> "OVCLIConfig":if self.actor_peer_id is not None and self.agent_id is not None:- raise ValueError("actor_peer_id cannot be used with legacy agent_id")+ raise ValueError("actor_peer_id cannot be used with agent_id")return selfdiff --git a/sdk/go/client_test.go b/sdk/go/client_test.goindex 255a408ba..0518e7940 100644--- a/sdk/go/client_test.go+++ b/sdk/go/client_test.go@@ -123,12 +123,7 @@ func TestFindSendsHeadersQueryAndBody(t *testing.T) {if !ok || len(levels) != 2 || levels[0] != float64(0) || levels[1] != float64(2) {t.Fatalf("level = %#v", body["level"])}- if got := body["agent_id"]; got != "agent-7" {- t.Fatalf("agent_id = %#v", got)- }- if got := body["agent_uri"]; got != "viking://peers/agent-7" {- t.Fatalf("agent_uri = %#v", got)- }+ requireBodyKeysAbsent(t, body, "agent_id", "agent_uri")writeOK(t, w, map[string]any{"resources": []map[string]any{{"uri": "viking://resources/docs/api.md", "context_type": "resource", "score": 0.9},@@ -145,8 +140,6 @@ func TestFindSendsHeadersQueryAndBody(t *testing.T) {Until: "2026-06-18",TimeField: "created_at",Level: []int{0, 2},- AgentID: "agent-7",- AgentURI: "viking://peers/agent-7",})if err != nil {t.Fatal(err)@@ -203,12 +196,7 @@ func TestSearchSendsSessionAndSearchFilters(t *testing.T) {if !ok || len(levels) != 1 || levels[0] != float64(2) {t.Fatalf("level = %#v", body["level"])}- if got := body["agent_id"]; got != "agent-7" {- t.Fatalf("agent_id = %#v", got)- }- if got := body["agent_uri"]; got != "viking://peers/agent-7" {- t.Fatalf("agent_uri = %#v", got)- }+ requireBodyKeysAbsent(t, body, "agent_id", "agent_uri")writeOK(t, w, map[string]any{"resources": []any{}})}))defer closeServer()@@ -220,8 +208,6 @@ func TestSearchSendsSessionAndSearchFilters(t *testing.T) {Until: "2026-06-18",TimeField: "updated_at",Level: []int{2},- AgentID: "agent-7",- AgentURI: "viking://peers/agent-7",}); err != nil {t.Fatal(err)}diff --git a/sdk/go/retrieval.go b/sdk/go/retrieval.goindex ff02948dd..72d32e3a0 100644--- a/sdk/go/retrieval.go+++ b/sdk/go/retrieval.go@@ -32,8 +32,6 @@ func (c *Client) Find(ctx context.Context, queryText string, opts *FindOptions)if len(opts.Level) > 0 {payload["level"] = opts.Level}- setString(payload, "agent_id", opts.AgentID)- setString(payload, "agent_uri", opts.AgentURI)setAny(payload, "telemetry", opts.Telemetry)var result FindResulterr := c.doJSON(ctx, http.MethodPost, "/api/v1/search/find", nil, payload, &result)@@ -68,8 +66,6 @@ func (c *Client) Search(ctx context.Context, queryText string, opts *SearchOptioif len(opts.Level) > 0 {payload["level"] = opts.Level}- setString(payload, "agent_id", opts.AgentID)- setString(payload, "agent_uri", opts.AgentURI)setAny(payload, "telemetry", opts.Telemetry)var result FindResulterr := c.doJSON(ctx, http.MethodPost, "/api/v1/search/search", nil, payload, &result)diff --git a/sdk/go/types.go b/sdk/go/types.goindex 91853a007..9029b8c2b 100644--- a/sdk/go/types.go+++ b/sdk/go/types.go@@ -168,13 +168,6 @@ type FindOptions struct {Until stringTimeField stringLevel []int- // AgentID / AgentURI select the peer whose memories this call is- // scoped to (server FindRequest.agent_id / agent_uri). This is a- // per-call selector and is mutually exclusive with the client-global- // Config.ActorPeerID header: the server rejects a request that sets a- // different peer via both. Leave empty to use the client-global peer.- AgentID string- AgentURI string}// SearchOptions controls Search.@@ -191,12 +184,6 @@ type SearchOptions struct {Until stringTimeField stringLevel []int- // AgentID / AgentURI select the peer whose memories this call is- // scoped to (server SearchRequest.agent_id / agent_uri). Per-call- // selector, mutually exclusive with the client-global- // Config.ActorPeerID header. Leave empty to use the client-global peer.- AgentID string- AgentURI string}// GrepOptions controls Grep.diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.pyindex f5f983877..f420d5711 100644--- a/sdk/python/openviking_sdk/client.py+++ b/sdk/python/openviking_sdk/client.py@@ -218,9 +218,9 @@ class AsyncHTTPClient:upload_mode: Optional[str] = None,):if actor_peer_id and agent_id:- raise ValueError("actor_peer_id cannot be used with legacy agent_id")+ raise ValueError("actor_peer_id cannot be used with agent_id")effective_user = user if user is not None else user_id- effective_actor = actor_peer_id or agent_id+ effective_actor = actor_peer_id if actor_peer_id is not None else agent_idconfig = resolve_client_config(url=url,api_key=api_key,diff --git a/sdk/python/openviking_sdk/config.py b/sdk/python/openviking_sdk/config.pyindex 51affa268..e874ef313 100644--- a/sdk/python/openviking_sdk/config.py+++ b/sdk/python/openviking_sdk/config.py@@ -141,7 +141,7 @@ def load_ovcli_config(config_path: Optional[str] = None) -> Optional[OVCLIConfigactor_peer_id = _optional_string(data.get("actor_peer_id"), path="ovcli.actor_peer_id")agent_id = _optional_string(data.get("agent_id"), path="ovcli.agent_id")if actor_peer_id is not None and agent_id is not None:- raise ValueError("actor_peer_id cannot be used with legacy agent_id")+ raise ValueError("actor_peer_id cannot be used with agent_id")timeout = _optional_float(data.get("timeout"), path="ovcli.timeout")profile = _optional_bool(data.get("profile"), path="ovcli.profile")@@ -191,8 +191,9 @@ def resolve_client_config(actor_peer_idor os.getenv("OPENVIKING_ACTOR_PEER_ID")or (cli_config.actor_peer_id if cli_config else None)- or (cli_config.agent_id if cli_config else None))+ if resolved_actor_peer_id is None and cli_config is not None and cli_config.agent_id:+ resolved_actor_peer_id = cli_config.agent_idresolved_timeout = timeoutif timeout == 60.0:diff --git a/sdk/python/tests/test_ovcli_config_compat.py b/sdk/python/tests/test_ovcli_config_compat.pyindex 817407dea..ab7616f26 100644--- a/sdk/python/tests/test_ovcli_config_compat.py+++ b/sdk/python/tests/test_ovcli_config_compat.py@@ -125,7 +125,7 @@ def test_async_http_client_inherits_profile_enabled_from_ovcli_config(tmp_path,def test_async_http_client_rejects_explicit_actor_peer_id_and_agent_id_together():- with pytest.raises(ValueError, match="actor_peer_id cannot be used with legacy agent_id"):+ with pytest.raises(ValueError, match="actor_peer_id cannot be used with agent_id"):AsyncHTTPClient(url="http://explicit-host:1933",actor_peer_id="actor-a",diff --git a/tests/client/test_http_client_config.py b/tests/client/test_http_client_config.pyindex 65f4a596f..ff0f32850 100644--- a/tests/client/test_http_client_config.py+++ b/tests/client/test_http_client_config.py@@ -7,7 +7,6 @@ import httpximport pytestfrom openviking_cli.client.http import AsyncHTTPClient-from openviking_cli.exceptions import InvalidArgumentErrorfrom openviking_cli.retrieve.types import ContextTypefrom openviking_cli.utils.config import OPENVIKING_CLI_CONFIG_ENV@@ -106,7 +105,6 @@ def test_async_http_client_loads_agent_id_from_ovcli_config(tmp_path, monkeypatcclient = AsyncHTTPClient()assert client._actor_peer_id == "legacy-agent"- assert client._legacy_agent_id == "legacy-agent"def test_async_http_client_rejects_mixed_config_agent_and_actor_peer(tmp_path, monkeypatch):@@ -122,7 +120,7 @@ def test_async_http_client_rejects_mixed_config_agent_and_actor_peer(tmp_path, m)monkeypatch.setenv(OPENVIKING_CLI_CONFIG_ENV, str(config_path))- with pytest.raises(ValueError, match="actor_peer_id cannot be used with legacy agent_id"):+ with pytest.raises(ValueError, match="actor_peer_id cannot be used with agent_id"):AsyncHTTPClient()@@ -197,7 +195,7 @@ async def test_async_http_client_sends_agent_id_as_actor_peer_header(tmp_path, mdef __init__(self, **kwargs):captured.update(kwargs)- monkeypatch.setattr("openviking_cli.client.http.httpx.AsyncClient", FakeAsyncClient)+ monkeypatch.setattr("openviking_sdk.client.httpx.AsyncClient", FakeAsyncClient)client = AsyncHTTPClient(url="http://explicit-host:1933",@@ -209,6 +207,7 @@ async def test_async_http_client_sends_agent_id_as_actor_peer_header(tmp_path, mawait client.initialize()assert captured["headers"]["X-OpenViking-Actor-Peer"] == "legacy-agent"+ assert "X-OpenViking-Agent" not in captured["headers"]def test_async_http_client_rejects_unknown_ovcli_field(tmp_path, monkeypatch):@@ -397,7 +396,9 @@ async def test_async_http_client_find_does_not_send_peer_id(tmp_path, monkeypatc@pytest.mark.asyncio-async def test_async_http_client_legacy_agent_find_sends_agent_id(tmp_path, monkeypatch):+async def test_async_http_client_agent_id_find_does_not_send_body_agent_id(+ tmp_path, monkeypatch+):config_path = tmp_path / "ovcli.conf"config_path.write_text("{}")monkeypatch.setenv(OPENVIKING_CLI_CONFIG_ENV, str(config_path))@@ -412,7 +413,8 @@ async def test_async_http_client_legacy_agent_find_sends_agent_id(tmp_path, monkawait client.find("invoice")- assert http.calls[0][1]["agent_id"] == "legacy-agent"+ assert "agent_id" not in http.calls[0][1]+ assert "agent_uri" not in http.calls[0][1]assert "peer_id" not in http.calls[0][1]@@ -450,7 +452,7 @@ async def test_async_http_client_search_does_not_send_peer_id(tmp_path, monkeypa@pytest.mark.asyncio-async def test_async_http_client_legacy_agent_add_message_sends_agent_id_for_assistant(+async def test_async_http_client_agent_id_add_message_does_not_send_body_agent_id(tmp_path,monkeypatch,):@@ -471,7 +473,7 @@ async def test_async_http_client_legacy_agent_add_message_sends_agent_id_for_assassert http.calls[0] == ("/api/v1/sessions/session-1/messages",- {"role": "assistant", "content": "hello", "agent_id": "legacy-agent"},+ {"role": "assistant", "content": "hello"},)assert http.calls[1] == ("/api/v1/sessions/session-1/messages",@@ -480,7 +482,7 @@ async def test_async_http_client_legacy_agent_add_message_sends_agent_id_for_ass@pytest.mark.asyncio-async def test_async_http_client_legacy_agent_add_message_rejects_peer_id(tmp_path, monkeypatch):+async def test_async_http_client_agent_id_allows_explicit_message_peer_id(tmp_path, monkeypatch):config_path = tmp_path / "ovcli.conf"config_path.write_text("{}")monkeypatch.setenv(OPENVIKING_CLI_CONFIG_ENV, str(config_path))@@ -493,14 +495,19 @@ async def test_async_http_client_legacy_agent_add_message_rejects_peer_id(tmp_pa)client._http = http- with pytest.raises(InvalidArgumentError, match="peer_id cannot be used"):- await client.add_message(- "session-1",- "assistant",- content="hello",- peer_id="legacy-agent",+ await client.add_message(+ "session-1",+ "assistant",+ content="hello",+ peer_id="legacy-agent",+ )++ assert http.calls == [+ (+ "/api/v1/sessions/session-1/messages",+ {"role": "assistant", "content": "hello", "peer_id": "legacy-agent"},)- assert http.calls == []+ ]@pytest.mark.asynciodiff --git a/tests/client/test_lifecycle.py b/tests/client/test_lifecycle.pyindex 5d3d29df4..656fe43dc 100644--- a/tests/client/test_lifecycle.py+++ b/tests/client/test_lifecycle.py@@ -8,7 +8,6 @@ from pathlib import Pathimport pytestfrom openviking import AsyncOpenViking-from openviking_cli.exceptions import InvalidArgumentErrorclass TestClientInitialization:@@ -75,13 +74,13 @@ class TestClientInitialization:"legacy-agent",]- with pytest.raises(InvalidArgumentError, match="peer_id cannot be used"):- await client.add_message(- "legacy-session",- "assistant",- content="again",- peer_id="legacy-agent",- )+ await client.add_message(+ "legacy-session",+ "assistant",+ content="again",+ peer_id="explicit-peer",+ )+ assert session.messages[-1].peer_id == "explicit-peer"finally:await AsyncOpenViking.reset()diff --git a/tests/server/test_actor_peer_retrieval_targets.py b/tests/server/test_actor_peer_retrieval_targets.pyindex e09f8a604..66b141f1b 100644--- a/tests/server/test_actor_peer_retrieval_targets.py+++ b/tests/server/test_actor_peer_retrieval_targets.py@@ -19,24 +19,21 @@ def test_normalize_peer_id_accepts_peer_id():def _ctx(actor_peer_id: str | None = None,- legacy_agent_id: str | None = None,) -> RequestContext:return RequestContext(user=UserIdentifier("acct", "support_bot"),role=Role.USER,actor_peer_id=actor_peer_id,- legacy_agent_id=legacy_agent_id,)def _target_dirs(target_uri="",actor_peer_id: str | None = None,- legacy_agent_id: str | None = None,):return resolve_retrieval_targets(target_uri,- _ctx(actor_peer_id, legacy_agent_id),+ _ctx(actor_peer_id),).target_directories@@ -62,25 +59,6 @@ def test_actor_default_search_keeps_user_view_and_filters_peer_collection():]-def test_legacy_agent_default_search_includes_unmigrated_agent_context():- targets = _target_dirs(- actor_peer_id="web-visitor-alice",- legacy_agent_id="web-visitor-alice",- )-- assert targets == [- "viking://resources",- "viking://user/support_bot/memories",- "viking://user/support_bot/resources",- "viking://user/support_bot/skills",- "viking://user/support_bot/peers/web-visitor-alice/memories",- "viking://user/support_bot/peers/web-visitor-alice/resources",- "viking://agent/web-visitor-alice/memories",- "viking://agent/web-visitor-alice/resources",- "viking://agent/web-visitor-alice/skills",- ]--def test_actor_search_keeps_explicit_resource_target():targets = _target_dirs("viking://resources/docs", actor_peer_id="web-visitor-alice")@@ -108,23 +86,15 @@ def test_actor_default_memory_targets_actor_peer_memory():]-def test_legacy_agent_default_memory_targets_unmigrated_agent_memory():+def test_actor_skill_defaults_include_user_and_shared_agent_skills():assert default_target_directories(- _ctx("web-visitor-alice", legacy_agent_id="web-visitor-alice"),- context_type=ContextType.MEMORY,+ _ctx("web-visitor-alice"), context_type=ContextType.SKILL) == [- "viking://user/support_bot/memories",- "viking://user/support_bot/peers/web-visitor-alice/memories",- "viking://agent/web-visitor-alice/memories",+ "viking://user/support_bot/skills",+ "viking://agent/skills",]-def test_actor_skill_defaults_keep_user_skills():- assert default_target_directories(- _ctx("web-visitor-alice"), context_type=ContextType.SKILL- ) == ["viking://user/support_bot/skills"]--def test_actor_default_resource_targets_global_and_actor_peer_resources():assert default_target_directories(_ctx("web-visitor-alice"), context_type=ContextType.RESOURCE@@ -173,32 +143,6 @@ def test_actor_explicit_other_peer_memory_target_is_denied():)-def test_explicit_legacy_agent_memory_target_includes_migrated_peer_memory():- targets = _target_dirs("viking://agent/web-visitor-alice/memories")-- assert targets == [- "viking://agent/web-visitor-alice/memories",- "viking://user/support_bot/peers/web-visitor-alice/memories",- ]---def test_explicit_legacy_agent_skill_target_includes_migrated_user_skills():- targets = _target_dirs("viking://agent/web-visitor-alice/skills")-- assert targets == [- "viking://agent/web-visitor-alice/skills",- "viking://user/support_bot/skills",- ]---def test_actor_explicit_other_legacy_agent_target_is_denied():- with pytest.raises(PermissionDeniedError, match="another legacy agent"):- _target_dirs(- "viking://agent/web-visitor-bob/memories",- actor_peer_id="web-visitor-alice",- )--def test_owner_peer_collection_targets_all_peer_contexts():assert _target_dirs("viking://user/support_bot/peers") == ["viking://user/support_bot/peers",diff --git a/tests/server/test_auth.py b/tests/server/test_auth.pyindex 20da83345..665bbadab 100644--- a/tests/server/test_auth.py+++ b/tests/server/test_auth.py@@ -761,6 +761,7 @@ async def test_actor_peer_header_sets_request_context_scope():ctx = await get_request_context(request, identity, "web-visitor-alice")assert ctx.actor_peer_id == "web-visitor-alice"+ assert ctx.legacy_agent_id is Noneasync def test_empty_actor_peer_header_is_unset():diff --git a/tests/server/test_peer_id_compat.py b/tests/server/test_peer_id_compat.pyindex 8321bed05..e34eb5d96 100644--- a/tests/server/test_peer_id_compat.py+++ b/tests/server/test_peer_id_compat.py@@ -1,50 +1,28 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""Peer ID compatibility tests."""+"""Peer ID request validation tests."""import pytest-from openviking.core.peer_id import (- normalize_peer_selector,-)-from openviking.server.identity import RequestContext, Rolefrom openviking.server.routers.search import (FindRequest,SearchRequest,- _ctx_with_legacy_actor_peer,)from openviking.server.routers.sessions import AddMessageRequest-from openviking_cli.exceptions import InvalidArgumentError-from openviking_cli.session.user_id import UserIdentifier---def test_normalize_peer_selector_accepts_legacy_agent_uri():- assert normalize_peer_selector(None, agent_uri="viking://agent/code-agent/skills") == (- "code-agent"- )---def test_normalize_peer_selector_rejects_peer_id_with_legacy_agent_id():- with pytest.raises(ValueError, match="peer_id cannot be used"):- normalize_peer_selector("review-agent", agent_id="code-agent")-def test_normalize_peer_selector_rejects_mismatched_agent_id_and_uri():- with pytest.raises(ValueError, match="legacy agent_id must match agent_uri"):- normalize_peer_selector(- None,- agent_id="code-agent",- agent_uri="viking://agent/review-agent/skills",- )---def test_search_request_maps_legacy_agent_uri_to_agent_id():+def test_search_request_preserves_legacy_agent_fields_without_peer_selector():request = SearchRequest.model_validate(- {"query": "invoice", "agent_uri": "viking://agent/code-agent/skills"}+ {+ "query": "invoice",+ "agent_id": "code-agent",+ "agent_uri": "viking://agent/code-agent/skills",+ })assert request.agent_id == "code-agent"+ assert request.agent_uri == "viking://agent/code-agent/skills"def test_find_request_rejects_unpublished_peer_id_body_field():@@ -52,42 +30,28 @@ def test_find_request_rejects_unpublished_peer_id_body_field():FindRequest.model_validate({"query": "invoice", "peer_id": "code-agent"})-def test_add_message_request_maps_legacy_agent_id_to_peer_id():+def test_add_message_request_does_not_map_agent_id_to_peer_id():request = AddMessageRequest.model_validate({"role": "assistant", "content": "hello", "agent_id": "code-agent"})+ assert request.peer_id is None+++def test_add_message_request_normalizes_explicit_peer_id():+ request = AddMessageRequest.model_validate(+ {"role": "assistant", "content": "hello", "peer_id": " code-agent "}+ )+assert request.peer_id == "code-agent"-def test_add_message_request_rejects_peer_id_with_legacy_agent_id():- with pytest.raises(ValueError, match="peer_id cannot be used"):+def test_add_message_request_rejects_path_like_peer_id():+ with pytest.raises(ValueError, match="Invalid peer_id"):AddMessageRequest.model_validate({"role": "assistant","content": "hello",- "peer_id": "code-agent",- "agent_id": "code-agent",+ "peer_id": "code/agent",})---def test_legacy_search_peer_sets_actor_peer_context():- ctx = RequestContext(user=UserIdentifier("acct", "alice"), role=Role.USER)-- scoped = _ctx_with_legacy_actor_peer(ctx, "code-agent")-- assert scoped.actor_peer_id == "code-agent"- assert scoped.legacy_agent_id == "code-agent"- assert ctx.actor_peer_id is None---def test_legacy_search_peer_must_match_actor_peer_context():- ctx = RequestContext(- user=UserIdentifier("acct", "alice"),- role=Role.USER,- actor_peer_id="actor-a",- )-- with pytest.raises(InvalidArgumentError, match="actor_peer_id cannot be used"):- _ctx_with_legacy_actor_peer(ctx, "actor-b")