Skip to content

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

feat(core): add actor peer filesystem view (#2594)

Qin Haojie49e4d7691374
diff --git a/crates/ov_cli/src/base_client.rs b/crates/ov_cli/src/base_client.rs
index f8419447a..810c97b9f 100644
--- a/crates/ov_cli/src/base_client.rs
+++ b/crates/ov_cli/src/base_client.rs
@@ -145,6 +145,7 @@ pub struct BaseClient {
pub(crate) api_key: Option<String>,
pub(crate) account: Option<String>,
pub(crate) user: Option<String>,
+ pub(crate) actor_peer_id: Option<String>,
pub(crate) profile_enabled: bool,
pub(crate) extra_headers: Option<std::collections::HashMap<String, String>>,
}
@@ -155,6 +156,7 @@ impl BaseClient {
api_key: Option<String>,
account: Option<String>,
user: Option<String>,
+ actor_peer_id: Option<String>,
timeout_secs: f64,
profile_enabled: bool,
extra_headers: Option<std::collections::HashMap<String, String>>,
@@ -170,6 +172,7 @@ impl BaseClient {
api_key,
account,
user,
+ actor_peer_id,
profile_enabled,
extra_headers,
}
@@ -187,6 +190,10 @@ impl BaseClient {
self.user.as_deref()
}
+ pub fn actor_peer_id(&self) -> Option<&str> {
+ self.actor_peer_id.as_deref()
+ }
+
pub fn api_key(&self) -> Option<&str> {
self.api_key.as_deref()
}
@@ -212,6 +219,11 @@ impl BaseClient {
headers.insert("X-OpenViking-User", value);
}
}
+ if let Some(actor_peer_id) = &self.actor_peer_id {
+ if let Ok(value) = reqwest::header::HeaderValue::from_str(actor_peer_id) {
+ headers.insert("X-OpenViking-Actor-Peer", value);
+ }
+ }
if let Some(extra_headers) = &self.extra_headers {
for (key, value) in extra_headers {
if let Ok(header_name) = reqwest::header::HeaderName::from_str(key) {
@@ -574,7 +586,16 @@ mod tests {
#[test]
fn append_profile_query_adds_flag_when_enabled() {
- let client = BaseClient::new("http://localhost:1933", None, None, None, 5.0, true, None);
+ let client = BaseClient::new(
+ "http://localhost:1933",
+ None,
+ None,
+ None,
+ None,
+ 5.0,
+ true,
+ None,
+ );
let params =
client.append_profile_query(&[("to_uri".to_string(), "viking://x".to_string())]);
@@ -590,7 +611,16 @@ mod tests {
#[test]
fn append_profile_query_keeps_existing_profile_flag() {
- let client = BaseClient::new("http://localhost:1933", None, None, None, 5.0, true, None);
+ let client = BaseClient::new(
+ "http://localhost:1933",
+ None,
+ None,
+ None,
+ None,
+ 5.0,
+ true,
+ None,
+ );
let params = client.append_profile_query(&[("profile".to_string(), "1".to_string())]);
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index 65a3a182b..7dab0c128 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -21,6 +21,7 @@ impl HttpClient {
api_key: Option<String>,
account: Option<String>,
user: Option<String>,
+ actor_peer_id: Option<String>,
timeout_secs: f64,
profile_enabled: bool,
extra_headers: Option<std::collections::HashMap<String, String>>,
@@ -31,6 +32,7 @@ impl HttpClient {
api_key,
account,
user,
+ actor_peer_id,
timeout_secs,
profile_enabled,
extra_headers,
@@ -42,6 +44,10 @@ impl HttpClient {
self.base.user_id()
}
+ pub fn actor_peer_id(&self) -> Option<&str> {
+ self.base.actor_peer_id()
+ }
+
pub fn api_key(&self) -> Option<&str> {
self.base.api_key()
}
@@ -387,7 +393,6 @@ impl HttpClient {
time_field: Option<String>,
level: Option<Vec<i32>>,
context_type: Option<Vec<String>>,
- peer_id: Option<String>,
) -> Result<serde_json::Value> {
let body = serde_json::json!({
"query": query,
@@ -399,7 +404,6 @@ impl HttpClient {
"time_field": time_field,
"level": level,
"context_type": context_type,
- "peer_id": peer_id,
});
self.post("/api/v1/search/find", &body).await
}
@@ -416,7 +420,6 @@ impl HttpClient {
time_field: Option<String>,
level: Option<Vec<i32>>,
context_type: Option<Vec<String>>,
- peer_id: Option<String>,
) -> Result<serde_json::Value> {
let body = serde_json::json!({
"query": query,
@@ -429,7 +432,6 @@ impl HttpClient {
"time_field": time_field,
"level": level,
"context_type": context_type,
- "peer_id": peer_id,
});
self.post("/api/v1/search/search", &body).await
}
@@ -1396,6 +1398,7 @@ mod tests {
Some("test-key".to_string()),
Some("acme".to_string()),
Some("alice".to_string()),
+ Some("peer-a".to_string()),
5.0,
true,
Some(extra_headers),
@@ -1409,6 +1412,24 @@ mod tests {
.and_then(|value| value.to_str().ok()),
Some("test-key")
);
+ assert_eq!(
+ headers
+ .get("X-OpenViking-Account")
+ .and_then(|value| value.to_str().ok()),
+ Some("acme")
+ );
+ assert_eq!(
+ headers
+ .get("X-OpenViking-User")
+ .and_then(|value| value.to_str().ok()),
+ Some("alice")
+ );
+ assert_eq!(
+ headers
+ .get("X-OpenViking-Actor-Peer")
+ .and_then(|value| value.to_str().ok()),
+ Some("peer-a")
+ );
assert_eq!(
headers
.get("X-Custom-Header")
@@ -1444,7 +1465,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, 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)
@@ -1460,7 +1481,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, 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)
diff --git a/crates/ov_cli/src/commands/search.rs b/crates/ov_cli/src/commands/search.rs
index b5b16395c..ea51583d3 100644
--- a/crates/ov_cli/src/commands/search.rs
+++ b/crates/ov_cli/src/commands/search.rs
@@ -55,7 +55,6 @@ pub async fn find(
time_field: Option<&str>,
level: Option<Vec<i32>>,
context_type: Option<Vec<String>>,
- peer_id: Option<&str>,
output_format: OutputFormat,
compact: bool,
) -> Result<()> {
@@ -70,7 +69,6 @@ pub async fn find(
time_field.map(|s| s.to_string()),
level,
context_type,
- peer_id.map(|s| s.to_string()),
)
.await?;
output_search_results(
@@ -94,7 +92,6 @@ pub async fn search(
time_field: Option<&str>,
level: Option<Vec<i32>>,
context_type: Option<Vec<String>>,
- peer_id: Option<&str>,
output_format: OutputFormat,
compact: bool,
) -> Result<()> {
@@ -110,7 +107,6 @@ pub async fn search(
time_field.map(|s| s.to_string()),
level,
context_type,
- peer_id.map(|s| s.to_string()),
)
.await?;
output_search_results(
diff --git a/crates/ov_cli/src/config.rs b/crates/ov_cli/src/config.rs
index fc332d372..bd6d1af72 100644
--- a/crates/ov_cli/src/config.rs
+++ b/crates/ov_cli/src/config.rs
@@ -45,6 +45,8 @@ 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 actor_peer_id: Option<String>,
#[serde(
default = "default_timeout",
skip_serializing_if = "is_default_timeout"
@@ -149,6 +151,7 @@ impl Default for Config {
root_api_key: None,
account: None,
user: None,
+ actor_peer_id: None,
timeout: 60.0,
output: "table".to_string(),
echo_command: true,
@@ -355,13 +358,15 @@ mod tests {
"url": "http://127.0.0.1:1933",
"api_key": "test-key",
"account": "acme",
- "user": "alice"
+ "user": "alice",
+ "actor_peer_id": "peer-a"
}"#,
)
.expect("config should deserialize");
assert_eq!(config.account.as_deref(), Some("acme"));
assert_eq!(config.user.as_deref(), Some("alice"));
+ assert_eq!(config.actor_peer_id.as_deref(), Some("peer-a"));
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_agent.rs b/crates/ov_cli/src/config_agent.rs
index a61c9c224..97ebd52fb 100644
--- a/crates/ov_cli/src/config_agent.rs
+++ b/crates/ov_cli/src/config_agent.rs
@@ -318,6 +318,7 @@ async fn add_ov_service(
"OpenViking Service API key",
)?;
validate_optional_identity(args.account.as_deref(), args.user.as_deref())?;
+ validate_optional_actor_peer_id(args.actor_peer_id.as_deref())?;
let config = Config {
url: OPENVIKING_SERVICE_URL.to_string(),
@@ -325,6 +326,7 @@ async fn add_ov_service(
root_api_key: None,
account: args.account,
user: args.user,
+ actor_peer_id: args.actor_peer_id,
..Config::default()
};
@@ -354,6 +356,7 @@ async fn add_ov_service(
async fn add_custom(store: &ConfigStore, args: ConfigAddCustomArgs) -> AgentResult<AddEditResult> {
let name = config_name_or_generate(store, args.name, ConfigKind::Custom)?;
validate_optional_identity(args.account.as_deref(), args.user.as_deref())?;
+ validate_optional_actor_peer_id(args.actor_peer_id.as_deref())?;
let api_key = read_optional_secret(
secret_input(args.api_key_stdin, args.api_key_env.as_deref()),
"API key",
@@ -364,7 +367,14 @@ async fn add_custom(store: &ConfigStore, args: ConfigAddCustomArgs) -> AgentResu
)?;
let url = normalize_custom_url(args.url.as_deref().unwrap_or(DEFAULT_CUSTOM_URL));
- let config = build_custom_config(url, api_key, root_api_key, args.account, args.user)?;
+ let config = build_custom_config(
+ url,
+ api_key,
+ root_api_key,
+ args.account,
+ args.user,
+ args.actor_peer_id,
+ )?;
if let Some(result) = existing_add_preflight(
store,
@@ -409,6 +419,7 @@ async fn edit_saved_config(
let new_name = args.new_name.clone().unwrap_or_else(|| args.name.clone());
validate_config_name(&new_name).map_err(config_error)?;
validate_optional_identity(args.account.as_deref(), args.user.as_deref())?;
+ validate_optional_actor_peer_id(args.actor_peer_id.as_deref())?;
if old_kind == ConfigKind::OpenVikingService && args.url.is_some() {
return Err(AgentError::bad_input(
@@ -453,6 +464,12 @@ async fn edit_saved_config(
if args.user.is_some() {
edited.user = args.user;
}
+ if args.clear_actor_peer_id {
+ edited.actor_peer_id = None;
+ }
+ if args.actor_peer_id.is_some() {
+ edited.actor_peer_id = args.actor_peer_id;
+ }
if !api_key_touched
&& !root_key_touched
&& existing_root_as_normal
@@ -483,6 +500,7 @@ fn build_custom_config(
root_api_key: Option<String>,
mut account: Option<String>,
mut user: Option<String>,
+ actor_peer_id: Option<String>,
) -> AgentResult<Config> {
if api_key.is_none() && root_api_key.is_none() && custom_requires_api_key(&url) {
return Err(AgentError::bad_input(
@@ -501,6 +519,7 @@ fn build_custom_config(
root_api_key,
account,
user,
+ actor_peer_id,
..Config::default()
};
@@ -883,6 +902,21 @@ fn validate_optional_identity(account: Option<&str>, user: Option<&str>) -> Agen
Ok(())
}
+fn validate_optional_actor_peer_id(actor_peer_id: Option<&str>) -> AgentResult<()> {
+ let Some(actor_peer_id) = actor_peer_id else {
+ return Ok(());
+ };
+ if actor_peer_id.trim().is_empty() {
+ return Err(AgentError::bad_input("actor_peer_id cannot be empty."));
+ }
+ if actor_peer_id.contains('/') || actor_peer_id.contains('\\') {
+ return Err(AgentError::bad_input(
+ "actor_peer_id cannot contain path separators.",
+ ));
+ }
+ Ok(())
+}
+
fn validation_error(kind: ConfigKind, error: Error) -> AgentError {
match error {
Error::Api { message, .. } => AgentError::auth(format!(
@@ -958,6 +992,8 @@ mod tests {
clear_root_api_key: false,
account: None,
user: None,
+ actor_peer_id: None,
+ clear_actor_peer_id: false,
activate: false,
force: false,
}
@@ -1033,8 +1069,8 @@ mod tests {
assert!(name.starts_with("ov-service-"));
validate_config_name(&name).expect("generated name should be valid");
- let name =
- config_name_or_generate(&store, None, ConfigKind::Custom).expect("name should generate");
+ let name = config_name_or_generate(&store, None, ConfigKind::Custom)
+ .expect("name should generate");
assert!(name.starts_with("custom-"));
validate_config_name(&name).expect("generated name should be valid");
}
@@ -1117,6 +1153,7 @@ mod tests {
Some("root-key".to_string()),
Some("acme".to_string()),
Some("alice".to_string()),
+ Some("peer-a".to_string()),
)
.expect("root-only custom config should build");
@@ -1124,6 +1161,18 @@ mod tests {
assert_eq!(config.root_api_key.as_deref(), Some("root-key"));
assert_eq!(config.account.as_deref(), Some("acme"));
assert_eq!(config.user.as_deref(), Some("alice"));
+ assert_eq!(config.actor_peer_id.as_deref(), Some("peer-a"));
+ }
+
+ #[test]
+ fn actor_peer_id_validation_rejects_path_separators() {
+ validate_optional_actor_peer_id(Some("peer-a")).expect("plain peer id should validate");
+
+ let error = validate_optional_actor_peer_id(Some("peer/a"))
+ .expect_err("path-like actor peer id should fail");
+
+ assert_eq!(error.exit_code(), EXIT_BAD_INPUT);
+ assert!(error.message.contains("path separators"));
}
#[test]
@@ -1134,6 +1183,7 @@ mod tests {
Some("root-key".to_string()),
Some("acme".to_string()),
Some("alice".to_string()),
+ None,
)
.expect("custom config with both keys should build");
@@ -1149,6 +1199,7 @@ mod tests {
Some("root-key".to_string()),
None,
Some("alice".to_string()),
+ None,
)
.expect_err("root key without account should fail");
@@ -1188,6 +1239,7 @@ mod tests {
Some("root-key".to_string()),
Some("acme".to_string()),
Some("alice".to_string()),
+ None,
)
.expect("add path should build root-as-normal config");
diff --git a/crates/ov_cli/src/config_wizard/store.rs b/crates/ov_cli/src/config_wizard/store.rs
index c2ec36ffa..046ebf66b 100644
--- a/crates/ov_cli/src/config_wizard/store.rs
+++ b/crates/ov_cli/src/config_wizard/store.rs
@@ -574,6 +574,7 @@ pub(crate) async fn validate_candidate_config_with_role(
auth.api_key.clone(),
auth.account,
auth.user,
+ config.actor_peer_id.clone(),
timeout,
config.profile,
config.extra_headers.clone(),
diff --git a/crates/ov_cli/src/config_wizard/wizard.rs b/crates/ov_cli/src/config_wizard/wizard.rs
index aa3c7168d..b55ee316c 100644
--- a/crates/ov_cli/src/config_wizard/wizard.rs
+++ b/crates/ov_cli/src/config_wizard/wizard.rs
@@ -749,6 +749,7 @@ async fn status_box_runtime(active: Option<&Config>) -> StatusBoxRuntime {
auth.api_key,
auth.account,
auth.user,
+ config.actor_peer_id.clone(),
STATUS_BOX_PROBE_TIMEOUT_SECS,
config.profile,
config.extra_headers.clone(),
diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rs
index 4ef88752e..aa2104d1d 100644
--- a/crates/ov_cli/src/handlers.rs
+++ b/crates/ov_cli/src/handlers.rs
@@ -80,6 +80,7 @@ pub async fn handle_add_resource(
auth.api_key,
auth.account,
auth.user,
+ ctx.config.actor_peer_id.clone(),
effective_timeout,
ctx.profile.unwrap_or(ctx.config.profile),
ctx.config.extra_headers.clone(),
@@ -1117,7 +1118,6 @@ pub async fn handle_find(
before: Option<String>,
level: Option<Vec<i32>>,
context_type: Option<Vec<String>>,
- peer_id: Option<String>,
ctx: CliContext,
) -> Result<()> {
let mut params = vec![format!("--uri={}", uri), format!("-n {}", node_limit)];
@@ -1137,9 +1137,6 @@ pub async fn handle_find(
if let Some(ref context_types) = context_type {
params.push(format!("--context-type {}", context_types.join(",")));
}
- if let Some(ref p) = peer_id {
- params.push(format!("--peer-id {}", p));
- }
params.push(format!("\"{}\"", query));
print_command_echo("ov find", &params.join(" "), ctx.config.echo_command);
let client = ctx.get_client();
@@ -1154,7 +1151,6 @@ pub async fn handle_find(
None,
level,
context_type,
- peer_id.as_deref(),
ctx.output_format,
ctx.compact,
)
@@ -1171,7 +1167,6 @@ pub async fn handle_search(
before: Option<String>,
level: Option<Vec<i32>>,
context_type: Option<Vec<String>>,
- peer_id: Option<String>,
ctx: CliContext,
) -> Result<()> {
let mut params = vec![format!("--uri={}", uri), format!("-n {}", node_limit)];
@@ -1194,9 +1189,6 @@ pub async fn handle_search(
if let Some(ref context_types) = context_type {
params.push(format!("--context-type {}", context_types.join(",")));
}
- if let Some(ref p) = peer_id {
- params.push(format!("--peer-id {}", p));
- }
params.push(format!("\"{}\"", query));
print_command_echo("ov search", &params.join(" "), ctx.config.echo_command);
let client = ctx.get_client();
@@ -1212,7 +1204,6 @@ pub async fn handle_search(
None,
level,
context_type,
- peer_id.as_deref(),
ctx.output_format,
ctx.compact,
)
diff --git a/crates/ov_cli/src/help_ui.rs b/crates/ov_cli/src/help_ui.rs
index 3397bbf97..7951fc651 100644
--- a/crates/ov_cli/src/help_ui.rs
+++ b/crates/ov_cli/src/help_ui.rs
@@ -2134,6 +2134,7 @@ fn config_help_path(tokens: &[String]) -> Option<Vec<String>> {
| "--root-api-key-env"
| "--account"
| "--user"
+ | "--actor-peer-id"
)
{
i += if token.contains('=') { 1 } else { 2 };
@@ -2189,6 +2190,7 @@ fn has_invalid_config_add_provider(tokens: &[String]) -> bool {
| "--root-api-key-env"
| "--account"
| "--user"
+ | "--actor-peer-id"
)
{
i += if token.contains('=') { 1 } else { 2 };
@@ -2263,11 +2265,12 @@ fn is_help_flag(token: &str) -> bool {
fn consumes_value(token: &str) -> bool {
matches!(
token,
- "-o" | "--output" | "-c" | "--compact" | "--account" | "--user"
+ "-o" | "--output" | "-c" | "--compact" | "--account" | "--user" | "--actor-peer-id"
) || token.starts_with("--output=")
|| token.starts_with("--compact=")
|| token.starts_with("--account=")
|| token.starts_with("--user=")
+ || token.starts_with("--actor-peer-id=")
}
#[cfg(test)]
@@ -2549,7 +2552,7 @@ mod tests {
}
#[test]
- fn curated_help_lists_upload_filters_peer_id_and_limit_aliases() {
+ fn curated_help_lists_upload_filters_and_limit_aliases() {
let add_resource = strip_ansi(
&render_command_help_request(&os_args(&["ov", "add-resource", "--help"]))
.expect("add-resource help should render"),
@@ -2580,16 +2583,11 @@ mod tests {
"missing --limit alias for {command} in:\n{rendered}"
);
}
-
for command in ["find", "search"] {
let rendered = strip_ansi(
&render_command_help_request(&os_args(&["ov", command, "--help"]))
.expect("help should render"),
);
- assert!(
- rendered.contains("--peer-id <id>"),
- "missing --peer-id for {command} in:\n{rendered}"
- );
assert!(
rendered.contains("--context-type <type>"),
"missing --context-type for {command} in:\n{rendered}"
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 68f7c5bdf..828753940 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -49,6 +49,7 @@ impl CliContext {
compact: bool,
account: Option<String>,
user: Option<String>,
+ actor_peer_id: Option<String>,
sudo: bool,
show_progress: Option<bool>,
verbose: Option<bool>,
@@ -60,6 +61,9 @@ impl CliContext {
if user.is_some() {
config.user = user;
}
+ if actor_peer_id.is_some() {
+ config.actor_peer_id = actor_peer_id;
+ }
Self {
config,
output_format,
@@ -92,6 +96,7 @@ impl CliContext {
auth.api_key,
auth.account,
auth.user,
+ self.config.actor_peer_id.clone(),
timeout_secs.unwrap_or(self.config.timeout),
self.profile.unwrap_or(self.config.profile),
self.config.extra_headers.clone(),
@@ -137,6 +142,10 @@ struct Cli {
#[arg(long, global = true, hide = true)]
user: Option<String>,
+ /// Peer actor scope to send as X-OpenViking-Actor-Peer
+ #[arg(long = "actor-peer-id", global = true, hide = true)]
+ actor_peer_id: Option<String>,
+
/// Use root API key for admin, system, and reindex commands
#[arg(long, global = true, hide = true)]
sudo: bool,
@@ -556,9 +565,6 @@ enum Commands {
help_heading = "Common options"
)]
context_type: Option<Vec<String>>,
- /// Limit memory retrieval to this peer plus the current user memory
- #[arg(long = "peer-id", value_name = "id", help_heading = "Advanced options")]
- peer_id: Option<String>,
},
/// [Experimental][Data] Run context-aware retrieval
Search {
@@ -617,9 +623,6 @@ enum Commands {
help_heading = "Advanced options"
)]
context_type: Option<Vec<String>>,
- /// Limit memory retrieval to this peer plus the current user memory
- #[arg(long = "peer-id", value_name = "id", help_heading = "Advanced options")]
- peer_id: Option<String>,
},
/// [Data] Run content pattern search
Grep {
@@ -1524,6 +1527,9 @@ struct ConfigAddOvServiceArgs {
/// User identifier to send as X-OpenViking-User
#[arg(long, value_name = "user", help_heading = "Advanced options")]
user: Option<String>,
+ /// Peer actor scope to send as X-OpenViking-Actor-Peer
+ #[arg(long = "actor-peer-id", hide = true)]
+ actor_peer_id: Option<String>,
/// Make the saved config active after validation
#[arg(long, help_heading = "Common options")]
activate: bool,
@@ -1576,6 +1582,9 @@ struct ConfigAddCustomArgs {
/// User identifier to send as X-OpenViking-User
#[arg(long, value_name = "user", help_heading = "Advanced options")]
user: Option<String>,
+ /// Peer actor scope to send as X-OpenViking-Actor-Peer
+ #[arg(long = "actor-peer-id", hide = true)]
+ actor_peer_id: Option<String>,
/// Make the saved config active after validation
#[arg(long, help_heading = "Common options")]
activate: bool,
@@ -1645,6 +1654,20 @@ struct ConfigEditArgs {
/// User identifier to send as X-OpenViking-User
#[arg(long, value_name = "user", help_heading = "Advanced options")]
user: Option<String>,
+ /// Peer actor scope to send as X-OpenViking-Actor-Peer
+ #[arg(
+ long = "actor-peer-id",
+ hide = true,
+ conflicts_with = "clear_actor_peer_id"
+ )]
+ actor_peer_id: Option<String>,
+ /// Remove the peer actor scope
+ #[arg(
+ long = "clear-actor-peer-id",
+ hide = true,
+ conflicts_with = "actor_peer_id"
+ )]
+ clear_actor_peer_id: bool,
/// Make the saved config active after validation
#[arg(long, help_heading = "Common options")]
activate: bool,
@@ -1668,7 +1691,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" => {
+ "--output" | "-o" | "--compact" | "--account" | "--user" | "--actor-peer-id" => {
i += 2;
}
"--sudo" | "--progress" | "--no-progress" | "--verbose" | "-v" => {
@@ -1768,6 +1791,7 @@ fn consumes_plain_help_value(token: &str) -> bool {
| "--compact"
| "--account"
| "--user"
+ | "--actor-peer-id"
| "-u"
| "--uri"
| "-x"
@@ -1834,6 +1858,7 @@ fn consumes_plain_help_value(token: &str) -> bool {
|| token.starts_with("--compact=")
|| token.starts_with("--account=")
|| token.starts_with("--user=")
+ || token.starts_with("--actor-peer-id=")
|| token.starts_with("--uri=")
|| token.starts_with("--exclude-uri=")
|| token.starts_with("--to=")
@@ -2352,7 +2377,10 @@ fn first_command_token(args: &[OsString]) -> Option<String> {
}
fn global_option_takes_value(option: &str) -> bool {
- matches!(option, "--output" | "--account" | "--user")
+ matches!(
+ option,
+ "--output" | "--account" | "--user" | "--actor-peer-id"
+ )
}
fn global_short_option_takes_value(option: &str) -> bool {
@@ -2522,6 +2550,7 @@ async fn main() {
compact,
cli.account.clone(),
cli.user.clone(),
+ cli.actor_peer_id.clone(),
cli.sudo,
None,
None,
@@ -2917,7 +2946,6 @@ async fn main() {
before,
level,
context_type,
- peer_id,
} => {
handlers::handle_find(
query,
@@ -2928,7 +2956,6 @@ async fn main() {
before,
level,
context_type,
- peer_id,
ctx,
)
.await
@@ -2943,7 +2970,6 @@ async fn main() {
before,
level,
context_type,
- peer_id,
} => {
handlers::handle_search(
query,
@@ -2955,7 +2981,6 @@ async fn main() {
before,
level,
context_type,
- peer_id,
ctx,
)
.await
@@ -3017,24 +3042,21 @@ mod tests {
#[test]
fn cli_parses_global_identity_override_flags() {
- let cli = Cli::try_parse_from(["ov", "--account", "acme", "--user", "alice", "ls"])
- .expect("cli should parse");
+ let cli = Cli::try_parse_from([
+ "ov",
+ "--account",
+ "acme",
+ "--user",
+ "alice",
+ "--actor-peer-id",
+ "peer-a",
+ "ls",
+ ])
+ .expect("cli should parse");
assert_eq!(cli.account.as_deref(), Some("acme"));
assert_eq!(cli.user.as_deref(), Some("alice"));
- }
-
- #[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"),
- }
+ assert_eq!(cli.actor_peer_id.as_deref(), Some("peer-a"));
}
#[test]
@@ -3054,20 +3076,6 @@ mod tests {
}
}
- #[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]
fn cli_parses_search_context_type() {
let cli = Cli::try_parse_from(["ov", "search", "invoice", "--context-type", "skill"])
@@ -3188,6 +3196,8 @@ mod tests {
"https://ov.example.com",
"--api-key-env",
"OV_KEY",
+ "--actor-peer-id",
+ "peer-a",
])
.expect("custom add should parse");
let Commands::Config {
@@ -3201,6 +3211,7 @@ mod tests {
};
assert_eq!(custom.url.as_deref(), Some("https://ov.example.com"));
assert_eq!(custom.api_key_env.as_deref(), Some("OV_KEY"));
+ assert_eq!(custom.actor_peer_id.as_deref(), Some("peer-a"));
let edit = Cli::try_parse_from([
"ov",
@@ -3208,6 +3219,7 @@ mod tests {
"edit",
"prod",
"--clear-api-key",
+ "--clear-actor-peer-id",
"--activate",
])
.expect("config edit should parse");
@@ -3219,6 +3231,7 @@ mod tests {
};
assert_eq!(edit.name, "prod");
assert!(edit.clear_api_key);
+ assert!(edit.clear_actor_peer_id);
assert!(edit.activate);
assert!(
@@ -3864,6 +3877,8 @@ mod tests {
"--output",
"json",
"--account=acme",
+ "--actor-peer-id",
+ "peer-a",
"--sudo",
"admin",
]))
@@ -4005,6 +4020,7 @@ mod tests {
root_api_key: None,
account: Some("from-config-account".to_string()),
user: Some("from-config-user".to_string()),
+ actor_peer_id: Some("from-config-peer".to_string()),
timeout: 60.0,
output: "table".to_string(),
echo_command: true,
@@ -4021,6 +4037,7 @@ mod tests {
true,
Some("from-cli-account".to_string()),
Some("from-cli-user".to_string()),
+ Some("from-cli-peer".to_string()),
false,
None,
None,
@@ -4029,6 +4046,7 @@ 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.actor_peer_id.as_deref(), Some("from-cli-peer"));
}
#[test]
@@ -4039,6 +4057,7 @@ mod tests {
root_api_key: Some("root-key".to_string()),
account: None,
user: None,
+ actor_peer_id: Some("peer-a".to_string()),
timeout: 60.0,
output: "table".to_string(),
echo_command: true,
@@ -4056,6 +4075,7 @@ mod tests {
true,
None,
None,
+ None,
false,
None,
None,
@@ -4063,6 +4083,7 @@ mod tests {
);
let client = ctx.get_client();
assert_eq!(client.api_key(), Some("user-key"));
+ assert_eq!(client.actor_peer_id(), Some("peer-a"));
// With sudo: use root_api_key
let ctx = CliContext::from_config(
@@ -4071,6 +4092,7 @@ mod tests {
true,
None,
None,
+ None,
true,
None,
None,
diff --git a/docs/en/agent-integrations/07-langchain-langgraph.md b/docs/en/agent-integrations/07-langchain-langgraph.md
index 1224af4bd..3169cb55b 100644
--- a/docs/en/agent-integrations/07-langchain-langgraph.md
+++ b/docs/en/agent-integrations/07-langchain-langgraph.md
@@ -23,24 +23,24 @@ 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
+## 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.
+Pass `actor_peer_id` to filter the current user's peer collection for filesystem and retrieval operations. Session message capture can still use `peer_id` for per-message speaker attribution.
```python
retriever = OpenVikingRetriever(
url="http://localhost:1933",
- peer_id="assistant-a",
+ actor_peer_id="assistant-a",
)
chain = with_openviking_context(
runnable,
session_id="support-thread-1",
- peer_id="assistant-a",
+ actor_peer_id="assistant-a",
)
```
-For dynamic runs, `with_openviking_context()` also reads `config["configurable"]["peer_id"]` by default:
+For dynamic runs, `with_openviking_context()` still reads `config["configurable"]["peer_id"]` by default for captured message attribution:
```python
chain.invoke(
diff --git a/docs/en/api/04-skills.md b/docs/en/api/04-skills.md
index 94acc12dc..535a6597d 100644
--- a/docs/en/api/04-skills.md
+++ b/docs/en/api/04-skills.md
@@ -188,7 +188,7 @@ Skills are a special type of resource that define actions or tools agents can pe
- **Targeting**:
- Skills are always user-scoped. `add_skill` does not accept `to`, `parent`, or `root_uri`.
- - Peer-scoped skill roots are not supported; peer-aware retrieval only adds peer memories/resources, not peer skills.
+ - Peer-scoped skill roots are not supported; actor peer filtering only applies to peer memories/resources, not peer skills.
- Use `viking://user/skills/...` as current-user shorthand when listing, reading, deleting, or searching skills.
- **Supported data formats**:
diff --git a/docs/en/api/06-retrieval.md b/docs/en/api/06-retrieval.md
index 77a9fc1bf..fac4cde6d 100644
--- a/docs/en/api/06-retrieval.md
+++ b/docs/en/api/06-retrieval.md
@@ -57,7 +57,6 @@ 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 |
| context_type | str \| List[str] | No | None | Limit results to one or more `ContextType` values: `memory`, `resource`, or `skill` |
-| peer_id | str | No | None | Stable interaction peer ID. When searching default user-scoped targets, results include this peer's memories and resources in addition to current-user content. 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 |
@@ -69,9 +68,8 @@ The `find()` method performs pure vector similarity search for simple query scen
| telemetry | bool \| object | No | False | Attach telemetry data to response |
**Target resolution notes**:
-- With empty `target_uri`, non-ROOT retrieval searches current-user memories, shared `viking://resources`, current-user resources, and current-user skills.
-- When `peer_id` is provided, OpenViking also searches `viking://user/{user_id}/peers/{peer_id}/memories` and `viking://user/{user_id}/peers/{peer_id}/resources`. Peer skills are not searched.
-- `peer_id` must be a safe single path segment, for example `web-visitor-alice`; values such as `web:visitor:alice`, `web+visitor+alice`, `.`, `..`, or values with path separators are rejected.
+- With empty `target_uri`, non-ROOT retrieval searches the current user root (`viking://user/{user}`) and shared `viking://resources`.
+- To filter the current user's peer collection to one peer for filesystem and retrieval operations, send `X-OpenViking-Actor-Peer: <peer_id>` or construct the SDK/CLI client with `actor_peer_id`. See [Multi-Tenant: Peer Collection Filter](../concepts/11-multi-tenant.md#peer-restricted-view).
- Current-user shorthand target URIs such as `viking://user/memories`, `viking://user/resources`, and `viking://user/skills` are canonicalized from the authenticated request identity.
**FindResult Structure**
@@ -201,11 +199,13 @@ results = client.find(
target_uri="viking://user/resources"
)
-# Include a specific peer's memories and resources in default retrieval
-results = client.find(
- "invoice follow-up",
- peer_id="web-visitor-alice"
+# Search with the peer collection filtered to one peer
+peer_client = ov.SyncHTTPClient(
+ url="http://localhost:1933",
+ api_key="your-key",
+ actor_peer_id="web-visitor-alice",
)
+peer_results = peer_client.find("invoice follow-up")
# Search only in skills
results = client.find(
@@ -316,7 +316,6 @@ The `search()` method adds session context understanding and intent analysis cap
| session | Session | No | None | Session for context-aware search (SDK) |
| session_id | str | No | None | Session ID for context-aware search (HTTP) |
| context_type | str \| List[str] | No | None | Limit results to one or more `ContextType` values: `memory`, `resource`, or `skill` |
-| peer_id | str | No | None | Stable interaction peer ID. When searching default user-scoped targets, results include this peer's memories and resources in addition to current-user content. 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 |
@@ -327,7 +326,7 @@ The `search()` method adds session context understanding and intent analysis cap
| include_provenance | bool | No | False | Include provenance/query-plan details in serialized result |
| telemetry | bool \| object | No | False | Attach telemetry data to response |
-`search()` uses the same target resolution rules as `find()`: default retrieval includes current-user memories/resources/skills plus shared resources, and `peer_id` adds only that peer's memories/resources.
+`search()` uses the same target resolution rules as `find()`, including the peer collection filter selected by `X-OpenViking-Actor-Peer` or SDK `actor_peer_id`.
#### 3. Usage Examples
diff --git a/docs/en/concepts/11-multi-tenant.md b/docs/en/concepts/11-multi-tenant.md
index db5afc292..d5103569d 100644
--- a/docs/en/concepts/11-multi-tenant.md
+++ b/docs/en/concepts/11-multi-tenant.md
@@ -102,17 +102,31 @@ But the underlying storage automatically gains an account prefix:
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
+### Filesystem And Retrieval Layer
-Semantic retrieval is tenant-aware as well:
+Filesystem operations and semantic retrieval are tenant-aware:
- Non-ROOT requests are automatically filtered by `account_id`
- `resources` can include account-shared resources
- `memory`, user resources, and `skill` are further filtered by the current user space
-- Passing `peer_id` adds only that peer's memories/resources; skills remain user-scoped
+- An actor peer filters `viking://user/{user}/peers` to one peer for filesystem and retrieval operations
This keeps "what you can search" aligned with "what you can read."
+### Peer Collection Filter
+
+`peer_id` is a content scope inside the current user boundary. It never changes the
+tenant or user identity.
+
+Set `X-OpenViking-Actor-Peer: <peer_id>` (or SDK/CLI `actor_peer_id`) when a request
+should only see one peer from the current user's peer collection:
+
+- Empty-target retrieval still includes the current user root and shared `viking://resources`.
+- When retrieval resolves `viking://user/{user}/peers`, only that peer's memories/resources are selected.
+- Filesystem operations cannot read, list/tree, grep/find/search, write, move, or delete another peer under `viking://user/{user}/peers`.
+- User-scoped memories, resources, skills, shared resources, and session ownership are otherwise unchanged.
+- The peer ID must be a safe single path segment, for example `web-visitor-alice`.
+
## Standard Usage Flow
### 1. Enable multi-tenancy
@@ -277,7 +291,7 @@ caller identity it should run as.
### 2. `peer_id` does not define the tenant
`peer_id` identifies an interaction peer under the current user. It does not create a tenant,
-but it can select a peer content subspace such as
+but peer content can be selected through explicit peer URIs or the peer collection filter, such as
`viking://user/{user_id}/peers/{peer_id}/memories` or
`viking://user/{user_id}/peers/{peer_id}/resources`.
diff --git a/docs/en/guides/04-authentication.md b/docs/en/guides/04-authentication.md
index 6f8d2da82..9c0c78d32 100644
--- a/docs/en/guides/04-authentication.md
+++ b/docs/en/guides/04-authentication.md
@@ -217,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.
-- Use request-level `peer_id` for stable interaction peers in session memory and retrieval APIs.
+- Use `peer_id` in session-message bodies for stable speaker attribution. Use `X-OpenViking-Actor-Peer` to filter the current user's peer collection for filesystem and retrieval operations.
- `/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.
diff --git a/docs/en/guides/06-mcp-integration.md b/docs/en/guides/06-mcp-integration.md
index f20cd4855..f9cf0d849 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), `peer_id` (optional), `limit`, `min_score` |
+| `search` | Semantic search across memories, resources, and skills | `query`, `target_uri` (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/zh/agent-integrations/07-langchain-langgraph.md b/docs/zh/agent-integrations/07-langchain-langgraph.md
index 23a56ab6f..a5b8b5e02 100644
--- a/docs/zh/agent-integrations/07-langchain-langgraph.md
+++ b/docs/zh/agent-integrations/07-langchain-langgraph.md
@@ -25,22 +25,22 @@ tools = create_openviking_tools(
## Peer 身份
-所有会读写 session memory 的适配器都支持 `peer_id`。当同一个 OpenViking user 需要和多个稳定外部对象交互时使用它,例如不同 agent、机器人,或共享会话中的不同人。
+传入 `actor_peer_id` 可以在文件系统和检索操作中过滤当前用户的 peer 集合。session message capture 仍可使用 `peer_id` 表达每条消息的说话人归属。
```python
retriever = OpenVikingRetriever(
url="http://localhost:1933",
- peer_id="assistant-a",
+ actor_peer_id="assistant-a",
)
chain = with_openviking_context(
runnable,
session_id="support-thread-1",
- peer_id="assistant-a",
+ actor_peer_id="assistant-a",
)
```
-动态运行时,`with_openviking_context()` 默认也会读取 `config["configurable"]["peer_id"]`:
+动态运行时,`with_openviking_context()` 默认仍会读取 `config["configurable"]["peer_id"]`,用于 captured message 的归属:
```python
chain.invoke(
diff --git a/docs/zh/api/04-skills.md b/docs/zh/api/04-skills.md
index 47485e282..09bb67996 100644
--- a/docs/zh/api/04-skills.md
+++ b/docs/zh/api/04-skills.md
@@ -188,7 +188,7 @@ This tool wraps the MCP tool `search-web`. Call this when the user needs functio
- **目标规则**:
- Skills 始终是 user-scoped;`add_skill` 不接受 `to`、`parent` 或 `root_uri`。
- - 不支持 peer-scoped skill 根;带 `peer_id` 的检索只额外加入 peer memories/resources,不加入 peer skills。
+ - 不支持 peer-scoped skill 根;actor peer 过滤只作用于 peer memories/resources,不作用于 peer skills。
- 列出、读取、删除或搜索技能时,可以使用 `viking://user/skills/...` 作为当前用户短写。
- **支持的数据格式**:
diff --git a/docs/zh/api/06-retrieval.md b/docs/zh/api/06-retrieval.md
index 6d1d68891..b44debf06 100644
--- a/docs/zh/api/06-retrieval.md
+++ b/docs/zh/api/06-retrieval.md
@@ -57,7 +57,6 @@ OpenViking 提供多种检索方法,包括简单的向量相似度搜索、带
| query | str | 是 | - | 搜索查询字符串 |
| target_uri | str \| List[str] | 否 | "" | 限制搜索范围到指定的 URI 前缀 |
| context_type | str \| List[str] | 否 | None | 限定一个或多个 `ContextType` 取值:`memory`、`resource` 或 `skill` |
-| peer_id | str | 否 | None | 稳定交互对象 ID。检索默认 user-scoped 目标时,会在当前用户内容之外额外检索该 peer 的 memories 和 resources。CLI `--peer-id` 会映射到这个字段 |
| limit | int | 否 | 10 | 最大返回结果数 |
| node_limit | int | 否 | None | 可选 HTTP 别名;如果提供,会覆盖 limit |
| score_threshold | float | 否 | None | 最低相关性分数阈值 |
@@ -70,9 +69,8 @@ OpenViking 提供多种检索方法,包括简单的向量相似度搜索、带
| telemetry | bool \| object | 否 | False | 在响应中附带遥测数据 |
**目标解析说明**:
-- `target_uri` 为空时,非 ROOT 检索默认搜索当前用户 memories、公共 `viking://resources`、当前用户 resources 和当前用户 skills。
-- 传入 `peer_id` 时,OpenViking 会额外搜索 `viking://user/{user_id}/peers/{peer_id}/memories` 和 `viking://user/{user_id}/peers/{peer_id}/resources`,不会搜索 peer skills。
-- `peer_id` 必须是安全的单段路径标识,例如 `web-visitor-alice`;`web:visitor:alice`、`web+visitor+alice`、`.`、`..` 或包含路径分隔符的值会被拒绝。
+- `target_uri` 为空时,非 ROOT 检索默认搜索当前用户根 `viking://user/{user}` 和公共 `viking://resources`。
+- 如需在文件系统和检索操作中把当前用户的 peer 集合过滤到某一个 peer,发送 `X-OpenViking-Actor-Peer: <peer_id>`,或用 SDK/CLI client 的 `actor_peer_id` 初始化。见 [多租户:Peer 集合过滤](../concepts/11-multi-tenant.md#peer-restricted-view)。
- `viking://user/memories`、`viking://user/resources`、`viking://user/skills` 等当前用户短写 target URI 会按认证请求身份 canonicalize。
**FindResult 结构**
@@ -202,11 +200,13 @@ results = client.find(
target_uri="viking://user/resources"
)
-# 在默认检索范围中额外加入指定 peer 的 memories/resources
-results = client.find(
- "invoice follow-up",
- peer_id="web-visitor-alice"
+# 检索时把 peer 集合过滤到一个 peer
+peer_client = ov.SyncHTTPClient(
+ url="http://localhost:1933",
+ api_key="your-key",
+ actor_peer_id="web-visitor-alice",
)
+peer_results = peer_client.find("invoice follow-up")
# 仅在技能中搜索
results = client.find(
@@ -317,7 +317,6 @@ openviking find "how to authenticate users" -L 1,2
| session | Session | 否 | None | 用于上下文感知搜索的会话(SDK)|
| session_id | str | 否 | None | 用于上下文感知搜索的会话 ID(HTTP)|
| context_type | str \| List[str] | 否 | None | 限定一个或多个 `ContextType` 取值:`memory`、`resource` 或 `skill` |
-| peer_id | str | 否 | None | 稳定交互对象 ID。检索默认 user-scoped 目标时,会在当前用户内容之外额外检索该 peer 的 memories 和 resources。CLI `--peer-id` 会映射到这个字段 |
| limit | int | 否 | 10 | 最大返回结果数 |
| node_limit | int | 否 | None | 可选 HTTP 别名;如果提供,会覆盖 limit |
| score_threshold | float | 否 | None | 最低相关性分数阈值 |
@@ -329,7 +328,7 @@ openviking find "how to authenticate users" -L 1,2
| include_provenance | bool | 否 | False | 在序列化结果中附带 provenance / query-plan 细节 |
| telemetry | bool \| object | 否 | False | 在响应中附带遥测数据 |
-`search()` 使用和 `find()` 相同的目标解析规则:默认检索包含当前用户 memories/resources/skills 和公共 resources,`peer_id` 只额外加入该 peer 的 memories/resources。
+`search()` 使用和 `find()` 相同的目标解析规则,包括由 `X-OpenViking-Actor-Peer` 或 SDK `actor_peer_id` 选择的 peer 集合过滤。
#### 3. 使用示例
diff --git a/docs/zh/concepts/11-multi-tenant.md b/docs/zh/concepts/11-multi-tenant.md
index a83963a35..a913792bf 100644
--- a/docs/zh/concepts/11-multi-tenant.md
+++ b/docs/zh/concepts/11-multi-tenant.md
@@ -102,17 +102,32 @@ viking://user/alice/peers/web-visitor-alice/resources/
因此多租户隔离不是靠“不同 URI 前缀”,而是靠请求上下文中的 `account_id` 和 `user_id` 共同生效。
-### 检索层
+### 文件系统与检索层
-语义检索同样受租户约束:
+文件系统操作和语义检索都受租户约束:
- 非 ROOT 请求会自动按 `account_id` 过滤
- `resources` 会允许检索 account 内共享资源
- `memory`、用户资源和 `skill` 会进一步按当前 `user space` 过滤
-- 传入 `peer_id` 时只额外加入该 peer 的 memories/resources;skills 仍保持 user-scoped
+- Actor peer 会把 `viking://user/{user}/peers` 过滤到一个 peer,并作用于文件系统和检索操作
这意味着“能搜到什么”与“能读到什么”保持一致,不会因为向量召回而越权。
+<a id="peer-restricted-view"></a>
+
+### Peer 集合过滤
+
+`peer_id` 是当前 user 边界内的内容范围,不会改变 tenant 或 user 身份。
+
+当一次请求只应该看到当前用户 peer 集合中的某一个 peer 时,设置
+`X-OpenViking-Actor-Peer: <peer_id>`,或使用 SDK/CLI 的 `actor_peer_id`:
+
+- 空 target 检索仍包含当前用户根和公共 `viking://resources`。
+- 检索解析到 `viking://user/{user}/peers` 时,只选择该 peer 的 memories/resources。
+- 文件系统操作不能 read、list、tree、grep/search/find、write、move 或 delete `viking://user/{user}/peers` 下的其他 peer。
+- User-scoped memories、resources、skills、共享 resources 和 session 归属不因 actor peer 改变。
+- peer ID 必须是安全的单段路径标识,例如 `web-visitor-alice`。
+
## 标准使用流程
### 1. 启用多租户
@@ -273,8 +288,9 @@ Root key 主要用于:
### 2. `peer_id` 不决定 account
-`peer_id` 表示当前用户下的交互对象。它不创建租户,但可以选择当前用户内的 peer 内容子空间,
-例如 `viking://user/{user_id}/peers/{peer_id}/memories` 或
+`peer_id` 表示当前用户下的交互对象。它不创建租户,但可以通过显式 peer URI 或
+peer 集合过滤选择当前用户内的 peer 内容子空间,例如
+`viking://user/{user_id}/peers/{peer_id}/memories` 或
`viking://user/{user_id}/peers/{peer_id}/resources`。
- account 边界由 `account_id` 决定
diff --git a/docs/zh/guides/06-mcp-integration.md b/docs/zh/guides/06-mcp-integration.md
index 2b56d7f1a..ebafb6866 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`(可选), `peer_id`(可选), `limit`, `min_score` |
+| `search` | 语义搜索记忆、资源和技能 | `query`, `target_uri`(可选), `limit`, `min_score` |
| `read` | 读取一个或多个 `viking://` URI 的内容 | `uris`(单个字符串或数组) |
| `list` | 列出 `viking://` 目录下的条目 | `uri`, `recursive`(可选) |
| `store` | 存储消息到长期记忆(触发记忆提取) | `messages`(`{role, content}` 列表) |
diff --git a/openviking/async_client.py b/openviking/async_client.py
index 9df8874ea..7fd936723 100644
--- a/openviking/async_client.py
+++ b/openviking/async_client.py
@@ -47,12 +47,14 @@ class AsyncOpenViking:
def __init__(
self,
path: Optional[str] = None,
+ actor_peer_id: Optional[str] = None,
):
"""
Initialize OpenViking client (embedded mode).
Args:
path: Local storage path (overrides ov.conf storage path).
+ actor_peer_id: Optional view filter for the current user's peer collection.
"""
# Singleton guard for repeated initialization
if hasattr(self, "_singleton_initialized") and self._singleton_initialized:
@@ -65,6 +67,7 @@ class AsyncOpenViking:
self._client: BaseClient = LocalClient(
path=path,
+ actor_peer_id=actor_peer_id,
)
self._singleton_initialized = True
@@ -372,7 +375,6 @@ 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.
@@ -403,7 +405,6 @@ class AsyncOpenViking:
until=until,
time_field=time_field,
level=level,
- peer_id=peer_id,
)
async def find(
@@ -419,7 +420,6 @@ 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()
@@ -435,7 +435,6 @@ 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.py
index 094730eec..e22366a83 100644
--- a/openviking/client/local.py
+++ b/openviking/client/local.py
@@ -61,19 +61,25 @@ class LocalClient(BaseClient):
self,
path: Optional[str] = None,
user: Optional[UserIdentifier] = None,
+ actor_peer_id: Optional[str] = None,
):
"""Initialize LocalClient.
Args:
path: Local storage path (overrides ov.conf storage path)
user: Explicit account/user identity for embedded mode
+ actor_peer_id: Optional view filter for the current user's peer collection.
"""
self._service = OpenVikingService(
path=path,
user=user or UserIdentifier.the_default_user(),
)
self._user = self._service.user
- self._ctx = RequestContext(user=self._user, role=Role.USER)
+ self._ctx = RequestContext(
+ user=self._user,
+ role=Role.USER,
+ actor_peer_id=normalize_peer_id(actor_peer_id),
+ )
@property
def service(self) -> OpenVikingService:
@@ -304,7 +310,6 @@ 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, context_type, since, until, time_field)
@@ -315,7 +320,6 @@ 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,
@@ -341,7 +345,6 @@ 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, context_type, since, until, time_field)
@@ -355,7 +358,6 @@ 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,
diff --git a/openviking/core/directories.py b/openviking/core/directories.py
index 96914fcbf..187545e57 100644
--- a/openviking/core/directories.py
+++ b/openviking/core/directories.py
@@ -154,10 +154,14 @@ class DirectoryInitializer:
return get_viking_fs()
async def initialize_account_directories(self, ctx: RequestContext) -> int:
- """Initialize account-shared scope roots."""
+ """Initialize account-shared scope roots.
+
+ ``viking://user`` is a current-user shorthand at API boundaries. Its
+ concrete metadata belongs to ``viking://user/{user_id}`` and is created
+ by ``initialize_user_directories``.
+ """
count = 0
scope_roots = {
- "user": PRESET_DIRECTORIES["user"],
"resources": PRESET_DIRECTORIES["resources"],
}
for scope, defn in scope_roots.items():
diff --git a/openviking/core/namespace.py b/openviking/core/namespace.py
index aa75f2d4b..717e9e5ca 100644
--- a/openviking/core/namespace.py
+++ b/openviking/core/namespace.py
@@ -197,6 +197,40 @@ def visible_roots(ctx: RequestContext) -> list[str]:
]
+def is_hidden_by_actor_peer_view(uri: str, ctx: RequestContext) -> bool:
+ """Return whether uri points to another peer hidden by the actor peer view."""
+ suffix = _actor_peer_view_user_suffix(uri, ctx)
+ return bool(
+ suffix and len(suffix) >= 2 and suffix[0] == "peers" and suffix[1] != ctx.actor_peer_id
+ )
+
+
+def may_include_hidden_actor_peers(uri: str, ctx: RequestContext) -> bool:
+ """Return whether recursive data under uri may include hidden peers."""
+ suffix = _actor_peer_view_user_suffix(uri, ctx)
+ return suffix is not None and (not suffix or suffix == ["peers"])
+
+
+def _actor_peer_view_user_suffix(uri: str, ctx: RequestContext) -> Optional[list[str]]:
+ """Return uri's suffix under the current user root when actor peer view is active.
+
+ The actor peer view filters only the current user's ``peers`` collection.
+ It applies to filesystem and retrieval views, but does not change
+ tenant/user identity or hide non-peer user content.
+ """
+ if not ctx.actor_peer_id:
+ return None
+ try:
+ canonical_uri = canonicalize_uri(uri, ctx)
+ except NamespaceShapeError:
+ return None
+ parts = uri_parts(canonical_uri)
+ user_root_parts = ["user", ctx.user.user_id]
+ if parts[: len(user_root_parts)] != user_root_parts:
+ return None
+ return parts[len(user_root_parts) :]
+
+
def resolve_uri(
uri: str,
ctx: Optional[RequestContext] = None,
diff --git a/openviking/core/retrieval_targets.py b/openviking/core/retrieval_targets.py
index 1b5ad5f2e..5cffbb861 100644
--- a/openviking/core/retrieval_targets.py
+++ b/openviking/core/retrieval_targets.py
@@ -1,6 +1,6 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
-"""Retrieval-only target resolution for search/find."""
+"""Target resolution for search/find."""
from dataclasses import dataclass
from typing import List, Optional, Union
@@ -9,11 +9,12 @@ from openviking.core.namespace import (
NamespaceShapeError,
canonical_user_root,
canonicalize_uri,
+ is_hidden_by_actor_peer_view,
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.exceptions import InvalidArgumentError, PermissionDeniedError
from openviking_cli.retrieve import ContextType
from openviking_cli.utils.uri import VikingURI
@@ -29,20 +30,18 @@ class ResolvedRetrievalTargets:
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=default_target_directories(ctx),
)
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):
+ for target_dir in _target_directories_for_uri(target, ctx=ctx):
if target_dir not in target_directories:
target_directories.append(target_dir)
return ResolvedRetrievalTargets(
@@ -54,31 +53,33 @@ def resolve_retrieval_targets(
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_user_scoped_targets(ctx, peer_id, "memories")
+ if ctx.actor_peer_id:
+ return [
+ f"{user_root}/memories",
+ f"{user_root}/peers/{ctx.actor_peer_id}/memories",
+ ]
+ return [user_root]
if context_type == ContextType.RESOURCE:
- return _default_resource_targets(ctx, peer_id)
+ if ctx.actor_peer_id:
+ return [
+ "viking://resources",
+ f"{user_root}/resources",
+ f"{user_root}/peers/{ctx.actor_peer_id}/resources",
+ ]
+ return ["viking://resources", user_root]
if context_type == ContextType.SKILL:
return _default_skill_targets(ctx)
- return [
- *_default_user_scoped_targets(ctx, peer_id, "memories"),
- *_default_resource_targets(ctx, peer_id),
- *_default_skill_targets(ctx),
- ]
-
-
-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
+ if ctx.actor_peer_id:
+ return ["viking://resources", *_default_user_root_targets(ctx)]
+ return [user_root, "viking://resources"]
def _canonicalize_target_uris(
@@ -103,59 +104,53 @@ 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_user_root_targets(ctx, peer_id)
+ return _default_user_root_targets(ctx)
- peer_target = _resolve_peer_target(target_uri, ctx=ctx, peer_id=peer_id)
+ peer_target = _resolve_peer_target(target_uri, ctx=ctx)
if peer_target is not None:
return peer_target
for segment in ("memories", "resources", "skills"):
if _is_default_user_content_root(target_uri, ctx, segment):
- if segment == "skills":
- return _default_skill_targets(ctx)
- return _default_user_scoped_targets(ctx, peer_id, segment)
+ return [target_uri]
return [target_uri]
-def _default_user_root_targets(ctx: RequestContext, peer_id: Optional[str]) -> List[str]:
- return [
- *_default_user_scoped_targets(ctx, peer_id, "memories"),
- *_default_user_scoped_targets(ctx, peer_id, "resources"),
- *_default_skill_targets(ctx),
- ]
-
-
-def _default_resource_targets(ctx: RequestContext, peer_id: Optional[str]) -> List[str]:
- return [
- "viking://resources",
- *_default_user_scoped_targets(ctx, peer_id, "resources"),
- ]
+def _default_user_root_targets(ctx: RequestContext) -> List[str]:
+ user_root = canonical_user_root(ctx)
+ if not ctx.actor_peer_id:
+ return [user_root]
+ return _dedupe(
+ [
+ f"{user_root}/memories",
+ f"{user_root}/resources",
+ *_default_skill_targets(ctx),
+ *_actor_peer_targets(ctx),
+ ]
+ )
def _default_skill_targets(ctx: RequestContext) -> List[str]:
return [f"{canonical_user_root(ctx)}/skills"]
-def _default_user_scoped_targets(
- ctx: RequestContext,
- peer_id: Optional[str],
- segment: str,
-) -> List[str]:
- targets = [f"{canonical_user_root(ctx)}/{segment}"]
- if peer_id:
- targets.append(f"{canonical_user_root(ctx)}/peers/{peer_id}/{segment}")
- return targets
+def _actor_peer_targets(ctx: RequestContext) -> List[str]:
+ if not ctx.actor_peer_id:
+ return []
+ peer_root = f"{canonical_user_root(ctx)}/peers/{ctx.actor_peer_id}"
+ return [
+ f"{peer_root}/memories",
+ f"{peer_root}/resources",
+ ]
def _resolve_peer_target(
target_uri: str,
*,
ctx: RequestContext,
- peer_id: Optional[str],
) -> Optional[List[str]]:
parts = uri_parts(target_uri)
user_root_parts = uri_parts(canonical_user_root(ctx))
@@ -167,11 +162,13 @@ def _resolve_peer_target(
return None
if len(suffix) == 1:
- raise InvalidArgumentError("target_uri must not point at all peer contexts.")
+ if ctx.actor_peer_id:
+ return _actor_peer_targets(ctx)
+ return [target_uri]
target_peer_id = _normalize_peer_id(suffix[1])
- if peer_id and target_peer_id != peer_id:
- raise InvalidArgumentError("target_uri peer does not match peer_id.")
+ if is_hidden_by_actor_peer_view(target_uri, ctx):
+ raise PermissionDeniedError("Actor peer cannot access another peer's context.")
peer_root = f"{canonical_user_root(ctx)}/peers/{target_peer_id}"
if len(suffix) == 2:
@@ -184,6 +181,21 @@ def _resolve_peer_target(
return [target_uri]
+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 _dedupe(items: List[str]) -> List[str]:
+ deduped: List[str] = []
+ for item in items:
+ if item not in deduped:
+ deduped.append(item)
+ return deduped
+
+
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("/")}
diff --git a/openviking/integrations/langchain/client.py b/openviking/integrations/langchain/client.py
index 49a4dab1f..e81ca3260 100644
--- a/openviking/integrations/langchain/client.py
+++ b/openviking/integrations/langchain/client.py
@@ -63,6 +63,7 @@ class OpenVikingConnection:
account: str | None = None
user: str | None = None
user_id: str | None = None
+ actor_peer_id: str | None = None
path: str | None = None
timeout: float = 60.0
extra_headers: dict[str, str] | None = None
@@ -212,13 +213,14 @@ def _create_client_from_connection(connection: OpenVikingConnection) -> Any:
account=connection.account,
user=connection.user,
user_id=connection.user_id,
+ actor_peer_id=connection.actor_peer_id,
timeout=connection.timeout,
extra_headers=connection.extra_headers,
)
else:
from openviking.sync_client import SyncOpenViking
- client = SyncOpenViking(path=connection.path)
+ client = SyncOpenViking(path=connection.path, actor_peer_id=connection.actor_peer_id)
if connection.auto_initialize and hasattr(client, "initialize"):
if not getattr(client, "_initialized", False):
diff --git a/openviking/integrations/langchain/context.py b/openviking/integrations/langchain/context.py
index 84bcaa18b..a1d34b212 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,
+ actor_peer_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,6 +79,7 @@ class OpenVikingSessionContextAssembler:
account=account,
user=user,
user_id=user_id,
+ actor_peer_id=actor_peer_id,
path=path,
timeout=timeout,
extra_headers=extra_headers,
@@ -91,18 +92,17 @@ class OpenVikingSessionContextAssembler:
account=account,
user=user,
user_id=user_id,
+ actor_peer_id=actor_peer_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_context
self.include_active_messages = include_active_messages
self.include_recall = include_recall
@@ -114,7 +114,6 @@ class OpenVikingSessionContextAssembler:
*,
session_id: str,
query: str = "",
- peer_id: str | None = None,
) -> OpenVikingAssembledContext:
client = self._get_client()
self._ensure_session(client, session_id)
@@ -122,7 +121,6 @@ class OpenVikingSessionContextAssembler:
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(
@@ -162,7 +160,6 @@ class OpenVikingSessionContextAssembler:
self,
session_id: str,
query: str,
- peer_id: str | None,
) -> list[Any]:
if not self.include_recall or not query:
return []
@@ -171,7 +168,6 @@ class OpenVikingSessionContextAssembler:
_retriever_for_session(
self.retriever,
session_id,
- peer_id=peer_id,
).invoke(query)
)
except Exception:
@@ -234,6 +230,7 @@ def with_openviking_context(
auto_initialize: bool = True,
session_id: str | None = None,
peer_id: str | None = None,
+ actor_peer_id: str | None = None,
target_uri: str | list[str] = "",
limit: int = 5,
score_threshold: float | None = None,
@@ -255,12 +252,12 @@ def with_openviking_context(
account=account,
user=user,
user_id=user_id,
+ actor_peer_id=actor_peer_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,
@@ -284,6 +281,7 @@ def with_openviking_context(
account=account,
user=user,
user_id=user_id,
+ actor_peer_id=actor_peer_id,
path=path,
timeout=timeout,
extra_headers=extra_headers,
@@ -342,7 +340,6 @@ def with_openviking_context(
assembled = assembler.assemble(
session_id=resolved_session_id,
query=query,
- peer_id=resolved_peer_id,
)
if not assembled.block:
return input_value
@@ -398,16 +395,12 @@ def _validate_session_id(value: Any, *, key: str) -> str:
def _retriever_for_session(
retriever: Any,
session_id: str,
- *,
- peer_id: str | None = None,
) -> Any:
if hasattr(retriever, "model_copy"):
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
diff --git a/openviking/integrations/langchain/history.py b/openviking/integrations/langchain/history.py
index ba5996231..9af0893c7 100644
--- a/openviking/integrations/langchain/history.py
+++ b/openviking/integrations/langchain/history.py
@@ -47,6 +47,7 @@ class OpenVikingChatMessageHistory(BaseChatMessageHistory):
account: str | None = None,
user: str | None = None,
user_id: str | None = None,
+ actor_peer_id: str | None = None,
path: str | None = None,
timeout: float = 60.0,
extra_headers: dict[str, str] | None = None,
@@ -74,6 +75,7 @@ class OpenVikingChatMessageHistory(BaseChatMessageHistory):
account=account,
user=user,
user_id=user_id,
+ actor_peer_id=actor_peer_id,
path=path,
timeout=timeout,
extra_headers=extra_headers,
diff --git a/openviking/integrations/langchain/middleware.py b/openviking/integrations/langchain/middleware.py
index 54c56d828..d3038b70b 100644
--- a/openviking/integrations/langchain/middleware.py
+++ b/openviking/integrations/langchain/middleware.py
@@ -66,6 +66,7 @@ class OpenVikingContextMiddleware(AgentMiddleware):
account: str | None = None,
user: str | None = None,
user_id: str | None = None,
+ actor_peer_id: str | None = None,
path: str | None = None,
target_uri: str | list[str] = "",
limit: int = 5,
@@ -89,6 +90,7 @@ class OpenVikingContextMiddleware(AgentMiddleware):
account=account,
user=user,
user_id=user_id,
+ actor_peer_id=actor_peer_id,
path=path,
)
self.retriever = retriever or OpenVikingRetriever(
@@ -98,9 +100,9 @@ class OpenVikingContextMiddleware(AgentMiddleware):
account=account,
user=user,
user_id=user_id,
+ actor_peer_id=actor_peer_id,
path=path,
target_uri=target_uri,
- peer_id=peer_id,
limit=limit,
score_threshold=score_threshold,
search_mode="search",
@@ -113,9 +115,9 @@ class OpenVikingContextMiddleware(AgentMiddleware):
account=account,
user=user,
user_id=user_id,
+ actor_peer_id=actor_peer_id,
path=path,
target_uri=target_uri,
- peer_id=peer_id,
limit=limit,
score_threshold=score_threshold,
token_budget=token_budget,
@@ -125,7 +127,7 @@ 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 = peer_id
self.peer_id_resolver = peer_id_resolver
self.capture_on_after_agent = capture_on_after_agent
self.commit_policy = commit_policy
@@ -152,7 +154,6 @@ class OpenVikingContextMiddleware(AgentMiddleware):
assembled = self.assembler.assemble(
session_id=session_id,
query=query,
- peer_id=peer_id,
)
context_block = assembled.block
if not context_block:
diff --git a/openviking/integrations/langchain/retrievers.py b/openviking/integrations/langchain/retrievers.py
index 05e4483a9..e38009cc6 100644
--- a/openviking/integrations/langchain/retrievers.py
+++ b/openviking/integrations/langchain/retrievers.py
@@ -38,6 +38,7 @@ class OpenVikingRetriever(BaseRetriever):
account: str | None = None
user: str | None = None
user_id: str | None = None
+ actor_peer_id: str | None = None
path: str | None = None
timeout: float = 60.0
extra_headers: dict[str, str] | None = None
@@ -46,7 +47,6 @@ class OpenVikingRetriever(BaseRetriever):
target_uri: str | list[str] = ""
search_mode: Literal["find", "search"] = "find"
session_id: str | None = None
- peer_id: str | None = None
limit: int = 10
score_threshold: float | None = None
filter: dict[str, Any] | None = None
@@ -68,6 +68,7 @@ class OpenVikingRetriever(BaseRetriever):
account=self.account,
user=self.user,
user_id=self.user_id,
+ actor_peer_id=self.actor_peer_id,
path=self.path,
timeout=self.timeout,
extra_headers=self.extra_headers,
@@ -85,7 +86,6 @@ 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.py
index 28afccf06..ab80d012b 100644
--- a/openviking/integrations/langchain/store.py
+++ b/openviking/integrations/langchain/store.py
@@ -60,6 +60,7 @@ class OpenVikingStore(BaseStore):
account: str | None = None,
user: str | None = None,
user_id: str | None = None,
+ actor_peer_id: str | None = None,
path: str | None = None,
root_uri: str = "viking://user/memories/langgraph_store",
index: bool | list[str] | None = None,
@@ -67,7 +68,6 @@ 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,6 +79,7 @@ class OpenVikingStore(BaseStore):
account=account,
user=user,
user_id=user_id,
+ actor_peer_id=actor_peer_id,
path=path,
auto_initialize=auto_initialize,
)
@@ -87,7 +88,6 @@ class OpenVikingStore(BaseStore):
self.wait = wait
self.timeout = timeout
self.search_fetch_limit = search_fetch_limit
- self.peer_id = peer_id
self._client_cache: Any = None
def batch(self, ops: Iterable[Any]) -> list[Any]:
@@ -231,7 +231,6 @@ 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] = []
diff --git a/openviking/integrations/langchain/testing.py b/openviking/integrations/langchain/testing.py
index 10ef9a4e2..6d437b253 100644
--- a/openviking/integrations/langchain/testing.py
+++ b/openviking/integrations/langchain/testing.py
@@ -44,10 +44,8 @@ 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,
@@ -55,7 +53,6 @@ class InMemoryOpenVikingClient:
"limit": limit,
"score_threshold": score_threshold,
"filter": filter,
- "peer_id": normalized_peer_id,
}
)
return self._search(query, target_uri, limit, score_threshold)
@@ -68,10 +65,8 @@ 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,
@@ -80,7 +75,6 @@ class InMemoryOpenVikingClient:
"limit": limit,
"score_threshold": score_threshold,
"filter": filter,
- "peer_id": normalized_peer_id,
}
)
session_text = " ".join(
diff --git a/openviking/integrations/langchain/tools.py b/openviking/integrations/langchain/tools.py
index 97af2b40e..90ebbc555 100644
--- a/openviking/integrations/langchain/tools.py
+++ b/openviking/integrations/langchain/tools.py
@@ -52,6 +52,7 @@ def create_openviking_tools(
account: str | None = None,
user: str | None = None,
user_id: str | None = None,
+ actor_peer_id: str | None = None,
path: str | None = None,
timeout: float = 60.0,
extra_headers: dict[str, str] | None = None,
@@ -81,6 +82,7 @@ def create_openviking_tools(
account=account,
user=user,
user_id=user_id,
+ actor_peer_id=actor_peer_id,
path=path,
timeout=timeout,
extra_headers=extra_headers,
@@ -108,7 +110,6 @@ def create_openviking_tools(
"find",
query=query,
target_uri=target_uri,
- peer_id=peer_id,
limit=limit,
score_threshold=min_score,
)
@@ -138,7 +139,6 @@ def create_openviking_tools(
query=query,
target_uri=target_uri,
session_id=session_id,
- peer_id=peer_id,
limit=limit,
score_threshold=min_score,
)
diff --git a/openviking/server/auth.py b/openviking/server/auth.py
index 9f961013b..eca3d3bd9 100644
--- a/openviking/server/auth.py
+++ b/openviking/server/auth.py
@@ -7,6 +7,7 @@ from typing import Optional
from fastapi import Depends, Header, Request
+from openviking.core.peer_id import normalize_peer_id
from openviking.server.identity import (
AuthMode,
RequestContext,
@@ -96,6 +97,16 @@ def _normalize_request_value(value: object) -> Optional[str]:
return None
+def normalize_actor_peer_header(value: Optional[str]) -> Optional[str]:
+ normalized = _normalize_header_value(value)
+ if normalized and ("/" in normalized or "\\" in normalized):
+ raise InvalidArgumentError("actor_peer_id must not contain path separators.")
+ try:
+ return normalize_peer_id(normalized)
+ except ValueError as exc:
+ raise InvalidArgumentError(str(exc)) from exc
+
+
def _explicit_identity_from_request(request: Request) -> tuple[Optional[str], Optional[str]]:
path_params = getattr(request, "path_params", {}) or {}
query_params = request.query_params
@@ -331,6 +342,7 @@ async def resolve_identity(
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"),
) -> RequestContext:
"""Convert ResolvedIdentity to RequestContext."""
path = request.url.path
@@ -365,6 +377,7 @@ async def get_request_context(
identity.user_id or "default",
),
role=identity.role,
+ actor_peer_id=normalize_actor_peer_header(x_openviking_actor_peer),
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.py
index 164bdbd24..cb4753312 100644
--- a/openviking/server/identity.py
+++ b/openviking/server/identity.py
@@ -48,6 +48,9 @@ class RequestContext:
user: UserIdentifier
role: Role
+ # 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
# 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
diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.py
index 96bd24a64..85b4968e9 100644
--- a/openviking/server/mcp_endpoint.py
+++ b/openviking/server/mcp_endpoint.py
@@ -37,7 +37,7 @@ from openviking.parse.parsers.code.ast.code_tools import (
search_symbols,
)
from openviking.parse.parsers.code.ast.extractor import get_extractor
-from openviking.server.auth import resolve_identity
+from openviking.server.auth import normalize_actor_peer_header, resolve_identity
from openviking.server.dependencies import get_server_config, get_service
from openviking.server.identity import RequestContext
from openviking.server.local_input_guard import (
@@ -146,6 +146,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")
+ )
except (UnauthenticatedError, PermissionDeniedError, InvalidArgumentError) as exc:
status = (
401
@@ -176,6 +179,8 @@ class _IdentityASGIMiddleware:
identity.user_id or "default",
),
role=identity.role,
+ actor_peer_id=actor_peer_id,
+ from_oauth=identity.from_oauth,
)
url_info = {
"x_forwarded_proto": request.headers.get("x-forwarded-proto"),
@@ -211,7 +216,6 @@ 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()
@@ -219,7 +223,6 @@ async def find(
query=query,
ctx=_get_ctx(),
target_uri=target_uri,
- peer_id=peer_id,
limit=limit,
score_threshold=min_score,
level=level,
@@ -235,7 +238,6 @@ 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,7 +250,6 @@ async def search(
query=query,
ctx=ctx,
target_uri=target_uri,
- peer_id=peer_id,
session=session,
limit=limit,
score_threshold=min_score,
diff --git a/openviking/server/routers/search.py b/openviking/server/routers/search.py
index afae542dd..bb3f9f05e 100644
--- a/openviking/server/routers/search.py
+++ b/openviking/server/routers/search.py
@@ -6,10 +6,9 @@ import math
from typing import Any, Dict, List, Literal, Optional, Union
from fastapi import APIRouter, Depends
-from pydantic import BaseModel, model_validator
+from pydantic import BaseModel, ConfigDict
from openviking.core.path_variables import resolve_path_variables
-from openviking.core.peer_id import normalize_peer_id
from openviking.pyagfs.exceptions import AGFSClientError, AGFSNotFoundError
from openviking.server.auth import get_request_context
from openviking.server.dependencies import get_service
@@ -76,10 +75,11 @@ def _resolve_uri_or_uris(uri: Union[str, List[str]]) -> Union[str, List[str]]:
class FindRequest(BaseModel):
"""Request model for find."""
+ model_config = ConfigDict(extra="forbid")
+
query: str
target_uri: Union[str, List[str]] = ""
context_type: Optional[Union[str, List[str]]] = None
- peer_id: Optional[str] = None
limit: int = 10
node_limit: Optional[int] = None
score_threshold: Optional[float] = None
@@ -91,19 +91,15 @@ class FindRequest(BaseModel):
level: Optional[Union[int, str, List[int]]] = None
telemetry: 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."""
+ model_config = ConfigDict(extra="forbid")
+
query: str
target_uri: Union[str, List[str]] = ""
context_type: Optional[Union[str, List[str]]] = None
- peer_id: Optional[str] = None
session_id: Optional[str] = None
limit: int = 10
node_limit: Optional[int] = None
@@ -117,11 +113,6 @@ class SearchRequest(BaseModel):
level: Optional[Union[int, str, List[int]]] = None
telemetry: 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."""
@@ -165,7 +156,6 @@ 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,
@@ -209,7 +199,6 @@ 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/service/search_service.py b/openviking/service/search_service.py
index f192e12d3..f57debb03 100644
--- a/openviking/service/search_service.py
+++ b/openviking/service/search_service.py
@@ -46,7 +46,6 @@ 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,
@@ -79,7 +78,6 @@ class SearchService:
query=query,
ctx=ctx,
target_uri=target_uri,
- peer_id=peer_id,
session_info=session_info,
limit=limit,
score_threshold=score_threshold,
@@ -93,7 +91,6 @@ 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,
@@ -119,7 +116,6 @@ 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.py
index 07a663263..c2c139d47 100644
--- a/openviking/service/session_service.py
+++ b/openviking/service/session_service.py
@@ -17,7 +17,11 @@ from openviking.session.memory.memory_type_registry import MemoryTypeRegistry
from openviking.session.memory_policy import MemoryPolicy
from openviking.storage import VikingDBManager
from openviking.storage.viking_fs import VikingFS
-from openviking_cli.exceptions import AlreadyExistsError, NotFoundError, NotInitializedError
+from openviking_cli.exceptions import (
+ AlreadyExistsError,
+ NotFoundError,
+ NotInitializedError,
+)
from openviking_cli.utils import get_logger
logger = get_logger(__name__)
@@ -218,13 +222,12 @@ class SessionService:
self._ensure_initialized()
session_uri = canonical_session_uri(ctx, session_id)
- if await self.session(ctx, session_id).exists():
- storage_ctx = ctx
- else:
+ session = await self.get(session_id, ctx)
+ if not await session.exists():
self._record_lifecycle_metric("delete", "error")
raise NotFoundError(session_id, "session")
- await self._viking_fs.rm(session_uri, recursive=True, ctx=storage_ctx)
+ await self._viking_fs.rm(session_uri, recursive=True, ctx=ctx)
logger.info(f"Deleted session: {session_id}")
self._record_lifecycle_metric("delete", "ok")
return True
diff --git a/openviking/session/session.py b/openviking/session/session.py
index 2fc980ca0..c4faed666 100644
--- a/openviking/session/session.py
+++ b/openviking/session/session.py
@@ -83,11 +83,33 @@ def _default_memory_counts() -> Dict[str, int]:
def _message_peer_ids(messages: List[Message]) -> set[str]:
- return {
- peer_id
- for message in messages
- if (peer_id := getattr(message, "peer_id", None))
- }
+ return {peer_id for message in messages if (peer_id := getattr(message, "peer_id", None))}
+
+
+@dataclass(frozen=True)
+class _MemoryExtractionScope:
+ allow_self_memory: bool
+ allowed_peer_ids: set[str]
+ include_session_skills: bool
+ memory_types: Optional[set[str]]
+
+
+def _resolve_memory_extraction_scope(
+ ctx: RequestContext,
+ policy: MemoryPolicy,
+ messages: List[Message],
+ *,
+ config_session_skill_extraction_enabled: bool,
+) -> _MemoryExtractionScope:
+ allow_self_memory = policy.self_enabled
+ allowed_peer_ids = _message_peer_ids(messages) if policy.peer_enabled else set()
+
+ return _MemoryExtractionScope(
+ allow_self_memory=allow_self_memory,
+ allowed_peer_ids=allowed_peer_ids,
+ include_session_skills=config_session_skill_extraction_enabled and allow_self_memory,
+ memory_types=policy.memory_types,
+ )
# =====================================================================
@@ -522,7 +544,12 @@ class Session:
def _tool_result_store(self) -> Optional[ToolResultStore]:
if not self._viking_fs:
return None
- return ToolResultStore(self._viking_fs, self._session_uri, self.session_id, self.ctx)
+ return ToolResultStore(
+ self._viking_fs,
+ self._session_uri,
+ self.session_id,
+ self.ctx,
+ )
async def _hydrate_tool_outputs_for_extraction(
self,
@@ -1339,15 +1366,18 @@ class Session:
ov_config.memory.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
+ extraction_scope = _resolve_memory_extraction_scope(
+ self.ctx,
+ effective_policy,
+ extraction_messages,
+ config_session_skill_extraction_enabled=(
+ config_session_skill_extraction_enabled
+ ),
)
- memory_type_filter = effective_policy.memory_types
+ self_memory_enabled = extraction_scope.allow_self_memory
+ allowed_peer_ids = extraction_scope.allowed_peer_ids
+ session_skill_extraction_enabled = extraction_scope.include_session_skills
+ memory_type_filter = extraction_scope.memory_types
long_term_memory_types, execution_memory_types = _split_policy_memory_types(
memory_type_filter
)
@@ -3149,10 +3179,18 @@ class Session:
)
run_async(
- viking_fs.write_file(uri=f"{archive_uri}/.abstract.md", content=abstract, ctx=self.ctx)
+ viking_fs.write_file(
+ uri=f"{archive_uri}/.abstract.md",
+ content=abstract,
+ ctx=self.ctx,
+ )
)
run_async(
- viking_fs.write_file(uri=f"{archive_uri}/.overview.md", content=overview, ctx=self.ctx)
+ viking_fs.write_file(
+ uri=f"{archive_uri}/.overview.md",
+ content=overview,
+ ctx=self.ctx,
+ )
)
logger.debug(f"Written archive: {archive_uri}")
diff --git a/openviking/storage/content_write.py b/openviking/storage/content_write.py
index 184b88d1a..08ef0fedf 100644
--- a/openviking/storage/content_write.py
+++ b/openviking/storage/content_write.py
@@ -57,6 +57,7 @@ class ContentWriteCoordinator:
raise InvalidArgumentError(str(exc)) from exc
self._validate_mode(mode)
self._validate_target_uri(normalized_uri)
+ self._viking_fs._ensure_mutable_access(normalized_uri, ctx)
if mode == "create":
return await self._create_and_write(
diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.py
index 291bbda4a..796e4f0d6 100644
--- a/openviking/storage/viking_fs.py
+++ b/openviking/storage/viking_fs.py
@@ -24,7 +24,11 @@ from datetime import datetime, timezone
from pathlib import PurePath
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
-from openviking.core.namespace import canonicalize_uri
+from openviking.core.namespace import (
+ canonicalize_uri,
+ is_hidden_by_actor_peer_view,
+ may_include_hidden_actor_peers,
+)
from openviking.core.namespace import (
is_accessible as namespace_is_accessible,
)
@@ -330,6 +334,10 @@ class VikingFS:
self._ensure_access(uri, ctx)
real_ctx = self._ctx_or_default(ctx)
normalized_uri, _ = self._normalized_uri_parts(uri)
+ if is_hidden_by_actor_peer_view(normalized_uri, real_ctx) or may_include_hidden_actor_peers(
+ normalized_uri, real_ctx
+ ):
+ raise PermissionDeniedError(f"Access denied for {uri}", resource=normalized_uri)
if real_ctx.role != Role.ROOT and normalized_uri.rstrip("/") == "viking://temp":
raise PermissionDeniedError(
"Temp root is read-only for non-root users",
@@ -802,6 +810,7 @@ class VikingFS:
matches = result.get("matches", [])
results = []
files_scanned_set = set()
+ real_ctx = self._ctx_or_default(ctx)
for match in matches:
match_file = match.get("file", "")
@@ -811,6 +820,8 @@ class VikingFS:
agfs_file_path = self._resolve_grep_match_agfs_path(path, match_file)
file_uri = self._path_to_uri(agfs_file_path, ctx=ctx)
+ if not self._is_accessible(file_uri, real_ctx):
+ continue
files_scanned_set.add(file_uri)
@@ -829,7 +840,9 @@ class VikingFS:
# counting files that produced at least one match (best-effort).
backend_files_scanned = result.get("files_scanned")
if isinstance(backend_files_scanned, int) and backend_files_scanned >= 0:
- files_scanned = backend_files_scanned
+ files_scanned = (
+ len(files_scanned_set) if real_ctx.actor_peer_id else backend_files_scanned
+ )
else:
files_scanned = len(files_scanned_set)
@@ -881,8 +894,12 @@ class VikingFS:
target_canonical_uri = canonicalize_uri(
self._path_to_uri(path, ctx=real_ctx), real_ctx
)
- filter_expr = PathScope("uri", target_canonical_uri, depth=-1)
- result["count"] = await vector_store.count(filter=filter_expr, ctx=real_ctx)
+ if not may_include_hidden_actor_peers(target_canonical_uri, real_ctx):
+ filter_expr = PathScope("uri", target_canonical_uri, depth=-1)
+ result["count"] = await vector_store.count(
+ filter=filter_expr,
+ ctx=real_ctx,
+ )
except Exception as e:
logger.warning(f"[VikingFS] Failed to count nodes for directory stat: {e}")
return result
@@ -1231,7 +1248,6 @@ class VikingFS:
filter: Optional[Dict] = None,
ctx: Optional[RequestContext] = None,
level: Optional[List[int]] = None,
- peer_id: Optional[str] = None,
):
"""Semantic search.
@@ -1255,7 +1271,7 @@ class VikingFS:
)
real_ctx = self._ctx_or_default(ctx)
- retrieval_targets = resolve_retrieval_targets(target_uri, real_ctx, peer_id)
+ retrieval_targets = resolve_retrieval_targets(target_uri, real_ctx)
for target_dir in retrieval_targets.target_directories:
self._ensure_access(target_dir, ctx)
@@ -1324,7 +1340,6 @@ 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.
@@ -1350,7 +1365,7 @@ class VikingFS:
)
real_ctx = self._ctx_or_default(ctx)
- retrieval_targets = resolve_retrieval_targets(target_uri, real_ctx, peer_id)
+ retrieval_targets = resolve_retrieval_targets(target_uri, real_ctx)
primary_target_uri = retrieval_targets.first_explicit_directory
session_summary = (
@@ -1739,6 +1754,8 @@ class VikingFS:
normalized_uri, parts = self._normalized_uri_parts(uri)
if ctx.role == Role.ROOT:
return True
+ if is_hidden_by_actor_peer_view(normalized_uri, ctx):
+ return False
if not parts:
return True
if is_watch_task_control_uri(normalized_uri):
@@ -2051,7 +2068,7 @@ class VikingFS:
ctx: Optional[RequestContext] = None,
) -> None:
"""Write file directly."""
- self._ensure_access(uri, ctx)
+ self._ensure_mutable_access(uri, ctx)
path = self._uri_to_path(uri, ctx=ctx)
await self._ensure_parent_dirs(path, ctx=ctx)
@@ -2139,7 +2156,7 @@ class VikingFS:
ctx: Optional[RequestContext] = None,
) -> None:
"""Write single binary file."""
- self._ensure_access(uri, ctx)
+ self._ensure_mutable_access(uri, ctx)
path = self._uri_to_path(uri, ctx=ctx)
await self._ensure_parent_dirs(path, ctx=ctx)
@@ -2152,7 +2169,7 @@ class VikingFS:
ctx: Optional[RequestContext] = None,
) -> None:
"""Append content to file."""
- self._ensure_access(uri, ctx)
+ self._ensure_mutable_access(uri, ctx)
path = self._uri_to_path(uri, ctx=ctx)
try:
diff --git a/openviking/sync_client.py b/openviking/sync_client.py
index a2f0ccdd3..844acb8f0 100644
--- a/openviking/sync_client.py
+++ b/openviking/sync_client.py
@@ -23,8 +23,8 @@ class SyncOpenViking:
Wraps AsyncOpenViking with synchronous methods.
"""
- def __init__(self, path: Optional[str] = None):
- self._async_client = AsyncOpenViking(path=path)
+ def __init__(self, path: Optional[str] = None, actor_peer_id: Optional[str] = None):
+ self._async_client = AsyncOpenViking(path=path, actor_peer_id=actor_peer_id)
self._initialized = False
def initialize(self) -> None:
@@ -235,7 +235,6 @@ 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(
@@ -253,7 +252,6 @@ class SyncOpenViking:
until=until,
time_field=time_field,
level=level,
- peer_id=peer_id,
)
)
@@ -270,7 +268,6 @@ 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(
@@ -286,7 +283,6 @@ class SyncOpenViking:
until,
time_field,
level,
- peer_id=peer_id,
)
)
diff --git a/openviking_cli/client/base.py b/openviking_cli/client/base.py
index d27618655..34f421eb1 100644
--- a/openviking_cli/client/base.py
+++ b/openviking_cli/client/base.py
@@ -170,7 +170,6 @@ class BaseClient(ABC):
filter: Optional[Dict] = None,
context_type: Optional[SearchContextTypeInput] = None,
telemetry: TelemetryRequest = False,
- peer_id: Optional[str] = None,
) -> Any:
"""Semantic search without session context."""
...
@@ -186,7 +185,6 @@ class BaseClient(ABC):
filter: Optional[Dict] = None,
context_type: Optional[SearchContextTypeInput] = None,
telemetry: TelemetryRequest = False,
- peer_id: Optional[str] = None,
) -> Any:
"""Semantic search with optional session context."""
...
diff --git a/openviking_cli/client/http.py b/openviking_cli/client/http.py
index 84a9aa597..ab9fef997 100644
--- a/openviking_cli/client/http.py
+++ b/openviking_cli/client/http.py
@@ -13,6 +13,7 @@ from typing import Any, Dict, List, Optional, Union
import httpx
+from openviking.core.peer_id import normalize_peer_id
from openviking.telemetry import TelemetryRequest, normalize_telemetry_request
from openviking.utils.search_filters import SearchContextTypeInput
from openviking_cli.client.base import BaseClient
@@ -144,6 +145,7 @@ class AsyncHTTPClient(BaseClient):
user_id: Optional[str] = None,
account: Optional[str] = None,
user: Optional[str] = None,
+ actor_peer_id: Optional[str] = None,
timeout: float = 60.0,
extra_headers: Optional[Dict[str, str]] = None,
profile_enabled: Optional[bool] = None,
@@ -156,6 +158,7 @@ class AsyncHTTPClient(BaseClient):
user_id: User identifier. If not provided, defaults to "default".
account: Optional account identity header for trusted deployments.
user: Optional user identity header for trusted deployments.
+ actor_peer_id: Optional peer actor scope header.
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.
"""
@@ -166,6 +169,7 @@ class AsyncHTTPClient(BaseClient):
or api_key is None
or account is None
or effective_user is None
+ or actor_peer_id is None
or timeout == 60.0
or extra_headers is None
)
@@ -177,6 +181,8 @@ class AsyncHTTPClient(BaseClient):
api_key = api_key or cli_config.api_key
account = account or cli_config.account
effective_user = effective_user or cli_config.user
+ if actor_peer_id is None:
+ actor_peer_id = cli_config.actor_peer_id
if timeout == 60.0: # only override default with config value
timeout = cli_config.timeout
if extra_headers is None:
@@ -195,6 +201,7 @@ class AsyncHTTPClient(BaseClient):
self._api_key = api_key
self._account = account
self._user_id = effective_user
+ self._actor_peer_id = normalize_peer_id(actor_peer_id)
self._user = UserIdentifier.the_default_user()
self._timeout = timeout
self._extra_headers = extra_headers
@@ -216,6 +223,8 @@ class AsyncHTTPClient(BaseClient):
headers["X-OpenViking-Account"] = self._account
if self._user_id:
headers["X-OpenViking-User"] = self._user_id
+ if self._actor_peer_id:
+ headers["X-OpenViking-Actor-Peer"] = self._actor_peer_id
if self._extra_headers:
headers.update(self._extra_headers)
self._http = httpx.AsyncClient(
@@ -690,7 +699,6 @@ class AsyncHTTPClient(BaseClient):
filter: Optional[Dict[str, Any]] = None,
context_type: Optional[SearchContextTypeInput] = None,
telemetry: TelemetryRequest = False,
- peer_id: Optional[str] = None,
) -> FindResult:
"""Semantic search without session context."""
telemetry = self._validate_telemetry(telemetry)
@@ -705,8 +713,6 @@ class AsyncHTTPClient(BaseClient):
"context_type": context_type,
"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 {})
@@ -723,7 +729,6 @@ class AsyncHTTPClient(BaseClient):
filter: Optional[Dict[str, Any]] = None,
context_type: Optional[SearchContextTypeInput] = None,
telemetry: TelemetryRequest = False,
- peer_id: Optional[str] = None,
) -> FindResult:
"""Semantic search with optional session context."""
telemetry = self._validate_telemetry(telemetry)
@@ -740,8 +745,6 @@ class AsyncHTTPClient(BaseClient):
"context_type": context_type,
"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 {})
diff --git a/openviking_cli/client/sync_http.py b/openviking_cli/client/sync_http.py
index 5dc53da48..8bd1047a5 100644
--- a/openviking_cli/client/sync_http.py
+++ b/openviking_cli/client/sync_http.py
@@ -36,6 +36,7 @@ class SyncHTTPClient:
user_id: Optional[str] = None,
account: Optional[str] = None,
user: Optional[str] = None,
+ actor_peer_id: Optional[str] = None,
timeout: float = 60.0,
extra_headers: Optional[Dict[str, str]] = None,
profile_enabled: Optional[bool] = None,
@@ -46,6 +47,7 @@ class SyncHTTPClient:
user_id=user_id,
account=account,
user=user,
+ actor_peer_id=actor_peer_id,
timeout=timeout,
extra_headers=extra_headers,
profile_enabled=profile_enabled,
@@ -288,7 +290,6 @@ class SyncHTTPClient:
filter: Optional[Dict] = None,
context_type: Optional[SearchContextTypeInput] = None,
telemetry: TelemetryRequest = False,
- peer_id: Optional[str] = None,
):
"""Semantic search with optional session context."""
return run_async(
@@ -303,7 +304,6 @@ class SyncHTTPClient:
filter=filter,
context_type=context_type,
telemetry=telemetry,
- peer_id=peer_id,
)
)
@@ -317,7 +317,6 @@ class SyncHTTPClient:
filter: Optional[Dict] = None,
context_type: Optional[SearchContextTypeInput] = None,
telemetry: TelemetryRequest = False,
- peer_id: Optional[str] = None,
):
"""Semantic search without session context."""
return run_async(
@@ -330,7 +329,6 @@ class SyncHTTPClient:
filter,
context_type,
telemetry=telemetry,
- peer_id=peer_id,
)
)
diff --git a/openviking_cli/utils/config/ovcli_config.py b/openviking_cli/utils/config/ovcli_config.py
index 703558c3b..c33e8fcc8 100644
--- a/openviking_cli/utils/config/ovcli_config.py
+++ b/openviking_cli/utils/config/ovcli_config.py
@@ -20,7 +20,7 @@ class OVCLIUploadConfig(BaseModel):
include: Optional[str] = None
exclude: Optional[str] = None
- model_config = {"extra": "ignore"}
+ model_config = {"extra": "forbid"}
class OVCLIConfig(BaseModel):
@@ -30,20 +30,23 @@ class OVCLIConfig(BaseModel):
api_key: Optional[str] = None
account: Optional[str] = None
user: Optional[str] = None
+ actor_peer_id: Optional[str] = None
timeout: float = 60.0
profile: bool = False
upload: Optional[OVCLIUploadConfig] = None
extra_headers: Optional[Dict[str, str]] = None
- model_config = {"extra": "ignore"}
+ model_config = {"extra": "forbid"}
@model_validator(mode="before")
@classmethod
def handle_extra_headers_aliases(cls, data: Any) -> Any:
if isinstance(data, dict):
+ data = dict(data)
# 支持 extra_header 作为 extra_headers 的别名
- if "extra_header" in data and "extra_headers" not in data:
- data["extra_headers"] = data["extra_header"]
+ extra_header = data.pop("extra_header", None)
+ if extra_header is not None and "extra_headers" not in data:
+ data["extra_headers"] = extra_header
return data
diff --git a/tests/api_test/api/client.py b/tests/api_test/api/client.py
index 45b5a7efb..e0525feba 100644
--- a/tests/api_test/api/client.py
+++ b/tests/api_test/api/client.py
@@ -175,15 +175,12 @@ class OpenVikingAPIClient:
score_threshold: Optional[float] = None,
filter: Optional[Dict[str, Any]] = None,
context_type: Optional[str | list[str]] = 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_id
if score_threshold is not None:
payload["score_threshold"] = score_threshold
if filter:
@@ -201,7 +198,6 @@ class OpenVikingAPIClient:
score_threshold: Optional[float] = None,
filter: Optional[Dict[str, Any]] = None,
context_type: Optional[str | list[str]] = None,
- peer_id: Optional[str] = None,
) -> requests.Response:
endpoint = "/api/v1/search/search"
url = self._build_url(self.server_url, endpoint)
@@ -210,8 +206,6 @@ class OpenVikingAPIClient:
payload["target_uri"] = target_uri
if session_id:
payload["session_id"] = session_id
- if peer_id is not None:
- payload["peer_id"] = peer_id
if score_threshold is not None:
payload["score_threshold"] = score_threshold
if filter:
diff --git a/tests/client/test_http_client_config.py b/tests/client/test_http_client_config.py
index 7f7c2fe6a..617776c8a 100644
--- a/tests/client/test_http_client_config.py
+++ b/tests/client/test_http_client_config.py
@@ -40,6 +40,7 @@ def test_async_http_client_loads_missing_fields_from_ovcli_config(tmp_path, monk
"api_key": "config-key",
"account": "config-account",
"user": "config-user",
+ "actor_peer_id": "config-actor",
"timeout": 12.5,
"profile": True,
}
@@ -53,6 +54,7 @@ def test_async_http_client_loads_missing_fields_from_ovcli_config(tmp_path, monk
assert client._api_key == "config-key"
assert client._account == "config-account"
assert client._user_id == "config-user"
+ assert client._actor_peer_id == "config-actor"
assert client._timeout == 12.5
assert client._profile_enabled is True
@@ -132,6 +134,7 @@ async def test_async_http_client_sends_configured_identity_headers(tmp_path, mon
api_key="explicit-key",
account="explicit-account",
user_id="explicit-user",
+ actor_peer_id="explicit-actor",
timeout=33.0,
extra_headers={},
)
@@ -142,6 +145,7 @@ async def test_async_http_client_sends_configured_identity_headers(tmp_path, mon
"X-API-Key": "explicit-key",
"X-OpenViking-Account": "explicit-account",
"X-OpenViking-User": "explicit-user",
+ "X-OpenViking-Actor-Peer": "explicit-actor",
}
@@ -300,7 +304,7 @@ def test_async_http_client_prefers_extra_headers_over_alias(tmp_path, monkeypatc
@pytest.mark.asyncio
-async def test_async_http_client_find_sends_peer_id(tmp_path, monkeypatch):
+async def test_async_http_client_find_does_not_send_peer_id(tmp_path, monkeypatch):
config_path = tmp_path / "ovcli.conf"
config_path.write_text("{}")
monkeypatch.setenv(OPENVIKING_CLI_CONFIG_ENV, str(config_path))
@@ -312,7 +316,6 @@ async def test_async_http_client_find_sends_peer_id(tmp_path, monkeypatch):
await client.find(
"invoice",
target_uri="viking://user/memories",
- peer_id="web-visitor-alice",
)
assert http.calls == [
@@ -326,14 +329,13 @@ async def test_async_http_client_find_sends_peer_id(tmp_path, monkeypatch):
"filter": None,
"context_type": None,
"telemetry": False,
- "peer_id": "web-visitor-alice",
},
)
]
@pytest.mark.asyncio
-async def test_async_http_client_search_sends_peer_id(tmp_path, monkeypatch):
+async def test_async_http_client_search_does_not_send_peer_id(tmp_path, monkeypatch):
config_path = tmp_path / "ovcli.conf"
config_path.write_text("{}")
monkeypatch.setenv(OPENVIKING_CLI_CONFIG_ENV, str(config_path))
@@ -346,7 +348,6 @@ async def test_async_http_client_search_sends_peer_id(tmp_path, monkeypatch):
"invoice",
target_uri="viking://user/memories",
session_id="session-1",
- peer_id="web-visitor-alice",
)
assert http.calls == [
@@ -361,7 +362,6 @@ async def test_async_http_client_search_sends_peer_id(tmp_path, monkeypatch):
"filter": None,
"context_type": None,
"telemetry": False,
- "peer_id": "web-visitor-alice",
},
)
]
diff --git a/tests/integration/test_group_chat.py b/tests/integration/test_group_chat.py
index cd7a8dd69..b6e9d9a4d 100644
--- a/tests/integration/test_group_chat.py
+++ b/tests/integration/test_group_chat.py
@@ -178,7 +178,8 @@ def verify_isolation(url: str, api_key: str, account: str):
)
sc.initialize()
- results = sc.find(query, limit=5, peer_id=search_agent)
+ target_uri = f"viking://user/{search_user}/peers/{search_agent}/memories"
+ results = sc.find(query, target_uri=target_uri, limit=5)
found = False
if hasattr(results, "memories") and results.memories:
for m in results.memories:
@@ -333,7 +334,7 @@ def main():
Panel(
f"[bold green]测试完成![/bold green]\n\n"
f"Trace IDs:\n{trace_info}\n\n"
- "预期:当前登录 user 命中自己的记忆;peer 记忆由 peer_id 路由。",
+ "预期:当前登录 user 命中自己的记忆;peer 记忆由显式 peer memory URI 路由。",
style="green",
width=PANEL_WIDTH,
)
diff --git a/tests/server/test_actor_peer_retrieval_targets.py b/tests/server/test_actor_peer_retrieval_targets.py
new file mode 100644
index 000000000..5d5a18e86
--- /dev/null
+++ b/tests/server/test_actor_peer_retrieval_targets.py
@@ -0,0 +1,148 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+"""Actor peer retrieval target resolution 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 PermissionDeniedError
+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 _ctx(actor_peer_id: str | None = None) -> RequestContext:
+ return RequestContext(
+ user=UserIdentifier("acct", "support_bot"),
+ role=Role.USER,
+ actor_peer_id=actor_peer_id,
+ )
+
+
+def _target_dirs(target_uri="", actor_peer_id: str | None = None):
+ return resolve_retrieval_targets(target_uri, _ctx(actor_peer_id)).target_directories
+
+
+def test_owner_default_search_targets_owner_memory_resources_and_skills():
+ targets = _target_dirs()
+
+ assert targets == [
+ "viking://user/support_bot",
+ "viking://resources",
+ ]
+
+
+def test_actor_default_search_keeps_user_view_and_filters_peer_collection():
+ targets = _target_dirs(actor_peer_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",
+ ]
+
+
+def test_actor_search_keeps_explicit_resource_target():
+ targets = _target_dirs("viking://resources/docs", actor_peer_id="web-visitor-alice")
+
+ assert targets == ["viking://resources/docs"]
+
+
+def test_actor_search_user_root_keeps_user_content_and_filters_peer_collection():
+ targets = _target_dirs("viking://user", actor_peer_id="web-visitor-alice")
+
+ assert targets == [
+ "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",
+ ]
+
+
+def test_actor_default_memory_targets_actor_peer_memory():
+ assert default_target_directories(
+ _ctx("web-visitor-alice"), context_type=ContextType.MEMORY
+ ) == [
+ "viking://user/support_bot/memories",
+ "viking://user/support_bot/peers/web-visitor-alice/memories",
+ ]
+
+
+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
+ ) == [
+ "viking://resources",
+ "viking://user/support_bot/resources",
+ "viking://user/support_bot/peers/web-visitor-alice/resources",
+ ]
+
+
+def test_explicit_user_memory_target_stays_self_memory_only():
+ targets = _target_dirs("viking://user/memories")
+
+ assert targets == ["viking://user/support_bot/memories"]
+
+
+def test_owner_explicit_peer_root_targets_that_peer_content():
+ targets = _target_dirs("viking://user/support_bot/peers/web-visitor-alice")
+
+ assert targets == [
+ "viking://user/support_bot/peers/web-visitor-alice/memories",
+ "viking://user/support_bot/peers/web-visitor-alice/resources",
+ ]
+
+
+def test_owner_explicit_peer_memory_target_allows_any_peer():
+ targets = _target_dirs("viking://user/support_bot/peers/web-visitor-bob/memories")
+
+ assert targets == ["viking://user/support_bot/peers/web-visitor-bob/memories"]
+
+
+def test_actor_explicit_own_peer_memory_target_is_allowed():
+ targets = _target_dirs(
+ "viking://user/support_bot/peers/web-visitor-alice/memories",
+ actor_peer_id="web-visitor-alice",
+ )
+
+ assert targets == ["viking://user/support_bot/peers/web-visitor-alice/memories"]
+
+
+def test_actor_explicit_other_peer_memory_target_is_denied():
+ with pytest.raises(PermissionDeniedError, match="another peer"):
+ _target_dirs(
+ "viking://user/support_bot/peers/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",
+ ]
+
+
+def test_actor_peer_collection_targets_actor_peer_only():
+ assert _target_dirs(
+ "viking://user/support_bot/peers",
+ actor_peer_id="web-visitor-alice",
+ ) == [
+ "viking://user/support_bot/peers/web-visitor-alice/memories",
+ "viking://user/support_bot/peers/web-visitor-alice/resources",
+ ]
diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.py
index 965baa8c9..62e5c4e42 100644
--- a/tests/server/test_admin_api.py
+++ b/tests/server/test_admin_api.py
@@ -16,6 +16,7 @@ from openviking.server.api_keys import APIKeyManager
from openviking.server.app import create_app
from openviking.server.config import ServerConfig
from openviking.server.dependencies import set_service
+from openviking.server.identity import RequestContext, Role
from openviking.server.models import ERROR_CODE_TO_HTTP_STATUS, ErrorInfo, Response
from openviking.service.core import OpenVikingService
from openviking_cli.exceptions import OpenVikingError
@@ -153,7 +154,7 @@ def trusted_headers(
# ---- Account CRUD ----
-async def test_create_account(admin_client: httpx.AsyncClient):
+async def test_create_account(admin_client: httpx.AsyncClient, admin_service: OpenVikingService):
"""ROOT can create an account with first admin."""
acct = _uid()
resp = await admin_client.post(
@@ -167,6 +168,10 @@ async def test_create_account(admin_client: httpx.AsyncClient):
assert body["result"]["admin_user_id"] == "alice"
assert "user_key" in body["result"]
+ ctx = RequestContext(user=UserIdentifier(acct, "alice"), role=Role.ADMIN)
+ assert await admin_service.viking_fs.abstract("viking://resources", ctx=ctx)
+ assert await admin_service.viking_fs.abstract("viking://user", ctx=ctx)
+
async def test_list_accounts(admin_client: httpx.AsyncClient):
"""ROOT can list all accounts."""
diff --git a/tests/server/test_api_search.py b/tests/server/test_api_search.py
index 0af324cf7..33508c465 100644
--- a/tests/server/test_api_search.py
+++ b/tests/server/test_api_search.py
@@ -46,6 +46,19 @@ async def test_find_basic(client_with_resource):
assert "telemetry" not in body
[email protected]("endpoint", ["/api/v1/search/find", "/api/v1/search/search"])
+async def test_search_endpoints_reject_unknown_request_fields(
+ client: httpx.AsyncClient,
+ endpoint: str,
+):
+ resp = await client.post(
+ endpoint,
+ json={"query": "sample document", "unexpected": "value"},
+ )
+
+ assert resp.status_code == 400
+
+
async def test_find_with_target_uri(client_with_resource):
client, uri = client_with_resource
resp = await client.post(
diff --git a/tests/server/test_auth.py b/tests/server/test_auth.py
index 1776e3c5d..9ffbf2b08 100644
--- a/tests/server/test_auth.py
+++ b/tests/server/test_auth.py
@@ -725,6 +725,32 @@ async def test_admin_reindex_requests_use_key_owner_in_api_key_mode():
assert ctx.user.user_id == "admin"
+async def test_actor_peer_header_sets_request_context_scope():
+ request = _make_request("/api/v1/search/find", auth_enabled=True)
+ identity = ResolvedIdentity(role=Role.USER, account_id="acme", user_id="alice")
+
+ ctx = await get_request_context(request, identity, "web-visitor-alice")
+
+ assert ctx.actor_peer_id == "web-visitor-alice"
+
+
+async def test_empty_actor_peer_header_is_unset():
+ request = _make_request("/api/v1/search/find", auth_enabled=True)
+ identity = ResolvedIdentity(role=Role.USER, account_id="acme", user_id="alice")
+
+ ctx = await get_request_context(request, identity, " ")
+
+ assert ctx.actor_peer_id is None
+
+
+async def test_actor_peer_header_rejects_path_separators():
+ request = _make_request("/api/v1/search/find", auth_enabled=True)
+ identity = ResolvedIdentity(role=Role.USER, account_id="acme", user_id="alice")
+
+ with pytest.raises(InvalidArgumentError, match="path separators"):
+ await get_request_context(request, identity, "bad/peer")
+
+
async def test_root_monitoring_requests_allow_implicit_default_identity():
"""Observer/debug endpoints keep the existing ROOT monitoring flow."""
observer_request = _make_request("/api/v1/observer/system", auth_enabled=True)
diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.py
index 887fdb100..34d483475 100644
--- a/tests/server/test_mcp_endpoint.py
+++ b/tests/server/test_mcp_endpoint.py
@@ -10,14 +10,18 @@ and service dependency, avoiding MCP protocol complexity.
from types import SimpleNamespace
from unittest.mock import AsyncMock
+import httpx
import pytest
+from fastapi import FastAPI
+from starlette.routing import Route
import openviking.server.mcp_endpoint as mcp_endpoint
from openviking.server.dependencies import set_service
-from openviking.server.identity import RequestContext, Role
+from openviking.server.identity import AuthMode, RequestContext, Role
from openviking.server.mcp_endpoint import (
StoreMessage,
_get_ctx,
+ _IdentityASGIMiddleware,
_mcp_ctx,
add_resource,
cancel_watch,
@@ -183,6 +187,55 @@ async def test_search_tool_calls_context_aware_search_with_session(service, monk
assert captured["score_threshold"] == 0.1
+async def test_mcp_middleware_sets_actor_peer_context():
+ async def downstream(scope, receive, send):
+ ctx = _get_ctx()
+ assert ctx.actor_peer_id == "peer-a"
+ response = httpx.Response(200, json={"ok": True})
+ await send(
+ {
+ "type": "http.response.start",
+ "status": response.status_code,
+ "headers": [(b"content-type", b"application/json")],
+ }
+ )
+ await send({"type": "http.response.body", "body": response.content})
+
+ app = FastAPI()
+ app.state.config = SimpleNamespace(get_effective_auth_mode=lambda: AuthMode.DEV)
+ app.routes.append(Route("/mcp", endpoint=_IdentityASGIMiddleware(downstream), methods=["POST"]))
+
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://ov.test") as client:
+ response = await client.post(
+ "/mcp",
+ json={"jsonrpc": "2.0", "id": 1, "method": "ping"},
+ headers={"X-OpenViking-Actor-Peer": "peer-a"},
+ )
+
+ assert response.status_code == 200
+
+
+async def test_mcp_middleware_rejects_invalid_actor_peer_header():
+ async def downstream(scope, receive, send):
+ raise AssertionError("invalid actor peer header should not reach downstream app")
+
+ app = FastAPI()
+ app.state.config = SimpleNamespace(get_effective_auth_mode=lambda: AuthMode.DEV)
+ app.routes.append(Route("/mcp", endpoint=_IdentityASGIMiddleware(downstream), methods=["POST"]))
+
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://ov.test") as client:
+ response = await client.post(
+ "/mcp",
+ json={"jsonrpc": "2.0", "id": 1, "method": "ping"},
+ headers={"X-OpenViking-Actor-Peer": "bad/peer"},
+ )
+
+ assert response.status_code == 400
+ assert "path separators" in response.text
+
+
# ---------------------------------------------------------------------------
# read tool
# ---------------------------------------------------------------------------
diff --git a/tests/server/test_peer_id_compat.py b/tests/server/test_peer_id_compat.py
deleted file mode 100644
index b667f74a5..000000000
--- a/tests/server/test_peer_id_compat.py
+++ /dev/null
@@ -1,147 +0,0 @@
-# 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 test_normalize_peer_id_rejects_invalid_character():
- with pytest.raises(ValueError, match="Invalid peer_id"):
- normalize_peer_id("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_content_without_all_peer_content():
- targets = _target_dirs()
-
- assert targets == [
- "viking://user/support_bot/memories",
- "viking://resources",
- "viking://user/support_bot/resources",
- "viking://user/support_bot/skills",
- ]
-
-
-def test_default_peer_search_targets_self_and_requested_peer_content():
- 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/resources",
- "viking://user/support_bot/peers/web-visitor-alice/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_content():
- targets = _target_dirs("viking://user/support_bot/peers/web-visitor-alice")
-
- assert targets == [
- "viking://user/support_bot/peers/web-visitor-alice/memories",
- "viking://user/support_bot/peers/web-visitor-alice/resources",
- ]
-
-
-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_explicit_peer_target_rejects_invalid_peer_id():
- with pytest.raises(InvalidArgumentError, match="Invalid peer_id"):
- _target_dirs("viking://user/support_bot/peers/web+visitor+alice/memories")
-
-
-def test_peer_search_rejects_all_peers_target():
- with pytest.raises(InvalidArgumentError, match="all peer contexts"):
- _target_dirs("viking://user/support_bot/peers")
-
-
-def test_peer_search_user_root_targets_user_content_and_requested_peer_content():
- 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/resources",
- "viking://user/support_bot/peers/web-visitor-alice/resources",
- "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/session/test_memory_extraction_scope.py b/tests/session/test_memory_extraction_scope.py
new file mode 100644
index 000000000..083b9d837
--- /dev/null
+++ b/tests/session/test_memory_extraction_scope.py
@@ -0,0 +1,53 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+"""Session commit memory extraction scope tests."""
+
+from openviking.message import Message, TextPart
+from openviking.server.identity import RequestContext, Role
+from openviking.session.memory_policy import MemoryPolicy
+from openviking.session.session import _resolve_memory_extraction_scope
+from openviking_cli.session.user_id import UserIdentifier
+
+
+def _ctx(actor_peer_id: str | None = None) -> RequestContext:
+ return RequestContext(
+ user=UserIdentifier("acct", "support_bot"),
+ role=Role.USER,
+ actor_peer_id=actor_peer_id,
+ )
+
+
+def _message(peer_id: str | None = None) -> Message:
+ return Message(
+ id=f"msg-{peer_id or 'self'}",
+ role="user",
+ parts=[TextPart("remember this")],
+ peer_id=peer_id,
+ )
+
+
+def test_owner_memory_extraction_scope_uses_message_peer_ids():
+ scope = _resolve_memory_extraction_scope(
+ _ctx(),
+ MemoryPolicy(peer_enabled=True),
+ [_message("alice"), _message("bob"), _message()],
+ config_session_skill_extraction_enabled=True,
+ )
+
+ assert scope.allow_self_memory is True
+ assert scope.allowed_peer_ids == {"alice", "bob"}
+ assert scope.include_session_skills is True
+
+
+def test_actor_memory_extraction_scope_still_uses_policy_and_messages():
+ scope = _resolve_memory_extraction_scope(
+ _ctx("alice"),
+ MemoryPolicy(peer_enabled=True),
+ [_message("bob"), _message()],
+ config_session_skill_extraction_enabled=True,
+ )
+
+ assert scope.allow_self_memory is True
+ assert scope.allowed_peer_ids == {"bob"}
+ assert scope.include_session_skills is True
diff --git a/tests/storage/test_viking_fs_actor_peer_view.py b/tests/storage/test_viking_fs_actor_peer_view.py
new file mode 100644
index 000000000..9f98e5f4a
--- /dev/null
+++ b/tests/storage/test_viking_fs_actor_peer_view.py
@@ -0,0 +1,224 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+import pytest
+
+from openviking.server.identity import RequestContext, Role
+from openviking.storage.viking_fs import VikingFS
+from openviking_cli.exceptions import PermissionDeniedError
+from openviking_cli.session.user_id import UserIdentifier
+
+_MOD_TIME = "2026-01-01T00:00:00Z"
+
+
+class _MemoryAGFS:
+ def __init__(self):
+ self.files = {
+ "/local/acct/user/support_bot/peers/customer-wang-yue/memories/profile.md": b"wang",
+ "/local/acct/user/support_bot/peers/customer-zhang-xiaoxiao/memories/profile.md": (
+ b"zhang"
+ ),
+ "/local/acct/user/support_bot/resources/guide.md": b"guide",
+ }
+ self.dirs = set()
+ for path in self.files:
+ parts = path.strip("/").split("/")[:-1]
+ current = ""
+ for part in parts:
+ current += f"/{part}"
+ self.dirs.add(current)
+ self.writes = []
+ self.removed = []
+
+ def ls(self, path, ctx=None):
+ if path not in self.dirs:
+ raise FileNotFoundError(path)
+ prefix = path.rstrip("/") + "/"
+ names = set()
+ for candidate in [*self.dirs, *self.files]:
+ if not candidate.startswith(prefix):
+ continue
+ rest = candidate[len(prefix) :]
+ if rest and "/" not in rest:
+ names.add(rest)
+ return [self._entry(f"{prefix}{name}") for name in sorted(names)]
+
+ def tree_directory(
+ self,
+ path,
+ show_hidden=False,
+ node_limit=None,
+ level_limit=None,
+ ctx=None,
+ ):
+ if path not in self.dirs:
+ raise FileNotFoundError(path)
+ prefix = path.rstrip("/") + "/"
+ entries = []
+ for candidate in sorted([*self.dirs, *self.files]):
+ if not candidate.startswith(prefix):
+ continue
+ rel_path = candidate[len(prefix) :]
+ if not rel_path:
+ continue
+ if level_limit is not None and len(rel_path.split("/")) > level_limit:
+ continue
+ entry = {
+ "path": candidate,
+ "rel_path": rel_path,
+ "info": self._entry(candidate),
+ "extra": {},
+ }
+ entries.append(entry)
+ if node_limit is not None and len(entries) >= node_limit:
+ break
+ return entries
+
+ def stat(self, path, ctx=None):
+ if path in self.dirs:
+ return self._entry(path)
+ if path in self.files:
+ return self._entry(path)
+ raise FileNotFoundError(path)
+
+ def read(self, path, *args, ctx=None):
+ if path not in self.files:
+ raise FileNotFoundError(path)
+ return self.files[path]
+
+ def write(self, path, data, ctx=None):
+ self.files[path] = data if isinstance(data, bytes) else data.encode("utf-8")
+ self.writes.append(path)
+
+ def rm(self, path, recursive=False, ctx=None):
+ self.removed.append(path)
+ self.files.pop(path, None)
+ return {}
+
+ def grep(self, **kwargs):
+ return {
+ "matches": [
+ {
+ "file": "peers/customer-wang-yue/memories/profile.md",
+ "line": 1,
+ "content": "wang",
+ },
+ {
+ "file": "peers/customer-zhang-xiaoxiao/memories/profile.md",
+ "line": 1,
+ "content": "zhang",
+ },
+ ],
+ "files_scanned": 2,
+ }
+
+ def _entry(self, path):
+ is_dir = path in self.dirs
+ return {
+ "name": path.rstrip("/").rsplit("/", 1)[-1],
+ "size": 0 if is_dir else len(self.files[path]),
+ "mode": 0o755,
+ "modTime": _MOD_TIME,
+ "isDir": is_dir,
+ }
+
+
+class _CountingVectorStore:
+ def __init__(self):
+ self.calls = []
+
+ async def count(self, filter=None, ctx=None):
+ self.calls.append((filter, ctx))
+ return 7
+
+
+def fs():
+ return VikingFS(agfs=_MemoryAGFS())
+
+
+def actor_ctx():
+ return RequestContext(
+ user=UserIdentifier("acct", "support_bot"),
+ role=Role.USER,
+ actor_peer_id="customer-wang-yue",
+ )
+
+
+def _other_peer_uri(suffix="memories/profile.md"):
+ return f"viking://user/support_bot/peers/customer-zhang-xiaoxiao/{suffix}"
+
+
+def _actor_peer_uri(suffix="memories/profile.md"):
+ return f"viking://user/support_bot/peers/customer-wang-yue/{suffix}"
+
+
+async def test_actor_peer_view_filters_ls_peer_collection(fs, actor_ctx):
+ entries = await fs.ls("viking://user/support_bot/peers", ctx=actor_ctx)
+
+ assert [entry["uri"] for entry in entries] == [
+ "viking://user/support_bot/peers/customer-wang-yue"
+ ]
+
+
+async def test_actor_peer_view_filters_tree_from_user_root(fs, actor_ctx):
+ entries = await fs.tree(
+ "viking://user/support_bot",
+ ctx=actor_ctx,
+ level_limit=None,
+ )
+ uris = {entry["uri"] for entry in entries}
+
+ assert _actor_peer_uri() in uris
+ assert _other_peer_uri() not in uris
+ assert "viking://user/support_bot/resources/guide.md" in uris
+
+
+async def test_actor_peer_view_blocks_read_stat_and_write_to_other_peer(fs, actor_ctx):
+ with pytest.raises(PermissionDeniedError):
+ await fs.stat(_other_peer_uri(), ctx=actor_ctx)
+ with pytest.raises(PermissionDeniedError):
+ await fs.read_file(_other_peer_uri(), ctx=actor_ctx)
+ with pytest.raises(PermissionDeniedError):
+ await fs.write_file(_other_peer_uri(), "blocked", ctx=actor_ctx)
+
+ await fs.write_file("viking://user/support_bot/resources/new.md", "allowed", ctx=actor_ctx)
+ assert "/local/acct/user/support_bot/resources/new.md" in fs._async_agfs.sync_client.writes
+
+
+async def test_actor_peer_view_stat_does_not_count_hidden_peer_roots(actor_ctx):
+ vector_store = _CountingVectorStore()
+ fs = VikingFS(agfs=_MemoryAGFS(), vector_store=vector_store)
+
+ user_root = await fs.stat("viking://user/support_bot", ctx=actor_ctx)
+ peer_collection = await fs.stat("viking://user/support_bot/peers", ctx=actor_ctx)
+ user_resources = await fs.stat("viking://user/support_bot/resources", ctx=actor_ctx)
+
+ assert "count" not in user_root
+ assert "count" not in peer_collection
+ assert user_resources["count"] == 7
+
+
+async def test_actor_peer_view_blocks_mutating_other_peer_and_peer_collection(fs, actor_ctx):
+ with pytest.raises(PermissionDeniedError):
+ await fs.rm(_other_peer_uri(), ctx=actor_ctx)
+ with pytest.raises(PermissionDeniedError):
+ await fs.mv(_actor_peer_uri(), _other_peer_uri(), ctx=actor_ctx)
+ with pytest.raises(PermissionDeniedError):
+ await fs.rm("viking://user/support_bot/peers", recursive=True, ctx=actor_ctx)
+ with pytest.raises(PermissionDeniedError):
+ await fs.rm("viking://user/support_bot", recursive=True, ctx=actor_ctx)
+
+
+async def test_actor_peer_view_filters_grep_matches(fs, actor_ctx):
+ result = await fs.grep("viking://user/support_bot", pattern="profile", ctx=actor_ctx)
+
+ assert [match["uri"] for match in result["matches"]] == [_actor_peer_uri()]
+ assert result["files_scanned"] == 1
diff --git a/tests/unit/test_langchain_integration.py b/tests/unit/test_langchain_integration.py
index f161695b1..bb4d2aab6 100644
--- a/tests/unit/test_langchain_integration.py
+++ b/tests/unit/test_langchain_integration.py
@@ -83,19 +83,19 @@ def test_retriever_returns_langchain_documents():
assert all(doc.page_content for doc in docs)
-def test_retriever_passes_peer_id_to_retrieval():
+def test_retriever_keeps_peer_id_out_of_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",
+ actor_peer_id="peer-1",
)
retriever.invoke("azure")
- assert client.find_calls[-1]["peer_id"] == "peer-1"
+ assert "peer_id" not in client.find_calls[-1]
def test_create_openviking_tools_exposes_common_viking_primitives():
@@ -152,7 +152,7 @@ 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():
+def test_create_openviking_tools_uses_peer_id_only_for_message_attribution():
client = InMemoryOpenVikingClient(
{"viking://user/memories/profile.md": "The peer likes LangGraph agents."}
)
@@ -171,8 +171,8 @@ def test_create_openviking_tools_passes_peer_id_without_exposing_tool_arg():
}
)
- assert client.find_calls[-1]["peer_id"] == "peer-tools"
- assert client.search_calls[-1]["peer_id"] == "peer-tools"
+ assert "peer_id" not in client.find_calls[-1]
+ assert "peer_id" not in client.search_calls[-1]
assert any(
messages and messages[0].get("peer_id") == "peer-tools"
for messages in client.sessions.values()
@@ -432,8 +432,9 @@ def test_ensure_client_keeps_local_path_clients_direct(monkeypatch, tmp_path):
created = {}
class FakeLocalClient:
- def __init__(self, path):
+ def __init__(self, path, actor_peer_id=None):
created["path"] = path
+ created["actor_peer_id"] = actor_peer_id
self._initialized = False
def initialize(self):
@@ -448,6 +449,7 @@ def test_ensure_client_keeps_local_path_clients_direct(monkeypatch, tmp_path):
assert isinstance(client, FakeLocalClient)
assert client._initialized is True
assert created["path"] == str(tmp_path)
+ assert created["actor_peer_id"] is None
def test_openviking_client_retries_recoverable_read_with_fresh_client(monkeypatch):
@@ -741,19 +743,19 @@ 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():
+def test_session_context_assembler_keeps_peer_id_out_of_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",
+ actor_peer_id="peer-assembler",
)
assembler.assemble(session_id="assembler-peer-session", query="azure")
- assert client.search_calls[-1]["peer_id"] == "peer-assembler"
+ assert "peer_id" not in client.search_calls[-1]
def test_with_openviking_context_wraps_runnable_with_history():
@@ -856,7 +858,7 @@ def test_with_openviking_context_dynamic_peer_uses_config_for_recall_and_history
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 "peer_id" not in client.search_calls[-1]
assert [message.get("peer_id") for message in client.sessions["thread-peer-session"]] == [
"peer-dynamic",
"peer-dynamic",
@@ -1082,14 +1084,14 @@ 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():
+def test_langgraph_store_semantic_search_keeps_peer_id_out_of_retrieval():
client = InMemoryOpenVikingClient()
- store = OpenVikingStore(client=client, peer_id="peer-store")
+ store = OpenVikingStore(client=client, actor_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"
+ assert "peer_id" not in client.find_calls[-1]
def test_langgraph_store_rejects_ttl_writes():
@@ -1298,7 +1300,7 @@ 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():
+def test_langgraph_middleware_uses_peer_id_only_for_message_capture():
client = InMemoryOpenVikingClient(
{"viking://user/memories/profile.md": "The middleware peer prefers azure."}
)
@@ -1332,7 +1334,7 @@ def test_langgraph_middleware_passes_peer_id_to_recall_and_capture():
runtime=None,
)
- assert client.search_calls[-1]["peer_id"] == "peer-middleware"
+ assert "peer_id" not in client.search_calls[-1]
assert [message.get("peer_id") for message in client.sessions["middleware-peer-session"]] == [
"peer-middleware",
"peer-middleware",