Skip to content

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

feat(migration): add legacy user-peer migration (#2610)

Qin Haojie058cd1f5eae8
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index 7dab0c128..016de454b 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -13,6 +13,7 @@ use crate::error::{Error, Result};
#[derive(Clone)]
pub struct HttpClient {
base: BaseClient,
+ legacy_agent_id: Option<String>,
}
impl HttpClient {
@@ -22,6 +23,7 @@ impl HttpClient {
account: Option<String>,
user: Option<String>,
actor_peer_id: Option<String>,
+ legacy_agent_id: Option<String>,
timeout_secs: f64,
profile_enabled: bool,
extra_headers: Option<std::collections::HashMap<String, String>>,
@@ -37,6 +39,7 @@ impl HttpClient {
profile_enabled,
extra_headers,
),
+ legacy_agent_id,
}
}
@@ -48,6 +51,10 @@ impl HttpClient {
self.base.actor_peer_id()
}
+ pub fn legacy_agent_id(&self) -> Option<&str> {
+ self.legacy_agent_id.as_deref()
+ }
+
pub fn api_key(&self) -> Option<&str> {
self.base.api_key()
}
@@ -394,7 +401,7 @@ impl HttpClient {
level: Option<Vec<i32>>,
context_type: Option<Vec<String>>,
) -> Result<serde_json::Value> {
- let body = serde_json::json!({
+ let mut body = serde_json::json!({
"query": query,
"target_uri": uri,
"limit": node_limit,
@@ -405,6 +412,7 @@ impl HttpClient {
"level": level,
"context_type": context_type,
});
+ self.attach_legacy_agent_scope(&mut body);
self.post("/api/v1/search/find", &body).await
}
@@ -421,7 +429,7 @@ impl HttpClient {
level: Option<Vec<i32>>,
context_type: Option<Vec<String>>,
) -> Result<serde_json::Value> {
- let body = serde_json::json!({
+ let mut body = serde_json::json!({
"query": query,
"target_uri": uri,
"session_id": session_id,
@@ -433,9 +441,16 @@ impl HttpClient {
"level": level,
"context_type": context_type,
});
+ self.attach_legacy_agent_scope(&mut body);
self.post("/api/v1/search/search", &body).await
}
+ fn attach_legacy_agent_scope(&self, body: &mut Value) {
+ if let Some(agent_id) = self.legacy_agent_id() {
+ body["agent_id"] = serde_json::json!(agent_id);
+ }
+ }
+
pub async fn grep(
&self,
uri: &str,
@@ -1178,6 +1193,15 @@ impl HttpClient {
self.post(&path, &serde_json::json!({})).await
}
+ pub async fn admin_migrate(&self, cleanup: bool) -> Result<Value> {
+ let action = if cleanup { "cleanup" } else { "migrate" };
+ self.post(
+ "/api/v1/admin/migrate",
+ &serde_json::json!({ "action": action }),
+ )
+ .await
+ }
+
// ============ Debug Vector Methods ============
/// Get paginated vector records
@@ -1465,7 +1489,7 @@ mod tests {
#[tokio::test]
async fn ls_does_not_send_display_time_query() {
let (base_url, request_rx) = spawn_request_capture_server().await;
- let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None);
+ let client = HttpClient::new(base_url, None, None, None, None, None, 5.0, false, None);
client
.ls("viking://resources", false, false, "agent", 256, false, 1)
@@ -1481,7 +1505,7 @@ mod tests {
#[tokio::test]
async fn tree_does_not_send_display_time_query() {
let (base_url, request_rx) = spawn_request_capture_server().await;
- let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None);
+ let client = HttpClient::new(base_url, None, None, None, None, None, 5.0, false, None);
client
.tree("viking://resources", "agent", 256, false, 1, 3)
@@ -1494,6 +1518,26 @@ mod tests {
assert!(!request.contains("include_mod_time_iso="));
}
+ #[test]
+ fn search_body_includes_legacy_agent_id() {
+ let client = HttpClient::new(
+ "http://localhost:1933",
+ None,
+ None,
+ None,
+ Some("legacy-agent".to_string()),
+ Some("legacy-agent".to_string()),
+ 5.0,
+ false,
+ None,
+ );
+ let mut body = json!({"query": "invoice"});
+
+ client.attach_legacy_agent_scope(&mut body);
+
+ assert_eq!(body["agent_id"], json!("legacy-agent"));
+ }
+
#[test]
fn standard_error_envelope_formats_api_error() {
let body = json!({
diff --git a/crates/ov_cli/src/commands/admin.rs b/crates/ov_cli/src/commands/admin.rs
index 049024b0b..4dc8091e2 100644
--- a/crates/ov_cli/src/commands/admin.rs
+++ b/crates/ov_cli/src/commands/admin.rs
@@ -49,6 +49,17 @@ pub async fn delete_account(
Ok(())
}
+pub async fn migrate(
+ client: &HttpClient,
+ cleanup: bool,
+ output_format: OutputFormat,
+ compact: bool,
+) -> Result<()> {
+ let response = client.admin_migrate(cleanup).await?;
+ output_success(&response, output_format, compact);
+ Ok(())
+}
+
pub async fn register_user(
client: &HttpClient,
account_id: &str,
diff --git a/crates/ov_cli/src/commands/session.rs b/crates/ov_cli/src/commands/session.rs
index 90e27d6f4..6746d6765 100644
--- a/crates/ov_cli/src/commands/session.rs
+++ b/crates/ov_cli/src/commands/session.rs
@@ -288,6 +288,19 @@ fn parse_messages(input: &str) -> Result<Vec<(String, String)>> {
Ok(vec![("user".to_string(), input.to_string())])
}
+fn message_body(client: &HttpClient, role: &str, content: &str) -> serde_json::Value {
+ let mut body = json!({
+ "role": role,
+ "content": content
+ });
+ if role == "assistant" {
+ if let Some(agent_id) = client.legacy_agent_id() {
+ body["agent_id"] = json!(agent_id);
+ }
+ }
+ body
+}
+
pub async fn add_message(
client: &HttpClient,
session_id: &str,
@@ -303,7 +316,16 @@ pub async fn add_message(
"content": content
});
if let Some(peer_id) = peer_id {
+ if client.legacy_agent_id().is_some() {
+ return Err(Error::Client(
+ "peer_id cannot be used when client is configured with legacy agent_id".to_string(),
+ ));
+ }
body["peer_id"] = json!(peer_id);
+ } else if role == "assistant" {
+ if let Some(agent_id) = client.legacy_agent_id() {
+ body["agent_id"] = json!(agent_id);
+ }
}
let response: serde_json::Value = client.post(&path, &body).await?;
@@ -322,7 +344,7 @@ pub async fn add_messages(
let path = format!("/api/v1/sessions/{}/messages/batch", url_encode(session_id));
let messages_json: Vec<serde_json::Value> = messages
.iter()
- .map(|(role, content)| json!({"role": role, "content": content}))
+ .map(|(role, content)| message_body(client, role, content))
.collect();
let body = json!({"messages": messages_json});
let response: serde_json::Value = client.post(&path, &body).await?;
@@ -367,7 +389,7 @@ pub async fn add_memory(
let path = format!("/api/v1/sessions/{}/messages/batch", url_encode(session_id));
let messages_json: Vec<serde_json::Value> = messages
.iter()
- .map(|(role, content)| json!({"role": role, "content": content}))
+ .map(|(role, content)| message_body(client, role, content))
.collect();
let body = json!({"messages": messages_json});
let response: serde_json::Value = client.post(&path, &body).await?;
diff --git a/crates/ov_cli/src/commands/skills.rs b/crates/ov_cli/src/commands/skills.rs
index 855a82c59..c1685b667 100644
--- a/crates/ov_cli/src/commands/skills.rs
+++ b/crates/ov_cli/src/commands/skills.rs
@@ -800,7 +800,9 @@ fn normalize_git_subdir(subdir: &Path) -> Result<PathBuf> {
}
if normalized.as_os_str().is_empty() {
- return Err(Error::Parse("Git source metadata missing subdir".to_string()));
+ return Err(Error::Parse(
+ "Git source metadata missing subdir".to_string(),
+ ));
}
Ok(normalized)
@@ -1936,7 +1938,11 @@ mod tests {
let error = update_target_from_record(&record, "local-skill", false)
.expect_err("local source should not be trusted for non-interactive update");
- assert!(error.to_string().contains("server-recorded local paths are not trusted"));
+ assert!(
+ error
+ .to_string()
+ .contains("server-recorded local paths are not trusted")
+ );
}
#[test]
@@ -1954,7 +1960,11 @@ mod tests {
let error = prepare_source_from_git_record(&record)
.err()
.expect("parent dir subdir should be rejected before clone");
- assert!(error.to_string().contains("parent directory components are not allowed"));
+ assert!(
+ error
+ .to_string()
+ .contains("parent directory components are not allowed")
+ );
}
#[test]
diff --git a/crates/ov_cli/src/config.rs b/crates/ov_cli/src/config.rs
index bd6d1af72..29fbac6ef 100644
--- a/crates/ov_cli/src/config.rs
+++ b/crates/ov_cli/src/config.rs
@@ -47,6 +47,8 @@ pub struct Config {
pub user: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub actor_peer_id: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub agent_id: Option<String>,
#[serde(
default = "default_timeout",
skip_serializing_if = "is_default_timeout"
@@ -152,6 +154,7 @@ impl Default for Config {
account: None,
user: None,
actor_peer_id: None,
+ agent_id: None,
timeout: 60.0,
output: "table".to_string(),
echo_command: true,
@@ -238,6 +241,7 @@ impl Config {
.map_err(|e| Error::Config(format!("Failed to read config file: {}", e)))?;
let config: Config = serde_json::from_str(&content)
.map_err(|e| Error::Config(format!("Failed to parse config file: {}", e)))?;
+ config.validate_identity_mode()?;
Ok(config)
}
@@ -258,6 +262,19 @@ impl Config {
self.effective_auth_with_overrides(None, None, None, sudo)
}
+ pub(crate) fn effective_actor_peer_id(&self) -> Option<String> {
+ self.actor_peer_id.clone().or_else(|| self.agent_id.clone())
+ }
+
+ fn validate_identity_mode(&self) -> Result<()> {
+ if self.actor_peer_id.is_some() && self.agent_id.is_some() {
+ return Err(Error::Config(
+ "actor_peer_id cannot be used with legacy agent_id".to_string(),
+ ));
+ }
+ Ok(())
+ }
+
pub(crate) fn effective_auth_with_overrides(
&self,
api_key_override: Option<String>,
@@ -372,6 +389,44 @@ mod tests {
assert!(config.upload.exclude.is_none());
}
+ #[test]
+ fn config_deserializes_legacy_agent_id_as_effective_actor_peer() {
+ let config: Config = serde_json::from_str(
+ r#"{
+ "url": "http://127.0.0.1:1933",
+ "api_key": "test-key",
+ "agent_id": "legacy-agent"
+ }"#,
+ )
+ .expect("config should deserialize");
+
+ assert_eq!(config.agent_id.as_deref(), Some("legacy-agent"));
+ assert_eq!(
+ config.effective_actor_peer_id().as_deref(),
+ Some("legacy-agent")
+ );
+ }
+
+ #[test]
+ fn config_file_rejects_mixed_actor_peer_and_legacy_agent_id() {
+ let dir = tempfile::tempdir().expect("tempdir should be created");
+ let path = dir.path().join("ovcli.conf");
+ std::fs::write(
+ &path,
+ r#"{
+ "url": "http://127.0.0.1:1933",
+ "actor_peer_id": "peer-a",
+ "agent_id": "legacy-agent"
+ }"#,
+ )
+ .expect("config file should be written");
+
+ let error = Config::from_file(&path.to_string_lossy())
+ .expect_err("mixed identity mode should fail");
+
+ assert!(error.to_string().contains("actor_peer_id cannot be used"));
+ }
+
#[test]
fn config_deserializes_root_api_key() {
let config: Config = serde_json::from_str(
diff --git a/crates/ov_cli/src/error_ui.rs b/crates/ov_cli/src/error_ui.rs
index ec5752f0a..d034d3b19 100644
--- a/crates/ov_cli/src/error_ui.rs
+++ b/crates/ov_cli/src/error_ui.rs
@@ -345,6 +345,7 @@ fn contextual_help_command(command: &str) -> Option<String> {
"create-account",
"list-accounts",
"delete-account",
+ "migrate",
"register-user",
"list-users",
"remove-user",
diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rs
index aa2104d1d..cd7a151b8 100644
--- a/crates/ov_cli/src/handlers.rs
+++ b/crates/ov_cli/src/handlers.rs
@@ -80,7 +80,8 @@ pub async fn handle_add_resource(
auth.api_key,
auth.account,
auth.user,
- ctx.config.actor_peer_id.clone(),
+ ctx.config.effective_actor_peer_id(),
+ ctx.config.agent_id.clone(),
effective_timeout,
ctx.profile.unwrap_or(ctx.config.profile),
ctx.config.extra_headers.clone(),
@@ -399,6 +400,9 @@ pub async fn handle_admin(cmd: AdminCommands, ctx: CliContext) -> Result<()> {
commands::admin::delete_account(&client, &account_id, ctx.output_format, ctx.compact)
.await
}
+ AdminCommands::Migrate { cleanup } => {
+ commands::admin::migrate(&client, cleanup, ctx.output_format, ctx.compact).await
+ }
AdminCommands::RegisterUser {
account_id,
user_id,
diff --git a/crates/ov_cli/src/help_ui.rs b/crates/ov_cli/src/help_ui.rs
index 95248af44..8352fad05 100644
--- a/crates/ov_cli/src/help_ui.rs
+++ b/crates/ov_cli/src/help_ui.rs
@@ -1043,6 +1043,14 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[
label: "ov admin register-user <account> <user>",
description: "Register a user in an account.",
},
+ HelpItem {
+ label: "ov admin migrate --sudo",
+ description: "Start legacy agent/session migration.",
+ },
+ HelpItem {
+ label: "ov admin migrate --cleanup --sudo",
+ description: "Remove legacy agent/session directories after verifying migration.",
+ },
],
next_steps: &[
HelpItem {
@@ -1646,7 +1654,7 @@ fn localized_help_item_description<'a>(
"-c, --compact <bool>" => "使用紧凑的表格或 JSON 输出。",
"--account <account>" => "覆盖本次命令的 X-OpenViking-Account。",
"--user <user>" => "覆盖本次命令的 X-OpenViking-User。",
- "--sudo" => "使用 root API Key 执行管理命令。",
+ "--sudo" => "使用 root API Key 执行支持的管理和任务查询命令。",
_ => description,
}
}
@@ -1869,7 +1877,7 @@ fn localized_global_option_description<'a>(
"compact" => "紧凑输出",
"account" => "覆盖账户",
"user" => "覆盖用户",
- "sudo" => "admin、system 和 reindex 使用 root API Key",
+ "sudo" => "admin、system、reindex、task status/list 使用 root API Key",
_ => description,
}
}
@@ -2316,7 +2324,9 @@ mod tests {
assert!(rendered.contains("ov status"));
assert!(rendered.contains("ov tui"));
assert!(rendered.contains("-c, --compact <true|false>"));
- assert!(rendered.contains("Use root API key for admin, system, and reindex"));
+ assert!(
+ rendered.contains("Use root API key for admin, system, reindex, and task status/list")
+ );
}
#[test]
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index c2588e9d0..2f9187607 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -64,6 +64,7 @@ impl CliContext {
}
if actor_peer_id.is_some() {
config.actor_peer_id = actor_peer_id;
+ config.agent_id = None;
}
Self {
config,
@@ -97,7 +98,8 @@ impl CliContext {
auth.api_key,
auth.account,
auth.user,
- self.config.actor_peer_id.clone(),
+ self.config.effective_actor_peer_id(),
+ self.config.agent_id.clone(),
timeout_secs.unwrap_or(self.config.timeout),
self.profile.unwrap_or(self.config.profile),
self.config.extra_headers.clone(),
@@ -150,7 +152,7 @@ struct Cli {
#[arg(long = "actor-peer-id", global = true, hide = true)]
actor_peer_id: Option<String>,
- /// Use root API key for admin, system, and reindex commands
+ /// Use root API key for admin, system, reindex, and task status/list commands
#[arg(long, global = true, hide = true)]
sudo: bool,
@@ -932,12 +934,16 @@ enum Commands {
}
impl Commands {
- /// Returns true if this is an admin command that supports --sudo
- fn is_admin_command(&self) -> bool {
- matches!(
- self,
- Self::Admin { .. } | Self::System { .. } | Self::Reindex { .. }
- )
+ /// Returns true if this command supports running with the root API key.
+ fn supports_sudo(&self) -> bool {
+ match self {
+ Self::Admin { .. } | Self::System { .. } | Self::Reindex { .. } => true,
+ Self::Task { action } => matches!(
+ action,
+ TaskCommands::Status { .. } | TaskCommands::List { .. }
+ ),
+ _ => false,
+ }
}
fn supports_upload_options(&self) -> bool {
@@ -1397,6 +1403,12 @@ enum AdminCommands {
#[arg(value_name = "account-id")]
account_id: String,
},
+ /// Migrate legacy agent/session data to user-owned namespaces (ROOT only)
+ Migrate {
+ /// Remove legacy agent/session directories after migration is verified
+ #[arg(long)]
+ cleanup: bool,
+ },
/// Register a new user in an account
RegisterUser {
/// Account ID
@@ -2039,6 +2051,7 @@ fn is_admin_subcommand(token: &str) -> bool {
"create-account"
| "list-accounts"
| "delete-account"
+ | "migrate"
| "register-user"
| "list-users"
| "remove-user"
@@ -2396,25 +2409,27 @@ async fn main() {
}
// Check this before loading config so misplaced --sudo reports the command rule directly.
- if cli.sudo && !cli.command.is_admin_command() {
+ if cli.sudo && !cli.command.supports_sudo() {
let language = i18n::Language::current();
let (title, message, actions) = match language {
i18n::Language::En => (
"Command Error",
- "--sudo is only supported for admin, system, and reindex commands.",
+ "--sudo is only supported for admin, system, reindex, task status, and task list commands.",
vec![
error_ui::ErrorAction::new("ov admin --help", "Show admin commands"),
error_ui::ErrorAction::new("ov system --help", "Show system commands"),
error_ui::ErrorAction::new("ov reindex --help", "Show reindex options"),
+ error_ui::ErrorAction::new("ov task --help", "Show task commands"),
],
),
i18n::Language::ZhCn => (
"命令错误",
- "--sudo 只支持 admin、system 和 reindex 命令。",
+ "--sudo 只支持 admin、system、reindex、task status 和 task list 命令。",
vec![
error_ui::ErrorAction::new("ov admin --help", "查看管理命令"),
error_ui::ErrorAction::new("ov system --help", "查看系统命令"),
error_ui::ErrorAction::new("ov reindex --help", "查看重建索引选项"),
+ error_ui::ErrorAction::new("ov task --help", "查看任务命令"),
],
),
};
@@ -2943,7 +2958,7 @@ mod tests {
};
use crate::config::{Config, DEFAULT_CUSTOM_URL};
use crate::output::OutputFormat;
- use crate::{SystemBackendCommands, SystemCommands, handlers};
+ use crate::{AdminCommands, SystemBackendCommands, SystemCommands, handlers};
use clap::{CommandFactory, Parser};
use std::ffi::OsString;
@@ -2987,6 +3002,31 @@ mod tests {
}
}
+ #[test]
+ fn cli_parses_admin_migrate_cleanup_flag() {
+ let migrate = Cli::try_parse_from(["ov", "--sudo", "admin", "migrate"])
+ .expect("admin migrate should parse");
+ match migrate.command {
+ Commands::Admin { action } => match action {
+ AdminCommands::Migrate { cleanup } => assert!(!cleanup),
+ _ => panic!("expected admin migrate command"),
+ },
+ _ => panic!("expected admin command"),
+ }
+
+ let cleanup = Cli::try_parse_from(["ov", "--sudo", "admin", "migrate", "--cleanup"])
+ .expect("admin migrate cleanup should parse");
+
+ assert!(cleanup.sudo);
+ match cleanup.command {
+ Commands::Admin { action } => match action {
+ AdminCommands::Migrate { cleanup } => assert!(cleanup),
+ _ => panic!("expected admin migrate command"),
+ },
+ _ => panic!("expected admin command"),
+ }
+ }
+
#[test]
fn cli_parses_search_context_type() {
let cli = Cli::try_parse_from(["ov", "search", "invoice", "--context-type", "skill"])
@@ -3261,6 +3301,7 @@ mod tests {
&["ov", "admin", "create-account"],
&["ov", "admin", "list-accounts"],
&["ov", "admin", "delete-account"],
+ &["ov", "admin", "migrate"],
&["ov", "admin", "register-user"],
&["ov", "admin", "list-users"],
&["ov", "admin", "remove-user"],
@@ -3663,6 +3704,31 @@ mod tests {
assert!(cli.sudo);
}
+ #[test]
+ fn sudo_supports_task_status_and_list_only() {
+ let status = Cli::try_parse_from(["ov", "--sudo", "task", "status", "task-123"])
+ .expect("sudo task status should parse");
+ assert!(status.sudo);
+ assert!(status.command.supports_sudo());
+
+ let list = Cli::try_parse_from([
+ "ov",
+ "--sudo",
+ "task",
+ "list",
+ "--task-type",
+ "legacy_migration",
+ ])
+ .expect("sudo task list should parse");
+ assert!(list.sudo);
+ assert!(list.command.supports_sudo());
+
+ let watch = Cli::try_parse_from(["ov", "--sudo", "task", "watch", "ls"])
+ .expect("sudo task watch should still parse before runtime validation");
+ assert!(watch.sudo);
+ assert!(!watch.command.supports_sudo());
+ }
+
#[test]
fn cli_config_without_subcommand_parses_as_setup_entrypoint() {
Cli::try_parse_from(["ov", "config"]).expect("bare config command should parse");
@@ -3957,6 +4023,7 @@ mod tests {
account: Some("from-config-account".to_string()),
user: Some("from-config-user".to_string()),
actor_peer_id: Some("from-config-peer".to_string()),
+ agent_id: None,
timeout: 60.0,
output: "table".to_string(),
echo_command: true,
@@ -3983,6 +4050,45 @@ 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"));
+ assert!(ctx.config.agent_id.is_none());
+ }
+
+ #[test]
+ fn cli_context_maps_legacy_agent_id_to_actor_peer_scope() {
+ let config = Config {
+ url: DEFAULT_CUSTOM_URL.to_string(),
+ api_key: Some("test-key".to_string()),
+ root_api_key: None,
+ account: None,
+ user: None,
+ actor_peer_id: None,
+ agent_id: Some("legacy-agent".to_string()),
+ timeout: 60.0,
+ output: "table".to_string(),
+ echo_command: true,
+ show_progress: false,
+ verbose: false,
+ upload: Default::default(),
+ extra_headers: None,
+ profile: false,
+ };
+
+ let ctx = CliContext::from_config(
+ config,
+ OutputFormat::Json,
+ true,
+ None,
+ None,
+ None,
+ false,
+ None,
+ None,
+ None,
+ );
+ let client = ctx.get_client();
+
+ assert_eq!(client.actor_peer_id(), Some("legacy-agent"));
+ assert_eq!(client.legacy_agent_id(), Some("legacy-agent"));
}
#[test]
@@ -3994,6 +4100,7 @@ mod tests {
account: None,
user: None,
actor_peer_id: Some("peer-a".to_string()),
+ agent_id: None,
timeout: 60.0,
output: "table".to_string(),
echo_command: true,
diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts
index 24d681e7c..7f9d62564 100644
--- a/docs/.vitepress/config.ts
+++ b/docs/.vitepress/config.ts
@@ -33,6 +33,7 @@ const sectionNames: Record<string, string> = {
concepts: 'Concepts',
guides: 'Guides',
'agent-integrations': 'Agent Integrations',
+ migration: 'Migration',
api: 'API Reference',
faq: 'FAQ',
about: 'About',
@@ -44,6 +45,7 @@ const zhSectionNames: Record<string, string> = {
concepts: '核心概念',
guides: '指南',
'agent-integrations': 'Agent 集成',
+ migration: '迁移指南',
api: 'API 参考',
faq: '常见问题',
about: '关于',
@@ -96,7 +98,7 @@ function sidebarSection(dir: string, title: string, collapsed = true): DefaultTh
function localizedGuideSidebarItems(locale: 'en' | 'zh'): DefaultTheme.SidebarItem[] {
const labels = locale === 'zh' ? zhSectionNames : sectionNames
- const sections = ['getting-started', 'concepts', 'guides', 'agent-integrations']
+ const sections = ['getting-started', 'concepts', 'guides', 'agent-integrations', 'migration']
return sections.map((section, index) =>
sidebarSection(`${locale}/${section}`, labels[section], index !== 0)
@@ -118,14 +120,14 @@ const designSidebar: DefaultTheme.SidebarItem[] = [
]
const enNav: DefaultTheme.NavItem[] = [
- { text: navLabels.en.guide, link: '/en/getting-started/01-introduction', activeMatch: '/en/(getting-started|concepts|guides|agent-integrations)/' },
+ { text: navLabels.en.guide, link: '/en/getting-started/01-introduction', activeMatch: '/en/(getting-started|concepts|guides|agent-integrations|migration)/' },
{ text: navLabels.en.api, link: '/en/api/01-overview', activeMatch: '/en/api/' },
{ text: navLabels.en.faq, link: '/en/faq/faq', activeMatch: '/en/faq/' },
{ text: navLabels.en.about, link: '/en/about/01-about-us', activeMatch: '/en/about/' }
]
const zhNav: DefaultTheme.NavItem[] = [
- { text: navLabels.zh.guide, link: '/zh/getting-started/01-introduction', activeMatch: '/zh/(getting-started|concepts|guides|agent-integrations)/' },
+ { text: navLabels.zh.guide, link: '/zh/getting-started/01-introduction', activeMatch: '/zh/(getting-started|concepts|guides|agent-integrations|migration)/' },
{ text: navLabels.zh.api, link: '/zh/api/01-overview', activeMatch: '/zh/api/' },
{ text: navLabels.zh.faq, link: '/zh/faq/faq', activeMatch: '/zh/faq/' },
{ text: navLabels.zh.about, link: '/zh/about/01-about-us', activeMatch: '/zh/about/' }
@@ -288,6 +290,7 @@ export default defineConfig({
'/en/concepts/': localizedGuideSidebarItems('en'),
'/en/guides/': localizedGuideSidebarItems('en'),
'/en/agent-integrations/': localizedGuideSidebarItems('en'),
+ '/en/migration/': localizedGuideSidebarItems('en'),
'/en/api/': localizedReferenceSidebarItems('en'),
'/en/about/': localizedAboutSidebarItems('en'),
'/design/': designSidebar
@@ -307,6 +310,7 @@ export default defineConfig({
'/zh/concepts/': localizedGuideSidebarItems('zh'),
'/zh/guides/': localizedGuideSidebarItems('zh'),
'/zh/agent-integrations/': localizedGuideSidebarItems('zh'),
+ '/zh/migration/': localizedGuideSidebarItems('zh'),
'/zh/api/': localizedReferenceSidebarItems('zh'),
'/zh/about/': localizedAboutSidebarItems('zh')
},
diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.md
index 6d8de19c3..ec842ce64 100644
--- a/docs/en/api/08-admin.md
+++ b/docs/en/api/08-admin.md
@@ -4,10 +4,9 @@ The Admin API manages accounts and users in a multi-tenant environment. It cover
This API is available in both `api_key` and `trusted` deployments:
- In `api_key` mode, the effective role is always derived from the presented API key.
-- In `trusted` mode, ordinary requests still do not use user-key registration, but a trusted gateway may call Admin API using a registered user with appropriate role (role is looked up from user registry).
+- In `trusted` mode, ordinary requests still do not use user-key registration. When a configured `root_api_key` is presented to `/api/v1/admin/*`, the trusted upstream is authorized as ROOT.
-In `trusted` mode, role is determined by looking up `X-OpenViking-Account` + `X-OpenViking-User` from the user registry. If the user doesn't exist, role defaults to `USER`.
-For `/api/v1/admin/*`, trusted mode also permits requests with no explicit identity headers; those requests are treated as ROOT and are intended for trusted upstreams authenticated by the deployment's `root_api_key`.
+For `/api/v1/admin/*`, `trusted` mode permits requests with no explicit identity headers, and also permits target identity headers when they match the account/user in the URL. These requests are treated as ROOT after the deployment's `root_api_key` is verified. For ordinary trusted-mode data APIs, role and identity still come from `X-OpenViking-Account` + `X-OpenViking-User`.
## Roles and Permissions
@@ -48,10 +47,12 @@ Configure `root_api_key` in `~/.openviking/ovcli.conf`:
- `ov --sudo admin` - Account and user management
- `ov --sudo system` - System utility commands
- `ov --sudo reindex` - Rebuild indexes
+- `ov --sudo admin migrate` - Legacy agent/session migration and cleanup
+- `ov --sudo task status/list` - Query root/system background tasks, such as migration tasks
### Usage Limitations
-- `--sudo` only works with admin commands - using it with regular data commands will error
+- `--sudo` only works with the commands above - using it with regular data commands will error
- Must have `root_api_key` configured to use `--sudo`
## API Reference
@@ -745,6 +746,94 @@ ov --sudo admin regenerate-key acme bob
---
+### migrate_legacy_data
+
+#### 1. API Implementation Overview
+
+Migrate 0.3.x legacy `viking://agent/...` / `viking://session/...` data into the 0.4.0 user / peer namespace, or clean up old namespaces after migration has been verified. This endpoint is ROOT-only and runs as a background task.
+
+**Processing Flow:**
+1. Verify requester has ROOT privileges
+2. For `action=migrate`, run preflight checks for account registry, session owner metadata, and other prerequisites
+3. Create a root-level background task
+4. During migration, copy files and existing vector records; during cleanup, delete old vector records before deleting old AGFS directories
+
+Migration does not automatically call `reindex`. If retrieval after migration is not as expected, users should manually reindex the new paths.
+
+**Code Entry Points:**
+- `openviking/server/routers/admin.py:migrate_legacy_data` - HTTP route
+- `openviking/service/legacy_migration.py:LegacyDataMigration` - Migration implementation
+
+#### 2. Interface and Parameters
+
+**HTTP API**
+
+```
+POST /api/v1/admin/migrate
+```
+
+**Parameters**
+
+| Parameter | Type | Required | Default | Description |
+|-----------|------|----------|---------|-------------|
+| action | str | No | migrate | `migrate` runs migration; `cleanup` removes old namespaces |
+
+**Migration result fields**
+
+| Field | Description |
+|-------|-------------|
+| migrated.files / migrated.directories | Number of files and directories copied |
+| migrated.vector_records | Number of existing vector records copied |
+| migrated.skipped_vector_records | Number of old records skipped because they had no vector payload |
+| migrated.operations | Operation counts grouped by migration category |
+| skipped / warnings / created_users | Skipped items, warnings, and users created automatically |
+
+**Cleanup result fields**
+
+| Field | Description |
+|-------|-------------|
+| cleanup.directories | Number of legacy directories deleted |
+| cleanup.vector_records | Number of old vector records deleted |
+| cleanup.targets | Legacy scopes that were cleaned |
+| skipped / warnings | Skipped items and warnings |
+
+#### 3. Usage Examples
+
+**Run migration**
+
+```bash
+curl -X POST http://localhost:1933/api/v1/admin/migrate \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: <root-key>" \
+ -d '{"action": "migrate"}'
+```
+
+**Clean old namespaces**
+
+```bash
+curl -X POST http://localhost:1933/api/v1/admin/migrate \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: <root-key>" \
+ -d '{"action": "cleanup"}'
+```
+
+**CLI**
+
+```bash
+ov --sudo admin migrate --output json
+ov --sudo admin migrate --cleanup --output json
+```
+
+**Response Example**
+
+```json
+{
+ "task_id": "legacy_migration_..."
+}
+```
+
+---
+
## Full Example
### Typical Admin Workflow
diff --git a/docs/en/concepts/04-viking-uri.md b/docs/en/concepts/04-viking-uri.md
index 762ba41ee..216471890 100644
--- a/docs/en/concepts/04-viking-uri.md
+++ b/docs/en/concepts/04-viking-uri.md
@@ -26,7 +26,8 @@ Public API and CLI filesystem/content operations accept the public scopes
`resources` and `user` (plus the root URI `viking://`). `session` is retained
as a backward-compatible alias for user session paths; new session data lives
under `viking://user/{user_id}/sessions`.
-`agent` is deprecated. `temp`, `queue`, and `upload` are internal implementation
+`agent` is deprecated but remains as a read-only compatibility entry for legacy
+agent data. `temp`, `queue`, and `upload` are internal implementation
scopes and cannot be addressed directly through public API URI parameters.
## Initial Directory Structure
@@ -217,7 +218,9 @@ viking://
└── history/
```
-`viking://agent/...` is deprecated and rejected by current namespace resolution.
+`viking://agent/...` is deprecated and only kept for read-only legacy agent
+compatibility. New data should be written under
+`viking://user/{user_id}/peers/{peer_id}/...`.
## URI Operations
diff --git a/docs/en/guides/04-authentication.md b/docs/en/guides/04-authentication.md
index 9c0c78d32..7fca4c3a8 100644
--- a/docs/en/guides/04-authentication.md
+++ b/docs/en/guides/04-authentication.md
@@ -70,10 +70,10 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts/acme/users \
Trusted deployments can also call Admin API through a trusted gateway. There are two supported patterns:
-- Present only the trusted deployment's `root_api_key`. For `/api/v1/admin/*`, the server treats the request as ROOT even without `X-OpenViking-Account` / `X-OpenViking-User`.
-- Present `X-OpenViking-Account` + `X-OpenViking-User` for a registered gateway user. In that case the server looks up the effective role from the user registry.
+- Present the trusted deployment's `root_api_key`. For `/api/v1/admin/*`, the server treats the request as ROOT after validating that key.
+- Optionally also present `X-OpenViking-Account` + `X-OpenViking-User` when the admin route targets a specific account/user. Those headers must match the target URL and are kept as the request identity, but authorization still comes from the trusted `root_api_key`.
-Example using a registered gateway user:
+Example using a trusted upstream identity:
```bash
# First, register the gateway admin (do this once in api_key mode)
@@ -218,9 +218,9 @@ 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 `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.
+- `/api/v1/admin/*` is special: when a configured `root_api_key` is presented, trusted mode treats the request as ROOT. Explicit account/user headers are allowed only when they are complete and match the target URL.
+- For ordinary trusted data APIs, 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 acts as proof that the caller is an approved trusted upstream.
- If `root_api_key` is also configured, every request must still provide a matching API key.
- Only expose this mode behind a trusted network boundary or an identity-injecting gateway.
@@ -228,10 +228,10 @@ Implications:
- Trusted mode is not development mode.
- Trusted mode does not use the Admin API as a prerequisite for ordinary reads, writes, search, or session access.
-- Admin API remains available in trusted mode for users that have been registered with appropriate roles (root/admin).
+- Admin API remains available in trusted mode to upstreams authenticated with the configured `root_api_key`.
- Trusted Admin API responses omit `user_key` from account creation and user registration results.
- `root` can create/delete accounts and change roles; `admin` can manage users inside its own account; `user` cannot call Admin API.
-- To use Admin API in trusted mode, first register the gateway's service account with the appropriate role using the Admin API in api_key mode.
+- To use Admin API in trusted mode on non-localhost deployments, configure `root_api_key` and pass it with each admin request.
**curl**
diff --git a/docs/en/migration/01-user-peer-model.md b/docs/en/migration/01-user-peer-model.md
new file mode 100644
index 000000000..509583c52
--- /dev/null
+++ b/docs/en/migration/01-user-peer-model.md
@@ -0,0 +1,368 @@
+# OpenViking 0.3.x to 0.4.0 Upgrade Guide
+
+This guide is for users already running OpenViking 0.3.x. It explains what to do before and after upgrading to 0.4.0, which legacy usage remains compatible, how to migrate data, and how to move application code to the new model.
+
+## Upgrade Decision
+
+If you stay on 0.3.x, existing `agent_id`, `viking://agent/...`, and `viking://session/...` behavior does not change. But you also cannot use the 0.4.0 model and tools:
+
+- No User / Peer data model.
+- No legacy agent/session migration or cleanup command.
+- No request-level `actor_peer_id` peer view.
+- Future fixes and features around the new model are not backported to the old model.
+
+If you upgrade to 0.4.0, you do not need to migrate data immediately. 0.4.0 keeps runtime compatibility so old data remains readable:
+
+- `agent_id` can still be configured temporarily, and maps to request-level `actor_peer_id`.
+- `viking://agent/...` can still read old agent data, but is read-only.
+- `viking://session/...` can still read old session data and merges with the new session view.
+- In legacy `agent_id` mode, `find` / `search` search both new peer data and unmigrated legacy agent data.
+
+Recommended order:
+
+```text
+Back up
+ -> Upgrade server / CLI / SDK
+ -> Verify old data is still readable
+ -> Run data migration
+ -> Verify new paths
+ -> Gradually update application usage
+ -> Optionally run cleanup
+```
+
+## Back Up First
+
+Create a backup with a 0.3.x-compatible package. `0.3.24` is recommended:
+
+```bash
+pip install openviking==0.3.24 --upgrade --force-reinstall
+ov backup ./backups/openviking-before-0.4.0.ovpack
+```
+
+Check the current version:
+
+```bash
+python -c "import openviking; print(openviking.__version__)"
+ov version
+```
+
+Do not run `ov --sudo admin migrate` on 0.3.x. The migration command is only available in 0.4.0 or later.
+
+## Upgrade Server and Clients
+
+Install 0.4.0, restart the server, and make sure CLI / SDK clients are on the same version line:
+
+```bash
+pip install openviking==0.4.0 --upgrade --force-reinstall
+openviking-server --config ov.conf
+```
+
+If you use the Rust `ov` CLI from the repository, rebuild or reinstall it. Otherwise the `ov` binary on PATH may still be the old one.
+
+After upgrading, validate config and legacy reads:
+
+```bash
+ov config validate
+ov ls viking://agent
+ov ls viking://session
+ov session list
+```
+
+The `viking://session` merged compatibility view is implemented on the server. Upgrading only the CLI does not change server-side reads.
+
+## Compatibility Matrix
+
+| Legacy usage | 0.4.0 behavior |
+| --- | --- |
+| Client config `agent_id` | Supported. It maps to request-level `actor_peer_id` and marks the request as legacy agent mode. |
+| `ov ls viking://agent` | Supported for reads. If `agent_id` / `actor_peer_id` is set, only the current actor peer's legacy agent is shown. |
+| Read `viking://agent/<agent_id>/...` | Supported for old data. |
+| Write `viking://agent/...` | Not supported. New writes should go to `viking://user/<user_id>/peers/<peer_id>/...`. |
+| `ov ls viking://session` | Supported for reads. It merges new and old sessions. |
+| Read `viking://session/<session_id>/...` | Supported. New path first, legacy path as fallback. |
+| Write `viking://session/...` | Not supported. New sessions are written to `viking://user/<user_id>/sessions/...`. |
+| `find` / `search` with `agent_id` | Supported. It searches both new peer data and old agent data. |
+| `find` / `search` body `peer_id` | Not supported. Use `actor_peer_id` or `X-OpenViking-Actor-Peer` for the new peer view. |
+| Configure both `actor_peer_id` and `agent_id` | Not supported. The client/request fails. |
+| Explicit message `peer_id` while using legacy `agent_id` client | Not supported. The request fails. |
+| `role_id` memory isolation | Not supported. It is ignored after upgrade. |
+
+## Run Migration
+
+After confirming that legacy data is readable, run migration:
+
+```bash
+ov --sudo admin migrate --output json
+```
+
+The response returns a task id:
+
+```json
+{
+ "task_id": "..."
+}
+```
+
+Check task status:
+
+```bash
+ov --sudo task status <task_id>
+ov --sudo task list --task-type legacy_migration
+```
+
+HTTP API:
+
+```http
+POST /api/v1/admin/migrate
+X-API-Key: <root-key>
+```
+
+The request body can be empty. It is equivalent to:
+
+```json
+{
+ "action": "migrate"
+}
+```
+
+Query the task:
+
+```http
+GET /api/v1/tasks/{task_id}
+X-API-Key: <root-key>
+```
+
+ROOT can query migration tasks without normal account/user filtering. Migration creates one root-level task for the whole storage, not one task per account.
+
+## Migration Rules
+
+0.4.0 uses the User / Peer model:
+
+```text
+User = natural person or business user
+Peer = interaction identity under a User
+Session = conversation state under a User
+Skill = executable skill under a User
+```
+
+Migration targets:
+
+| Legacy data | New location |
+| --- | --- |
+| `viking://agent/<agent_id>/memories/...` | `viking://user/<user_id>/peers/<agent_id>/memories/...` |
+| `viking://agent/<agent_id>/resources/...` | `viking://user/<user_id>/peers/<agent_id>/resources/...` |
+| `viking://agent/<agent_id>/skills/<skill>/...` | `viking://user/<user_id>/skills/<skill>/...` |
+| `viking://session/<session_id>/...` | `viking://user/<user_id>/sessions/<session_id>/...` |
+
+Shared legacy agent data is copied into each target user's peer directory. If the legacy path already identifies a user owner, it is migrated only to that user.
+
+Migration also handles existing vector records: for memory / resource / skill files or directories that were actually copied, it reads the old record's `vector` / `sparse_vector` and scalar fields, rewrites the URI, and writes a new record. Migration does not re-embed content and does not automatically call `reindex`. When shared legacy agent data is copied to multiple users, vector records are copied once per target user URI.
+
+Old scalar-only records without a vector payload are skipped and counted in `migrated.skipped_vector_records`. Session migration copies file state only and does not handle vector records.
+
+Session owner is resolved in this order:
+
+1. `.meta.json.created_by_user_id`
+2. `.meta.json.user_id`, `.meta.json.owner_user_id`, or `.meta.json.created_by`
+3. A user hint in the legacy path, such as `/session/alice/sess-001`
+4. The only registered user in a single-user account
+
+In a multi-user account, a legacy session without an identifiable owner fails preflight. Runtime compatibility can keep that old session readable temporarily, but owner metadata should be fixed before migration.
+
+Legacy agent instructions are not migrated:
+
+```text
+viking://agent/<agent_id>/instructions
+```
+
+Migration records a warning and does not create a replacement directory.
+
+## Preflight Checks
+
+Preflight fails before creating a task for:
+
+- Legacy data under a physical account that is not present in the API key user registry.
+- A legacy session in a multi-user account with no identifiable owner.
+- A session owner that is present but is not a valid OpenViking user id.
+
+Preflight records warnings or skips, then continues, for:
+
+- A target user already has a skill with the same name. The legacy skill is skipped and the existing skill is not overwritten.
+- Legacy agent instructions are found. Instructions are not migrated.
+- A shared legacy agent exists but no target users exist in the account.
+
+If migration finds legacy data owned by a user missing from the registry, it registers that user automatically. The task result records created users but does not return plaintext user keys.
+
+If `api_key_hashing` is enabled, plaintext keys cannot be recovered from storage. Regenerate the key:
+
+```bash
+ov --sudo admin regenerate-key <account_id> <user_id>
+```
+
+## Verify Migration
+
+Check the task result:
+
+```bash
+ov --sudo task status <task_id>
+```
+
+Review:
+
+- `migrated.files` / `migrated.directories`
+- `migrated.vector_records` / `migrated.skipped_vector_records`
+- `migrated.operations`
+- `skipped`
+- `warnings`
+- `created_users`
+
+Verify new paths:
+
+```bash
+ov ls viking://user/<user_id>/peers/<agent_id>/memories
+ov ls viking://user/<user_id>/skills
+ov ls viking://user/<user_id>/sessions
+```
+
+Migration copies data and does not delete legacy paths or old vector records. Re-running it is idempotent: existing target files and skills are skipped instead of overwritten. If retrieval after migration is not as expected, run `reindex` manually on the new paths; the migration flow itself never triggers reindex.
+
+## Application Migration
+
+### Client Config
+
+Legacy config can keep working during the migration window:
+
+```json
+{
+ "agent_id": "legacy-agent"
+}
+```
+
+Recommended new config:
+
+```json
+{
+ "actor_peer_id": "legacy-agent"
+}
+```
+
+Do not configure both:
+
+```json
+{
+ "actor_peer_id": "customer-a",
+ "agent_id": "legacy-agent"
+}
+```
+
+This fails.
+
+### File Paths
+
+Legacy paths:
+
+```text
+viking://agent/code-agent/memories/profile.md
+viking://session/sess-001/messages.jsonl
+```
+
+New paths:
+
+```text
+viking://user/alice/peers/code-agent/memories/profile.md
+viking://user/alice/sessions/sess-001/messages.jsonl
+```
+
+`viking://session/<session_id>` can remain a read alias for the current user's session, but new writes and long-term references should use `viking://user/<user_id>/sessions/<session_id>`.
+
+### find / search
+
+During the migration window, if you still need unmigrated old agent data, keep using:
+
+```json
+{
+ "query": "deployment notes",
+ "agent_id": "legacy-agent"
+}
+```
+
+After migration, when old agent data is no longer needed, move to client/request-level `actor_peer_id`.
+
+### Session Messages
+
+A legacy `agent_id` client automatically attaches `agent_id` to assistant messages. After moving to the new usage, do not rely on `agent_id`; use message `peer_id` when you need to attribute a message speaker.
+
+## Deferring Data Migration
+
+It is acceptable as a short-term transition, with these limits:
+
+- Old agent/session data is readable, but legacy namespaces are not writable.
+- New sessions and new resources are written to the new namespace, so data can exist in both old and new paths for a while.
+- Legacy `agent_id` retrieval searches both old and new data; pure `actor_peer_id` does not search old `viking://agent` by default.
+- In multi-user accounts, old sessions without clear owner metadata may be readable at runtime but will fail formal migration preflight.
+- Legacy directories and old vector records remain until cleanup.
+
+This is intended as a migration window, not a long-term state.
+
+## Optional Cleanup
+
+After verifying migration, delete legacy namespaces:
+
+```bash
+ov --sudo admin migrate --cleanup --output json
+ov --sudo task status <cleanup_task_id>
+```
+
+HTTP request body:
+
+```json
+{
+ "action": "cleanup"
+}
+```
+
+Cleanup deletes only:
+
+```text
+/local/<account>/agent
+/local/<account>/session
+/local/<account>/user/<user>/agent
+```
+
+Cleanup deletes old vector records under those legacy URI scopes before deleting the matching AGFS directories. If vector read or delete fails, that directory is skipped so files are not removed while stale index records remain. Cleanup does not delete files or vector records under the new user / peer paths.
+
+It does not delete new model directories:
+
+```text
+/local/<account>/user/<user>/peers
+/local/<account>/user/<user>/sessions
+/local/<account>/user/<user>/skills
+```
+
+After cleanup, `viking://agent/...` is no longer the way to read migrated peer data. Use the new paths. `viking://session/...` can still be used as an alias for the current user's new sessions.
+
+## FAQ
+
+### ov ls viking://agent shows only one agent
+
+If `agent_id` or `actor_peer_id` is configured, this is expected. The `viking://agent` root is filtered to the current actor peer.
+
+### ov ls viking://session is still empty
+
+Make sure the server has been restarted on 0.4.0. The `viking://session` merged read view runs on the server; upgrading only the CLI is not enough.
+
+### Config has both actor_peer_id and agent_id
+
+This is not allowed. Keep `agent_id` for legacy mode, or remove it and use `actor_peer_id`.
+
+### Preflight reports an unknown account
+
+The physical storage contains legacy data for an account missing from the API key registry. Restore or recreate that account before migrating.
+
+### Preflight reports an unresolved session owner
+
+Add owner metadata to the legacy session `.meta.json`, or move the session under a path that clearly identifies the owner, then run migration again.
+
+### A skill did not migrate
+
+Check the task `skipped` list. The usual reason is that the target user already had a skill with the same name. Migration does not overwrite existing skills.
diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.md
index 3df10861e..60172d923 100644
--- a/docs/zh/api/08-admin.md
+++ b/docs/zh/api/08-admin.md
@@ -4,10 +4,9 @@ Admin API 用于多租户环境下的账户和用户管理。包括工作区(a
该 API 适用于 `api_key` 和 `trusted` 两种模式下的管理链路:
- 在 `api_key` 模式下,角色始终从 API Key 推导。
-- 在 `trusted` 模式下,普通请求仍然不依赖 user key 注册流程;但受信任网关可以使用已注册且具有适当角色的用户调用 Admin API(角色从用户注册表查询)。
+- 在 `trusted` 模式下,普通请求仍然不依赖 user key 注册流程;当请求 `/api/v1/admin/*` 并携带已配置的 `root_api_key` 时,受信上游会按 ROOT 授权。
-在 `trusted` 模式下,角色通过查询 `X-OpenViking-Account` + `X-OpenViking-User` 从用户注册表确定。如果用户不存在,角色默认为 `USER`。
-对于 `/api/v1/admin/*`,`trusted` 模式还允许不携带显式身份头;这类请求会被视为 ROOT,适用于仅通过部署级 `root_api_key` 认证的受信上游。
+对于 `/api/v1/admin/*`,`trusted` 模式允许不携带显式身份头;也允许携带与 URL 中 account/user 匹配的目标身份头。只要部署级 `root_api_key` 校验通过,这类请求都会按 ROOT 处理。普通 trusted 数据 API 的身份和角色仍然来自 `X-OpenViking-Account` + `X-OpenViking-User`。
## 角色与权限
@@ -48,10 +47,12 @@ Admin API 用于多租户环境下的账户和用户管理。包括工作区(a
- `ov --sudo admin` - 账户和用户管理
- `ov --sudo system` - 系统工具命令
- `ov --sudo reindex` - 重建索引
+- `ov --sudo admin migrate` - legacy agent/session 迁移和 cleanup
+- `ov --sudo task status/list` - 查询 root/system 后台任务,例如迁移任务
### 使用限制
-- `--sudo` 仅适用于管理类命令,用于普通数据命令会报错
+- `--sudo` 仅适用于上面的命令,用于普通数据命令会报错
- 必须配置 `root_api_key` 才能使用 `--sudo`
## API 参考
@@ -742,6 +743,94 @@ ov --sudo admin regenerate-key acme bob
---
+### migrate_legacy_data
+
+#### 1. API 实现介绍
+
+将 0.3.x legacy `viking://agent/...` / `viking://session/...` 数据迁移到 0.4.0 的 user / peer namespace,或在确认迁移结果后清理旧 namespace。该接口仅 ROOT 可调用,并以后台 task 执行。
+
+**处理流程:**
+1. 验证请求者具有 ROOT 权限
+2. `action=migrate` 时执行 preflight,检查 account registry、session owner 等前置条件
+3. 创建 root 级后台 task
+4. 迁移时复制文件和已有向量记录;cleanup 时先删除旧向量记录,再删除旧 AGFS 目录
+
+迁移不会自动调用 `reindex`。如果迁移后的检索结果不符合预期,需要用户对新路径手动执行 reindex。
+
+**代码入口:**
+- `openviking/server/routers/admin.py:migrate_legacy_data` - HTTP 路由
+- `openviking/service/legacy_migration.py:LegacyDataMigration` - 迁移实现
+
+#### 2. 接口和参数说明
+
+**HTTP API**
+
+```
+POST /api/v1/admin/migrate
+```
+
+**参数**
+
+| 参数 | 类型 | 必填 | 默认值 | 说明 |
+|------|------|------|--------|------|
+| action | str | 否 | migrate | `migrate` 执行迁移;`cleanup` 清理旧 namespace |
+
+**迁移结果字段**
+
+| 字段 | 说明 |
+|------|------|
+| migrated.files / migrated.directories | 复制的文件和目录数量 |
+| migrated.vector_records | 复制的已有向量记录数量 |
+| migrated.skipped_vector_records | 因没有向量 payload 而跳过的旧记录数量 |
+| migrated.operations | 按迁移类别统计的操作数量 |
+| skipped / warnings / created_users | 跳过项、告警、自动创建的用户 |
+
+**Cleanup 结果字段**
+
+| 字段 | 说明 |
+|------|------|
+| cleanup.directories | 删除的 legacy 目录数量 |
+| cleanup.vector_records | 删除的旧向量记录数量 |
+| cleanup.targets | 已清理的 legacy scope |
+| skipped / warnings | 跳过项和告警 |
+
+#### 3. 使用示例
+
+**执行迁移**
+
+```bash
+curl -X POST http://localhost:1933/api/v1/admin/migrate \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: <root-key>" \
+ -d '{"action": "migrate"}'
+```
+
+**清理旧 namespace**
+
+```bash
+curl -X POST http://localhost:1933/api/v1/admin/migrate \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: <root-key>" \
+ -d '{"action": "cleanup"}'
+```
+
+**CLI**
+
+```bash
+ov --sudo admin migrate --output json
+ov --sudo admin migrate --cleanup --output json
+```
+
+**响应示例**
+
+```json
+{
+ "task_id": "legacy_migration_..."
+}
+```
+
+---
+
## 完整示例
### 典型管理流程
diff --git a/docs/zh/concepts/04-viking-uri.md b/docs/zh/concepts/04-viking-uri.md
index 431ae0a73..fead3b01b 100644
--- a/docs/zh/concepts/04-viking-uri.md
+++ b/docs/zh/concepts/04-viking-uri.md
@@ -24,7 +24,8 @@ viking://{scope}/{path}
公开 API 和 CLI 的文件系统/内容操作接受公开作用域 `resources` 和 `user`,
以及根 URI `viking://`。`session` 保留为 user session 路径的向后兼容别名;
-新 session 数据位于 `viking://user/{user_id}/sessions`。`agent` 已废弃。
+新 session 数据位于 `viking://user/{user_id}/sessions`。`agent` 已废弃,但仍作为
+legacy agent 数据的只读兼容入口。
`temp`、`queue` 和 `upload` 是内部实现作用域,不能通过公开 API 的 URI 参数直接访问。
## 初始目录
@@ -214,7 +215,8 @@ viking://
└── history/
```
-`viking://agent/...` 已废弃,当前 namespace 解析会拒绝该路径。
+`viking://agent/...` 已废弃,仅保留 legacy agent 数据的只读兼容;新数据应写入
+`viking://user/{user_id}/peers/{peer_id}/...`。
## URI 操作
diff --git a/docs/zh/guides/04-authentication.md b/docs/zh/guides/04-authentication.md
index 8f206518e..4670858b2 100644
--- a/docs/zh/guides/04-authentication.md
+++ b/docs/zh/guides/04-authentication.md
@@ -70,10 +70,10 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts/acme/users \
受信部署也可以通过受信网关调用 Admin API,目前支持两种方式:
-- 只携带受信部署自身的 `root_api_key`。对于 `/api/v1/admin/*`,即使没有 `X-OpenViking-Account` / `X-OpenViking-User`,服务端也会将请求视为 ROOT。
-- 携带 `X-OpenViking-Account` + `X-OpenViking-User`,并使用一个已注册的网关用户。此时服务端会从用户注册表查询该身份的实际角色。
+- 携带受信部署自身的 `root_api_key`。对于 `/api/v1/admin/*`,服务端校验该 key 后会将请求视为 ROOT。
+- 如果 Admin 路由指向具体 account/user,也可以同时携带 `X-OpenViking-Account` + `X-OpenViking-User`。这些 header 必须与目标 URL 匹配,并会保留为请求身份;授权仍来自受信 `root_api_key`。
-下面是“已注册网关用户”这种方式的示例:
+下面是“受信上游身份”这种方式的示例:
```bash
# 首先,注册网关管理员(在 api_key 模式下执行一次)
@@ -217,9 +217,9 @@ Trusted 模式规则:
- 普通数据访问不需要先注册 user key,也不依赖 user key 分发流程
- 租户级请求必须包含 `X-OpenViking-Account` 和 `X-OpenViking-User`
-- `/api/v1/admin/*` 是特例:如果没有显式身份,trusted 模式会将请求视为 ROOT,用于只通过部署级 root API key 认证的受信上游
-- 角色通过在 APIKeyManager 中查找 account/user 确定。如果用户存在,使用其配置的角色;否则默认为 `USER`
-- trusted 身份完全来自请求头,而不是 user key;如果同时配置了 `root_api_key`,它仍然只是“这个上游是被允许的 trusted 调用方”的证明
+- `/api/v1/admin/*` 是特例:当请求携带已配置的 `root_api_key` 时,trusted 模式会将请求视为 ROOT。显式 account/user header 只有在完整且与目标 URL 匹配时才允许
+- 普通 trusted 数据 API 的角色通过在 APIKeyManager 中查找 account/user 确定。如果用户存在,使用其配置的角色;否则默认为 `USER`
+- trusted 身份完全来自请求头,而不是 user key;如果同时配置了 `root_api_key`,它表示“这个上游是被允许的 trusted 调用方”
- 如果同时配置了 `root_api_key`,每个请求仍然必须带匹配的 API Key
- 只应部署在受信网络边界之后,或由身份注入网关统一转发
@@ -227,10 +227,10 @@ Trusted 模式规则:
- `trusted` 不是开发模式
- `trusted` 下的普通读写、检索、会话访问不需要先走 Admin API 注册流程
-- `trusted` 模式下,已注册并具有适当角色(root/admin)的用户仍然可以调用 Admin API
+- `trusted` 模式下,携带已配置 `root_api_key` 的受信上游可以调用 Admin API
- `trusted` 模式下,创建 account 或注册用户的 Admin API 响应不会返回 `user_key`
- `root` 可以创建/删除 account 并修改角色;`admin` 可以管理自己 account 下的用户;`user` 不能调用 Admin API
-- 要在 trusted 模式下使用 Admin API,首先需要在 api_key 模式下使用 Admin API 注册网关服务账户并赋予适当角色
+- 非 localhost 部署要在 trusted 模式下使用 Admin API,需要配置 `root_api_key`,并在每个管理请求中携带它
**curl**
diff --git a/docs/zh/migration/01-user-peer-model.md b/docs/zh/migration/01-user-peer-model.md
new file mode 100644
index 000000000..64ec0c80b
--- /dev/null
+++ b/docs/zh/migration/01-user-peer-model.md
@@ -0,0 +1,368 @@
+# OpenViking 0.3.x 到 0.4.0 升级指南
+
+本文面向已经运行 OpenViking 0.3.x 的用户,说明升级到 0.4.0 前后需要做什么、哪些旧用法仍然兼容、数据迁移如何执行,以及业务代码如何逐步迁移到新模型。
+
+## 是否需要升级
+
+如果继续停留在 0.3.x,现有 `agent_id`、`viking://agent/...`、`viking://session/...` 行为不会变化,但也无法使用 0.4.0 的能力:
+
+- 没有 User / Peer 数据模型。
+- 没有 legacy agent/session 数据迁移和 cleanup 命令。
+- 没有 `actor_peer_id` 请求级 peer 视图。
+- 后续围绕新模型的修复和能力不会回补到旧模型。
+
+如果升级到 0.4.0,可以先不迁移数据。0.4.0 提供运行期兼容,旧数据不会因为升级立即不可读:
+
+- `agent_id` 仍可临时配置,会映射成 `actor_peer_id`。
+- `viking://agent/...` 仍可读旧 agent 数据,但只读。
+- `viking://session/...` 仍可读旧 session 数据,并会合并新 session 视图。
+- legacy `agent_id` 模式下,`find` / `search` 会同时查新 peer 数据和未迁移的旧 agent 数据。
+
+推荐顺序:
+
+```text
+备份
+ -> 升级 server / CLI / SDK
+ -> 验证旧数据仍可读
+ -> 执行数据迁移
+ -> 验证新路径
+ -> 逐步迁移业务用法
+ -> 可选 cleanup
+```
+
+## 升级前备份
+
+先用 0.3.x 兼容版本创建备份。建议使用 `0.3.24`:
+
+```bash
+pip install openviking==0.3.24 --upgrade --force-reinstall
+ov backup ./backups/openviking-before-0.4.0.ovpack
+```
+
+确认当前版本:
+
+```bash
+python -c "import openviking; print(openviking.__version__)"
+ov version
+```
+
+不要在 0.3.x 上执行 `ov --sudo admin migrate`。迁移命令只在 0.4.0 或更新版本可用。
+
+## 升级服务和客户端
+
+安装 0.4.0,重启服务端,并确保 CLI / SDK 也升级到同一版本线:
+
+```bash
+pip install openviking==0.4.0 --upgrade --force-reinstall
+openviking-server --config ov.conf
+```
+
+如果使用仓库内 Rust `ov` CLI,需要重新构建或安装 CLI;否则本地 `ov` 可能仍是旧二进制。
+
+升级后先验证配置和旧数据读取:
+
+```bash
+ov config validate
+ov ls viking://agent
+ov ls viking://session
+ov session list
+```
+
+`viking://session` 的兼容合并发生在服务端。只升级 CLI、不重启 server,不会改变服务端读取行为。
+
+## 兼容性速查
+
+| 旧用法 | 0.4.0 行为 |
+| --- | --- |
+| client 配置 `agent_id` | 支持,映射成请求级 `actor_peer_id`,并标记为 legacy agent 模式。 |
+| `ov ls viking://agent` | 支持读;如果设置了 `agent_id` / `actor_peer_id`,只显示当前 actor peer 对应的 legacy agent。 |
+| 读 `viking://agent/<agent_id>/...` | 支持读旧数据。 |
+| 写 `viking://agent/...` | 不支持。新写入应进入 `viking://user/<user_id>/peers/<peer_id>/...`。 |
+| `ov ls viking://session` | 支持读,会合并新 session 和旧 session。 |
+| 读 `viking://session/<session_id>/...` | 支持读,按新路径优先、旧路径兜底。 |
+| 写 `viking://session/...` | 不支持。新 session 写入 `viking://user/<user_id>/sessions/...`。 |
+| `find` / `search` 传 `agent_id` | 支持,会同时查新 peer 数据和旧 agent 数据。 |
+| `find` / `search` body 传旧 `peer_id` | 不支持。新 peer 视图使用 `actor_peer_id` 或 `X-OpenViking-Actor-Peer`。 |
+| 同时配置 `actor_peer_id` 和 `agent_id` | 不支持,会报错。 |
+| legacy `agent_id` client 下显式传 message `peer_id` | 不支持,会报错。 |
+| `role_id` 记忆隔离 | 不再支持,升级后忽略。 |
+
+## 执行数据迁移
+
+确认升级后旧数据可读,再执行迁移:
+
+```bash
+ov --sudo admin migrate --output json
+```
+
+响应会返回 task id:
+
+```json
+{
+ "task_id": "..."
+}
+```
+
+查询任务:
+
+```bash
+ov --sudo task status <task_id>
+ov --sudo task list --task-type legacy_migration
+```
+
+HTTP API:
+
+```http
+POST /api/v1/admin/migrate
+X-API-Key: <root-key>
+```
+
+请求体可以为空,等价于:
+
+```json
+{
+ "action": "migrate"
+}
+```
+
+查询任务:
+
+```http
+GET /api/v1/tasks/{task_id}
+X-API-Key: <root-key>
+```
+
+ROOT 查询迁移任务时不会按普通 account/user 过滤。迁移会为整个存储创建一个 root 级别 task,不会按 account 分别创建 task。
+
+## 迁移规则
+
+0.4.0 的新模型是 User / Peer:
+
+```text
+User = 自然人或业务使用者
+Peer = User 下的交互对象
+Session = User 下的会话状态
+Skill = User 下的可执行技能
+```
+
+迁移目标:
+
+| 旧数据 | 新位置 |
+| --- | --- |
+| `viking://agent/<agent_id>/memories/...` | `viking://user/<user_id>/peers/<agent_id>/memories/...` |
+| `viking://agent/<agent_id>/resources/...` | `viking://user/<user_id>/peers/<agent_id>/resources/...` |
+| `viking://agent/<agent_id>/skills/<skill>/...` | `viking://user/<user_id>/skills/<skill>/...` |
+| `viking://session/<session_id>/...` | `viking://user/<user_id>/sessions/<session_id>/...` |
+
+共享 legacy agent 数据会复制到每个目标 user 的 peer 目录。如果旧路径已经表达了 user owner,只迁移到该 user。
+
+迁移会一并处理已有向量索引:对实际复制成功的 memory / resource / skill 文件或目录,直接读取旧记录中的 `vector` / `sparse_vector` 和标量字段,重写 URI 后写入新记录。迁移不会重新向量化,也不会自动调用 `reindex`。共享 legacy agent 数据复制到多个 user 时,会按每个目标 user URI 写入多份向量记录。
+
+没有向量 payload 的旧标量记录会跳过并计入 `migrated.skipped_vector_records`。Session 迁移只复制文件状态,不处理向量索引。
+
+Session owner 按以下顺序解析:
+
+1. `.meta.json.created_by_user_id`
+2. `.meta.json.user_id`、`.meta.json.owner_user_id` 或 `.meta.json.created_by`
+3. 旧路径里的 user hint,例如 `/session/alice/sess-001`
+4. 单用户 account 下的唯一注册用户
+
+多用户 account 下,如果某个 legacy session 无法识别 owner,preflight 会失败。升级后的运行期兼容可以临时读取旧 session,但正式迁移前仍应补齐 owner。
+
+Legacy agent instructions 不迁移:
+
+```text
+viking://agent/<agent_id>/instructions
+```
+
+迁移会记录 warning,不创建替代目录。
+
+## 迁移前检查
+
+以下问题会在 task 创建前直接失败:
+
+- 物理存储中存在 legacy 数据,但对应 account 不在 API key user registry 中。
+- 多用户 account 下存在无法识别 owner 的 legacy session。
+- session owner 存在,但不是合法的 OpenViking user id。
+
+以下问题会记录为 warning 或 skipped,并继续迁移:
+
+- 目标 user 已经存在同名 skill。旧 skill 会被跳过,不覆盖现有 skill。
+- 发现 legacy agent instructions。Instructions 不迁移。
+- 存在共享 legacy agent,但 account 下没有可迁移的目标 user。
+
+如果迁移发现 legacy 数据 owner 不在 user registry 中,会自动注册该 user。迁移结果只记录自动创建了哪些用户,不返回明文 user key。
+
+如果开启了 `api_key_hashing`,明文 key 无法从存储中反查。需要重新生成:
+
+```bash
+ov --sudo admin regenerate-key <account_id> <user_id>
+```
+
+## 验证迁移结果
+
+查看任务结果:
+
+```bash
+ov --sudo task status <task_id>
+```
+
+重点看:
+
+- `migrated.files` / `migrated.directories`
+- `migrated.vector_records` / `migrated.skipped_vector_records`
+- `migrated.operations`
+- `skipped`
+- `warnings`
+- `created_users`
+
+验证新路径:
+
+```bash
+ov ls viking://user/<user_id>/peers/<agent_id>/memories
+ov ls viking://user/<user_id>/skills
+ov ls viking://user/<user_id>/sessions
+```
+
+迁移只复制数据,不删除 legacy 路径或旧向量记录。重复执行是幂等的:已存在的目标文件和 skill 会被跳过,不会覆盖。如果迁移后的检索结果不符合预期,再由用户对新路径手动执行 `reindex`;迁移流程本身不会触发 reindex。
+
+## 业务用法迁移
+
+### Client 配置
+
+旧配置可以先继续用:
+
+```json
+{
+ "agent_id": "legacy-agent"
+}
+```
+
+推荐逐步改成:
+
+```json
+{
+ "actor_peer_id": "legacy-agent"
+}
+```
+
+不要同时配置:
+
+```json
+{
+ "actor_peer_id": "customer-a",
+ "agent_id": "legacy-agent"
+}
+```
+
+这会报错。
+
+### 文件路径
+
+旧路径:
+
+```text
+viking://agent/code-agent/memories/profile.md
+viking://session/sess-001/messages.jsonl
+```
+
+新路径:
+
+```text
+viking://user/alice/peers/code-agent/memories/profile.md
+viking://user/alice/sessions/sess-001/messages.jsonl
+```
+
+`viking://session/<session_id>` 可以继续作为当前 user session 的读 alias 使用,但新写入和长期引用建议使用 `viking://user/<user_id>/sessions/<session_id>`。
+
+### find / search
+
+迁移窗口内,如果还需要读取未迁移的旧 agent 数据,可以继续传:
+
+```json
+{
+ "query": "deployment notes",
+ "agent_id": "legacy-agent"
+}
+```
+
+迁移完成并确认不再需要旧 agent 数据后,改为 client/request 级 `actor_peer_id`。
+
+### 会话消息
+
+legacy `agent_id` client 会自动给 assistant message 带 `agent_id`。迁移到新用法后,不要再依赖 `agent_id`;需要表达消息说话人时使用 message `peer_id`。
+
+## 暂不迁移数据
+
+升级后可以暂时不迁移,但要知道这些限制:
+
+- 旧 agent/session 数据可读,但旧 namespace 不可写。
+- 新 session 和新资源会写入新 namespace,数据会在新旧路径并存一段时间。
+- legacy `agent_id` 检索会同时查新旧数据;纯 `actor_peer_id` 不会默认查旧 `viking://agent`。
+- 多用户 account 下 owner 不明确的旧 session,运行期可能可读,但正式迁移会被 preflight 拦截。
+- cleanup 之前旧目录和旧向量记录仍会保留。
+
+因此不迁移适合作为短期过渡,不建议作为长期状态。
+
+## 可选 cleanup
+
+确认迁移结果无误后,可以删除旧 namespace:
+
+```bash
+ov --sudo admin migrate --cleanup --output json
+ov --sudo task status <cleanup_task_id>
+```
+
+HTTP 请求体:
+
+```json
+{
+ "action": "cleanup"
+}
+```
+
+Cleanup 只删除:
+
+```text
+/local/<account>/agent
+/local/<account>/session
+/local/<account>/user/<user>/agent
+```
+
+Cleanup 会先删除上述 legacy URI scope 下的旧向量记录,再删除对应 AGFS 目录。若向量读取或删除失败,该目录会被跳过,避免旧文件已删除但旧索引仍残留。Cleanup 不会删除新 user / peer 路径下的文件或向量记录。
+
+不会删除新模型目录:
+
+```text
+/local/<account>/user/<user>/peers
+/local/<account>/user/<user>/sessions
+/local/<account>/user/<user>/skills
+```
+
+Cleanup 后,`viking://agent/...` 不再用于读取迁移后的 peer 数据;请使用新路径。`viking://session/...` 仍可作为当前 user session 的 alias 读取新 session。
+
+## 常见问题
+
+### ov ls viking://agent 只看到一个 agent
+
+如果配置了 `agent_id` 或 `actor_peer_id`,这是预期行为。`viking://agent` 根目录会过滤到当前 actor peer,只显示对应 legacy agent。
+
+### ov ls viking://session 仍为空
+
+确认服务端已经重启并加载 0.4.0。`viking://session` 的合并读发生在服务端;只升级 CLI 不会改变服务端读取行为。
+
+### 配置同时有 actor_peer_id 和 agent_id
+
+这是不允许的。保留 `agent_id` 进入 legacy 模式,或删除 `agent_id` 后改用 `actor_peer_id`。
+
+### Preflight 报告 unknown account
+
+物理存储中存在某个 account 的 legacy 数据,但 API key registry 中没有这个 account。先恢复或重新创建该 account,再重新执行迁移。
+
+### Preflight 报告 unresolved session owner
+
+给 legacy session 的 `.meta.json` 补充 owner 字段,或把 session 移到能明确识别 owner 的旧路径下,然后重新执行迁移。
+
+### 某个 skill 没有迁移
+
+查看 task 的 `skipped` 列表。最常见原因是目标 user 已经存在同名 skill。迁移不会覆盖现有 skill。
diff --git a/openviking/async_client.py b/openviking/async_client.py
index 7fd936723..8da2c3d5e 100644
--- a/openviking/async_client.py
+++ b/openviking/async_client.py
@@ -48,6 +48,7 @@ class AsyncOpenViking:
self,
path: Optional[str] = None,
actor_peer_id: Optional[str] = None,
+ agent_id: Optional[str] = None,
):
"""
Initialize OpenViking client (embedded mode).
@@ -55,6 +56,7 @@ class AsyncOpenViking:
Args:
path: Local storage path (overrides ov.conf storage path).
actor_peer_id: Optional view filter for the current user's peer collection.
+ agent_id: Legacy alias for actor_peer_id.
"""
# Singleton guard for repeated initialization
if hasattr(self, "_singleton_initialized") and self._singleton_initialized:
@@ -68,6 +70,7 @@ class AsyncOpenViking:
self._client: BaseClient = LocalClient(
path=path,
actor_peer_id=actor_peer_id,
+ agent_id=agent_id,
)
self._singleton_initialized = True
diff --git a/openviking/client/local.py b/openviking/client/local.py
index e22366a83..c1679abe1 100644
--- a/openviking/client/local.py
+++ b/openviking/client/local.py
@@ -7,7 +7,7 @@ Implements BaseClient interface using direct service calls (embedded mode).
from typing import Any, Dict, List, Optional, Union
-from openviking.core.peer_id import normalize_peer_id
+from openviking.core.peer_id import normalize_peer_id, normalize_peer_selector
from openviking.server.identity import RequestContext, Role
from openviking.service import OpenVikingService
from openviking.telemetry import TelemetryRequest
@@ -17,7 +17,7 @@ from openviking.telemetry.execution import (
)
from openviking.utils.search_filters import SearchContextTypeInput, merge_search_filter
from openviking_cli.client.base import BaseClient
-from openviking_cli.exceptions import NotFoundError
+from openviking_cli.exceptions import InvalidArgumentError, NotFoundError
from openviking_cli.session.user_id import UserIdentifier
from openviking_cli.utils import run_async
@@ -62,6 +62,7 @@ class LocalClient(BaseClient):
path: Optional[str] = None,
user: Optional[UserIdentifier] = None,
actor_peer_id: Optional[str] = None,
+ agent_id: Optional[str] = None,
):
"""Initialize LocalClient.
@@ -69,16 +70,21 @@ class LocalClient(BaseClient):
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.
+ agent_id: Legacy alias for actor_peer_id.
"""
self._service = OpenVikingService(
path=path,
user=user or UserIdentifier.the_default_user(),
)
self._user = self._service.user
+ if actor_peer_id and agent_id:
+ raise ValueError("actor_peer_id cannot be used with legacy agent_id")
+ self._legacy_agent_id = normalize_peer_selector(None, agent_id=agent_id)
self._ctx = RequestContext(
user=self._user,
role=Role.USER,
- actor_peer_id=normalize_peer_id(actor_peer_id),
+ actor_peer_id=normalize_peer_selector(actor_peer_id, agent_id=agent_id),
+ legacy_agent_id=self._legacy_agent_id,
)
@property
@@ -573,7 +579,7 @@ class LocalClient(BaseClient):
session.add_message(
role,
message_parts,
- peer_id=peer_id,
+ peer_id=self._resolve_message_peer_id(role, peer_id),
created_at=created_at,
)
return {
@@ -625,7 +631,8 @@ class LocalClient(BaseClient):
{
"role": role,
"parts": message_parts,
- "peer_id": normalize_peer_id(
+ "peer_id": self._resolve_message_peer_id(
+ role,
message.get("peer_id"),
),
"created_at": message.get("created_at"),
@@ -639,6 +646,17 @@ class LocalClient(BaseClient):
"added": len(added),
}
+ def _resolve_message_peer_id(self, role: str, peer_id: Optional[str]) -> Optional[str]:
+ if self._legacy_agent_id is None:
+ return normalize_peer_id(peer_id)
+ if peer_id is not None:
+ raise InvalidArgumentError(
+ "peer_id cannot be used when client is configured with legacy agent_id"
+ )
+ if role == "assistant":
+ return self._legacy_agent_id
+ return None
+
# ============= Pack =============
async def export_ovpack(
diff --git a/openviking/core/directories.py b/openviking/core/directories.py
index 187545e57..1b4e75d81 100644
--- a/openviking/core/directories.py
+++ b/openviking/core/directories.py
@@ -124,6 +124,11 @@ PRESET_DIRECTORIES: Dict[str, DirectoryDefinition] = {
overview="Access when the current User or a proxy acting with the current User's API key needs to execute specific tasks. Skills categorized by tags, "
"should retrieve relevant skills before executing tasks, select most appropriate skill to execute.",
),
+ DirectoryDefinition(
+ path="sessions",
+ abstract="User session registry. Stores conversation state, live messages, tool outputs, and session history owned by the current User.",
+ overview="Use this directory to inspect or migrate user-owned session records. Session entries are created lazily when sessions are started.",
+ ),
],
),
"resources": DirectoryDefinition(
diff --git a/openviking/core/namespace.py b/openviking/core/namespace.py
index 717e9e5ca..d766ec3dd 100644
--- a/openviking/core/namespace.py
+++ b/openviking/core/namespace.py
@@ -12,6 +12,7 @@ from openviking_cli.utils.uri import VikingURI
_CONTENT_TYPES_BY_SCOPE = {
"user": {"memories": "memory", "resources": "resource", "skills": "skill"},
+ "agent": {"memories": "memory", "resources": "resource", "skills": "skill"},
}
_PEER_CONTENT_SEGMENTS = frozenset({"memories", "resources"})
_USER_RELATIVE_ROOT_SEGMENTS = frozenset({"peers", "privacy", "sessions"})
@@ -55,7 +56,7 @@ class UriClassification:
@property
def is_agent_namespace_root(self) -> bool:
- return False
+ return self.scope == "agent" and len(self.parts) == 2
@property
def is_memory_root(self) -> bool:
@@ -114,6 +115,8 @@ def relative_uri_path(root_uri: str, uri: str) -> str:
def _content_segment_index(parts: tuple[str, ...]) -> Optional[int]:
"""Return the first content segment after a user namespace root."""
+ if len(parts) >= 3 and parts[0] == "agent" and parts[2] in _CONTENT_TYPES_BY_SCOPE["agent"]:
+ return 2
if len(parts) < 2 or parts[0] != "user":
return None
if parts[1] in _CONTENT_TYPES_BY_SCOPE["user"]:
@@ -247,7 +250,7 @@ def resolve_uri(
if scope == "user":
return _resolve_user_uri(parts, ctx=ctx, require_canonical=require_canonical)
if scope == "agent":
- raise NamespaceShapeError("viking://agent is deprecated; use viking://user instead")
+ return ResolvedNamespace(uri=VikingURI.normalize(uri).rstrip("/"), scope=scope)
if scope == "session":
return _resolve_session_uri(parts, ctx=ctx, require_canonical=require_canonical)
if scope in {"resources", "temp", "queue", "upload"}:
@@ -276,6 +279,11 @@ def is_accessible(uri: str, ctx: RequestContext) -> bool:
if target.owner_user_id and target.owner_user_id != ctx.user.user_id:
return False
return True
+ if target.scope == "agent":
+ parts = uri_parts(target.uri)
+ if ctx.actor_peer_id and len(parts) >= 2 and parts[1] != ctx.actor_peer_id:
+ return False
+ return True
return True
diff --git a/openviking/core/peer_id.py b/openviking/core/peer_id.py
index 4d3782770..7fc54ebb3 100644
--- a/openviking/core/peer_id.py
+++ b/openviking/core/peer_id.py
@@ -15,3 +15,42 @@ def normalize_peer_id(
return normalize_identifier_part(peer_id, "peer_id")
except ValueError as exc:
raise ValueError(f"Invalid peer_id: {exc}") from exc
+
+
+def peer_id_from_legacy_agent_uri(agent_uri: Optional[str]) -> Optional[str]:
+ """Resolve a legacy agent URI or ID into a peer_id."""
+ if not agent_uri:
+ return None
+ value = agent_uri.strip()
+ if not value:
+ return None
+ if value.startswith("viking://agent/"):
+ parts = [part for part in value[len("viking://agent/") :].strip("/").split("/") if part]
+ value = parts[0] if parts else ""
+ return normalize_peer_id(value)
+
+
+def normalize_peer_selector(
+ peer_id: Optional[str],
+ *,
+ agent_id: Optional[str] = None,
+ agent_uri: Optional[str] = None,
+) -> Optional[str]:
+ """Normalize peer_id with legacy agent_id/agent_uri compatibility."""
+ resolved_peer_id = normalize_peer_id(peer_id)
+ legacy_agent_id = normalize_peer_id(agent_id)
+ legacy_agent_uri_id = peer_id_from_legacy_agent_uri(agent_uri)
+ if legacy_agent_id and legacy_agent_uri_id and legacy_agent_id != legacy_agent_uri_id:
+ raise ValueError("legacy agent_id must match agent_uri")
+ legacy_peer_id = legacy_agent_id or legacy_agent_uri_id
+ if resolved_peer_id and legacy_peer_id:
+ raise ValueError("peer_id cannot be used with legacy agent_id/agent_uri")
+ return resolved_peer_id or legacy_peer_id
+
+
+def safe_peer_id(peer_id: Optional[str]) -> Optional[str]:
+ """Return a usable peer_id, or None for empty/path-like values."""
+ try:
+ return normalize_peer_id(peer_id)
+ except ValueError:
+ return None
diff --git a/openviking/core/retrieval_targets.py b/openviking/core/retrieval_targets.py
index 5cffbb861..9a1305dbc 100644
--- a/openviking/core/retrieval_targets.py
+++ b/openviking/core/retrieval_targets.py
@@ -60,25 +60,32 @@ def default_target_directories(
return []
user_root = canonical_user_root(ctx)
+ legacy_agent_targets = _legacy_agent_targets(ctx.legacy_agent_id, context_type=context_type)
if context_type == ContextType.MEMORY:
if ctx.actor_peer_id:
- return [
- f"{user_root}/memories",
- f"{user_root}/peers/{ctx.actor_peer_id}/memories",
- ]
+ return _dedupe(
+ [
+ f"{user_root}/memories",
+ f"{user_root}/peers/{ctx.actor_peer_id}/memories",
+ *legacy_agent_targets,
+ ]
+ )
return [user_root]
if context_type == ContextType.RESOURCE:
if ctx.actor_peer_id:
- return [
- "viking://resources",
- f"{user_root}/resources",
- f"{user_root}/peers/{ctx.actor_peer_id}/resources",
- ]
+ return _dedupe(
+ [
+ "viking://resources",
+ f"{user_root}/resources",
+ f"{user_root}/peers/{ctx.actor_peer_id}/resources",
+ *legacy_agent_targets,
+ ]
+ )
return ["viking://resources", user_root]
if context_type == ContextType.SKILL:
- return _default_skill_targets(ctx)
+ return _dedupe([*_default_skill_targets(ctx), *legacy_agent_targets])
if ctx.actor_peer_id:
- return ["viking://resources", *_default_user_root_targets(ctx)]
+ return _dedupe(["viking://resources", *_default_user_root_targets(ctx)])
return [user_root, "viking://resources"]
@@ -108,6 +115,10 @@ def _target_directories_for_uri(
if _is_current_user_root(target_uri, ctx):
return _default_user_root_targets(ctx)
+ legacy_agent_target = _resolve_legacy_agent_target(target_uri, ctx=ctx)
+ if legacy_agent_target is not None:
+ return legacy_agent_target
+
peer_target = _resolve_peer_target(target_uri, ctx=ctx)
if peer_target is not None:
return peer_target
@@ -129,6 +140,7 @@ def _default_user_root_targets(ctx: RequestContext) -> List[str]:
f"{user_root}/resources",
*_default_skill_targets(ctx),
*_actor_peer_targets(ctx),
+ *_legacy_agent_targets(ctx.legacy_agent_id),
]
)
@@ -147,6 +159,89 @@ def _actor_peer_targets(ctx: RequestContext) -> List[str]:
]
+def _legacy_agent_targets(
+ agent_id: Optional[str],
+ *,
+ context_type: Optional[ContextType] = None,
+) -> List[str]:
+ if not agent_id:
+ return []
+ agent_root = f"viking://agent/{agent_id}"
+ if context_type == ContextType.MEMORY:
+ return [f"{agent_root}/memories"]
+ if context_type == ContextType.RESOURCE:
+ return [f"{agent_root}/resources"]
+ if context_type == ContextType.SKILL:
+ return [f"{agent_root}/skills"]
+ return [
+ f"{agent_root}/memories",
+ f"{agent_root}/resources",
+ f"{agent_root}/skills",
+ ]
+
+
+def _resolve_legacy_agent_target(
+ target_uri: str,
+ *,
+ ctx: RequestContext,
+) -> Optional[List[str]]:
+ parts = uri_parts(target_uri)
+ if not parts or parts[0] != "agent":
+ return None
+ if len(parts) == 1:
+ agent_id = ctx.legacy_agent_id or ctx.actor_peer_id
+ if not agent_id:
+ return [target_uri]
+ return _legacy_agent_and_migrated_targets(agent_id, ctx)
+
+ agent_id = _normalize_peer_id(parts[1])
+ if ctx.actor_peer_id and agent_id != ctx.actor_peer_id:
+ raise PermissionDeniedError("Actor peer cannot access another legacy agent context.")
+
+ suffix = parts[2:]
+ if not suffix:
+ return _legacy_agent_and_migrated_targets(agent_id, ctx)
+ if suffix[0] == "memories":
+ return _dedupe(
+ [
+ target_uri,
+ _with_suffix(f"{canonical_user_root(ctx)}/peers/{agent_id}/memories", suffix[1:]),
+ ]
+ )
+ if suffix[0] == "resources":
+ return _dedupe(
+ [
+ target_uri,
+ _with_suffix(f"{canonical_user_root(ctx)}/peers/{agent_id}/resources", suffix[1:]),
+ ]
+ )
+ if suffix[0] == "skills":
+ return _dedupe(
+ [
+ target_uri,
+ _with_suffix(f"{canonical_user_root(ctx)}/skills", suffix[1:]),
+ ]
+ )
+ return [target_uri]
+
+
+def _legacy_agent_and_migrated_targets(agent_id: str, ctx: RequestContext) -> List[str]:
+ return _dedupe(
+ [
+ *_legacy_agent_targets(agent_id),
+ f"{canonical_user_root(ctx)}/peers/{agent_id}/memories",
+ f"{canonical_user_root(ctx)}/peers/{agent_id}/resources",
+ *_default_skill_targets(ctx),
+ ]
+ )
+
+
+def _with_suffix(root: str, suffix: List[str]) -> str:
+ if not suffix:
+ return root
+ return f"{root}/{'/'.join(suffix)}"
+
+
def _resolve_peer_target(
target_uri: str,
*,
diff --git a/openviking/server/auth.py b/openviking/server/auth.py
index eca3d3bd9..86316f0e8 100644
--- a/openviking/server/auth.py
+++ b/openviking/server/auth.py
@@ -39,6 +39,7 @@ _API_KEY_ROOT_ALLOWED_PREFIXES = (
"/api/v1/admin",
"/api/v1/observer",
"/api/v1/console",
+ "/api/v1/tasks",
"/api/v1/system/backend",
"/api/v1/system/sync",
)
@@ -275,6 +276,12 @@ async def resolve_identity(
"X-OpenViking-Account or explicit account_id in the URL and "
"X-OpenViking-User or explicit user_id in the URL."
)
+ if configured_root_api_key:
+ return ResolvedIdentity(
+ role=Role.ROOT,
+ account_id=effective_account_id or "trusted",
+ user_id=effective_user_id or "trusted",
+ )
if not effective_account_id and not effective_user_id:
return ResolvedIdentity(
role=Role.ROOT,
diff --git a/openviking/server/identity.py b/openviking/server/identity.py
index cb4753312..c8e3621c7 100644
--- a/openviking/server/identity.py
+++ b/openviking/server/identity.py
@@ -51,6 +51,10 @@ class RequestContext:
# Request-level view filter for the current user's peers collection. This does
# not change tenant/user identity or session ownership.
actor_peer_id: Optional[str] = None
+ # Set only when the request came through the legacy agent_id compatibility
+ # path. Search/find use it to include unmigrated viking://agent data without
+ # making pure actor_peer_id requests read legacy agent scopes by default.
+ legacy_agent_id: Optional[str] = None
# Mirrors ResolvedIdentity.from_oauth. Routes that mint OAuth state
# (OTP issuance, oauth-verify) reject callers with from_oauth=True to
# prevent a stolen access token from laundering itself into a long-lived
diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.py
index a703a9d7a..5776482b6 100644
--- a/openviking/server/routers/admin.py
+++ b/openviking/server/routers/admin.py
@@ -2,6 +2,8 @@
# SPDX-License-Identifier: AGPL-3.0
"""Admin endpoints for OpenViking multi-tenant HTTP Server."""
+import asyncio
+
from fastapi import APIRouter, Depends, Path, Request
from pydantic import BaseModel
@@ -15,8 +17,20 @@ from openviking.server.config import ServerConfig
from openviking.server.dependencies import get_service
from openviking.server.identity import RequestContext, Role
from openviking.server.models import Response
+from openviking.service.legacy_migration import LegacyDataMigration
+from openviking.service.task_store import (
+ SYSTEM_TASK_ACCOUNT_ID,
+ SYSTEM_TASK_USER_ID,
+)
+from openviking.service.task_tracker import (
+ get_task_tracker,
+)
from openviking.storage.viking_fs import get_viking_fs
-from openviking_cli.exceptions import InvalidArgumentError, PermissionDeniedError
+from openviking_cli.exceptions import (
+ FailedPreconditionError,
+ InvalidArgumentError,
+ PermissionDeniedError,
+)
from openviking_cli.session.user_id import UserIdentifier
from openviking_cli.utils.logger import get_logger
@@ -39,6 +53,10 @@ class SetRoleRequest(BaseModel):
role: str
+class MigrateLegacyDataRequest(BaseModel):
+ action: str = "migrate"
+
+
def _get_api_key_manager(request: Request):
"""Get APIKeyManager from app state."""
return get_api_key_manager_or_raise(request)
@@ -77,6 +95,28 @@ def _validate_register_user_role(ctx: RequestContext, role: str) -> Role:
return resolved_role
+async def _run_legacy_migration_task(
+ task_id: str,
+ migration: LegacyDataMigration,
+ *,
+ action: str,
+ account_id: str,
+ user_id: str,
+) -> None:
+ tracker = get_task_tracker()
+ await tracker.start(task_id, account_id=account_id, user_id=user_id, stage="running")
+ try:
+ if action == "cleanup":
+ result = await migration.cleanup()
+ else:
+ result = await migration.run()
+ except Exception as exc:
+ await tracker.fail(task_id, str(exc), account_id=account_id, user_id=user_id)
+ logger.exception("Legacy %s task %s failed", action, task_id)
+ return
+ await tracker.complete(task_id, result, account_id=account_id, user_id=user_id)
+
+
# ---- Account endpoints ----
@@ -121,6 +161,56 @@ async def list_accounts(
return Response(status="ok", result=accounts)
[email protected]("/migrate")
+@require_auth_root
+async def migrate_legacy_data(
+ request: Request,
+ body: MigrateLegacyDataRequest | None = None,
+ ctx: RequestContext = Depends(get_request_context),
+):
+ """Preflight and enqueue legacy agent/session data migration or cleanup."""
+ manager = _get_api_key_manager(request)
+ service = get_service()
+ if service.viking_fs is None:
+ raise FailedPreconditionError("OpenViking service is not initialized.")
+ action = (body.action if body else "migrate").strip().lower()
+ if action not in {"migrate", "cleanup"}:
+ raise InvalidArgumentError("Migration action must be 'migrate' or 'cleanup'.")
+
+ migration = LegacyDataMigration(
+ viking_fs=service.viking_fs,
+ api_key_manager=manager,
+ service=service,
+ )
+ if action == "migrate":
+ plan = await migration.preflight()
+ if plan.errors:
+ raise FailedPreconditionError(
+ "Legacy migration preflight failed.",
+ details=plan.to_preflight_result(),
+ )
+
+ tracker = get_task_tracker()
+ task_type = "legacy_cleanup" if action == "cleanup" else "legacy_migration"
+ resource_id = "legacy-data-cleanup" if action == "cleanup" else "legacy-data"
+ task = await tracker.create(
+ task_type,
+ resource_id=resource_id,
+ account_id=SYSTEM_TASK_ACCOUNT_ID,
+ user_id=SYSTEM_TASK_USER_ID,
+ )
+ asyncio.create_task(
+ _run_legacy_migration_task(
+ task.task_id,
+ migration,
+ action=action,
+ account_id=SYSTEM_TASK_ACCOUNT_ID,
+ user_id=SYSTEM_TASK_USER_ID,
+ )
+ )
+ return Response(status="ok", result={"task_id": task.task_id})
+
+
@router.delete("/accounts/{account_id}")
@require_auth_root
async def delete_account(
diff --git a/openviking/server/routers/search.py b/openviking/server/routers/search.py
index bb3f9f05e..442c287ab 100644
--- a/openviking/server/routers/search.py
+++ b/openviking/server/routers/search.py
@@ -3,12 +3,14 @@
"""Search endpoints for OpenViking HTTP Server."""
import math
+from dataclasses import replace
from typing import Any, Dict, List, Literal, Optional, Union
from fastapi import APIRouter, Depends
-from pydantic import BaseModel, ConfigDict
+from pydantic import BaseModel, ConfigDict, model_validator
from openviking.core.path_variables import resolve_path_variables
+from openviking.core.peer_id import normalize_peer_selector
from openviking.pyagfs.exceptions import AGFSClientError, AGFSNotFoundError
from openviking.server.auth import get_request_context
from openviking.server.dependencies import get_service
@@ -72,6 +74,21 @@ def _resolve_uri_or_uris(uri: Union[str, List[str]]) -> Union[str, List[str]]:
return resolve_path_variables(uri)
+def _ctx_with_legacy_actor_peer(
+ ctx: RequestContext,
+ legacy_peer_id: Optional[str],
+) -> RequestContext:
+ if legacy_peer_id is None:
+ return ctx
+ if ctx.actor_peer_id and ctx.actor_peer_id != legacy_peer_id:
+ raise InvalidArgumentError(
+ "actor_peer_id cannot be used with a different legacy agent_id/agent_uri"
+ )
+ if ctx.actor_peer_id == legacy_peer_id and ctx.legacy_agent_id == legacy_peer_id:
+ return ctx
+ return replace(ctx, actor_peer_id=legacy_peer_id, legacy_agent_id=legacy_peer_id)
+
+
class FindRequest(BaseModel):
"""Request model for find."""
@@ -80,6 +97,8 @@ class FindRequest(BaseModel):
query: str
target_uri: Union[str, List[str]] = ""
context_type: Optional[Union[str, List[str]]] = None
+ agent_id: Optional[str] = None
+ agent_uri: Optional[str] = None
limit: int = 10
node_limit: Optional[int] = None
score_threshold: Optional[float] = None
@@ -91,6 +110,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.agent_id = normalize_peer_selector(
+ None,
+ agent_id=self.agent_id,
+ agent_uri=self.agent_uri,
+ )
+ return self
+
class SearchRequest(BaseModel):
"""Request model for search with session."""
@@ -100,6 +128,8 @@ class SearchRequest(BaseModel):
query: str
target_uri: Union[str, List[str]] = ""
context_type: Optional[Union[str, List[str]]] = None
+ agent_id: Optional[str] = None
+ agent_uri: Optional[str] = None
session_id: Optional[str] = None
limit: int = 10
node_limit: Optional[int] = None
@@ -113,6 +143,15 @@ 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.agent_id = normalize_peer_selector(
+ None,
+ agent_id=self.agent_id,
+ agent_uri=self.agent_uri,
+ )
+ return self
+
class GrepRequest(BaseModel):
"""Request model for grep."""
@@ -140,6 +179,7 @@ async def find(
):
"""Semantic search without session context."""
service = get_service()
+ ctx = _ctx_with_legacy_actor_peer(_ctx, request.agent_id)
actual_limit = _resolve_search_limit(request.limit, request.node_limit)
effective_filter = _resolve_search_filter(
request.filter,
@@ -154,7 +194,7 @@ async def find(
telemetry=request.telemetry,
fn=lambda: service.search.find(
query=request.query,
- ctx=_ctx,
+ ctx=ctx,
target_uri=resolved_target_uri,
limit=actual_limit,
score_threshold=request.score_threshold,
@@ -180,6 +220,7 @@ async def search(
):
"""Semantic search with optional session context."""
service = get_service()
+ ctx = _ctx_with_legacy_actor_peer(_ctx, request.agent_id)
actual_limit = _resolve_search_limit(request.limit, request.node_limit)
effective_filter = _resolve_search_filter(
request.filter,
@@ -193,11 +234,11 @@ async def search(
async def _search():
session = None
if request.session_id:
- session = service.sessions.session(_ctx, request.session_id)
+ session = service.sessions.session(ctx, request.session_id)
await session.load()
return await service.search.search(
query=request.query,
- ctx=_ctx,
+ ctx=ctx,
target_uri=resolved_target_uri,
session=session,
limit=actual_limit,
diff --git a/openviking/server/routers/sessions.py b/openviking/server/routers/sessions.py
index 1a06c563e..3bdf554e4 100644
--- a/openviking/server/routers/sessions.py
+++ b/openviking/server/routers/sessions.py
@@ -8,7 +8,7 @@ from fastapi import APIRouter, Body, Depends, Path, Query, Request
from pydantic import BaseModel, Field, model_validator
from openviking.core.path_variables import resolve_path_variables
-from openviking.core.peer_id import normalize_peer_id
+from openviking.core.peer_id import normalize_peer_selector
from openviking.message.part import Part, TextPart, part_from_dict
from openviking.server.auth import get_request_context
from openviking.server.dependencies import get_service
@@ -85,6 +85,8 @@ class AddMessageRequest(BaseModel):
role: str
peer_id: Optional[str] = None
+ agent_id: Optional[str] = None
+ agent_uri: Optional[str] = None
content: Optional[str] = None
parts: Optional[List[Dict[str, Any]]] = None
created_at: Optional[str] = None
@@ -94,7 +96,11 @@ class AddMessageRequest(BaseModel):
def validate_content_or_parts(self) -> "AddMessageRequest":
if self.content is None and self.parts is None:
raise ValueError("Either 'content' or 'parts' must be provided")
- self.peer_id = normalize_peer_id(self.peer_id)
+ self.peer_id = normalize_peer_selector(
+ self.peer_id,
+ agent_id=self.agent_id,
+ agent_uri=self.agent_uri,
+ )
return self
diff --git a/openviking/server/routers/tasks.py b/openviking/server/routers/tasks.py
index e197c62c0..adfc292d1 100644
--- a/openviking/server/routers/tasks.py
+++ b/openviking/server/routers/tasks.py
@@ -12,8 +12,9 @@ from typing import Optional
from fastapi import APIRouter, Depends, Query
from openviking.server.auth import get_request_context
-from openviking.server.identity import RequestContext
+from openviking.server.identity import RequestContext, Role
from openviking.server.models import Response
+from openviking.service.task_store import SYSTEM_TASK_ACCOUNT_ID, SYSTEM_TASK_USER_ID
from openviking.service.task_tracker import get_task_tracker
from openviking_cli.exceptions import OpenVikingError
@@ -27,11 +28,20 @@ async def get_task(
):
"""Get the status of a single background task."""
tracker = get_task_tracker()
- task = await tracker.get(
- task_id,
- account_id=_ctx.account_id,
- user_id=_ctx.user.user_id,
- )
+ if _ctx.role == Role.ROOT:
+ task = await tracker.get(task_id)
+ if task is None:
+ task = await tracker.get(
+ task_id,
+ account_id=SYSTEM_TASK_ACCOUNT_ID,
+ user_id=SYSTEM_TASK_USER_ID,
+ )
+ else:
+ task = await tracker.get(
+ task_id,
+ account_id=_ctx.account_id,
+ user_id=_ctx.user.user_id,
+ )
if not task:
raise OpenVikingError(
"Task not found or expired",
@@ -53,12 +63,31 @@ async def list_tasks(
):
"""List background tasks with optional filters."""
tracker = get_task_tracker()
- tasks = await tracker.list_tasks(
- task_type=task_type,
- status=status,
- resource_id=resource_id,
- limit=limit,
- account_id=_ctx.account_id,
- user_id=_ctx.user.user_id,
- )
+ if _ctx.role == Role.ROOT:
+ system_tasks = await tracker.list_tasks(
+ task_type=task_type,
+ status=status,
+ resource_id=resource_id,
+ limit=limit,
+ account_id=SYSTEM_TASK_ACCOUNT_ID,
+ user_id=SYSTEM_TASK_USER_ID,
+ )
+ cached_tasks = await tracker.list_tasks(
+ task_type=task_type,
+ status=status,
+ resource_id=resource_id,
+ limit=limit,
+ )
+ tasks_by_id = {task.task_id: task for task in cached_tasks}
+ tasks_by_id.update({task.task_id: task for task in system_tasks})
+ tasks = sorted(tasks_by_id.values(), key=lambda task: task.created_at, reverse=True)[:limit]
+ else:
+ tasks = await tracker.list_tasks(
+ task_type=task_type,
+ status=status,
+ resource_id=resource_id,
+ limit=limit,
+ account_id=_ctx.account_id,
+ user_id=_ctx.user.user_id,
+ )
return Response(status="ok", result=[t.to_dict() for t in tasks])
diff --git a/openviking/service/legacy_migration.py b/openviking/service/legacy_migration.py
new file mode 100644
index 000000000..7350dac6e
--- /dev/null
+++ b/openviking/service/legacy_migration.py
@@ -0,0 +1,781 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Legacy agent/session data migration to user-owned namespaces."""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, field
+from typing import Any
+
+from openviking.pyagfs import AsyncAGFSClient
+from openviking.server.identity import RequestContext, Role
+from openviking.storage.vector_migration import (
+ VectorMigrationResult,
+ copy_vector_records,
+ delete_vector_records,
+)
+from openviking.storage.viking_fs import VikingFS
+from openviking_cli.exceptions import FailedPreconditionError
+from openviking_cli.session.user_id import UserIdentifier, validate_user_id
+
+
+@dataclass(frozen=True)
+class TreeCopy:
+ source_path: str
+ target_path: str
+ category: str
+ source_uri: str
+ target_uri: str
+ skip_tree_if_target_exists: bool = False
+ copy_contents: bool = False
+
+
+@dataclass(frozen=True)
+class LegacyCleanupTarget:
+ account_id: str
+ source_path: str
+ source_uri: str
+ category: str
+
+
+@dataclass
+class MigrationPlan:
+ account_users: dict[str, set[str]] = field(default_factory=dict)
+ created_users: set[tuple[str, str]] = field(default_factory=set)
+ operations: list[TreeCopy] = field(default_factory=list)
+ warnings: list[str] = field(default_factory=list)
+ skipped: list[dict[str, Any]] = field(default_factory=list)
+ errors: list[dict[str, Any]] = field(default_factory=list)
+
+ def to_preflight_result(self) -> dict[str, Any]:
+ return {
+ "errors": list(self.errors),
+ "warnings": list(self.warnings),
+ "skipped": list(self.skipped),
+ "created_users": [
+ {"account_id": account_id, "user_id": user_id}
+ for account_id, user_id in sorted(self.created_users)
+ ],
+ "operation_count": len(self.operations),
+ }
+
+
+@dataclass
+class LegacyCleanupPlan:
+ targets: list[LegacyCleanupTarget] = field(default_factory=list)
+
+
+@dataclass(frozen=True)
+class VectorCopyScope:
+ source_uri: str
+ target_uri: str
+ recursive: bool
+
+
+@dataclass
+class CopyResult:
+ copied: bool = False
+ vector_scopes: list[VectorCopyScope] = field(default_factory=list)
+
+ def extend(self, other: "CopyResult") -> None:
+ self.copied = self.copied or other.copied
+ self.vector_scopes.extend(other.vector_scopes)
+
+
+@dataclass
+class MigrationResult:
+ files: int = 0
+ directories: int = 0
+ vector_records: int = 0
+ skipped_vector_records: int = 0
+ operations: dict[str, int] = field(default_factory=dict)
+ skipped: list[dict[str, Any]] = field(default_factory=list)
+ warnings: list[str] = field(default_factory=list)
+ created_users: list[dict[str, Any]] = field(default_factory=list)
+
+ def mark_operation(self, category: str) -> None:
+ self.operations[category] = self.operations.get(category, 0) + 1
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "migrated": {
+ "files": self.files,
+ "directories": self.directories,
+ "vector_records": self.vector_records,
+ "skipped_vector_records": self.skipped_vector_records,
+ "operations": dict(sorted(self.operations.items())),
+ },
+ "skipped": self.skipped,
+ "warnings": self.warnings,
+ "created_users": self.created_users,
+ }
+
+
+@dataclass
+class LegacyCleanupResult:
+ vector_records: int = 0
+ removed: list[dict[str, Any]] = field(default_factory=list)
+ skipped: list[dict[str, Any]] = field(default_factory=list)
+ warnings: list[str] = field(default_factory=list)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "cleanup": {
+ "directories": len(self.removed),
+ "vector_records": self.vector_records,
+ "targets": self.removed,
+ },
+ "skipped": self.skipped,
+ "warnings": self.warnings,
+ }
+
+
+def target_to_dict(target: LegacyCleanupTarget) -> dict[str, str]:
+ return {
+ "account_id": target.account_id,
+ "type": target.category,
+ "source": target.source_uri,
+ }
+
+
+class LegacyDataMigration:
+ """Plan and execute legacy agent/session migration."""
+
+ def __init__(self, *, viking_fs: VikingFS, api_key_manager: Any, service: Any):
+ if api_key_manager is None:
+ raise FailedPreconditionError("Admin migration requires an API key user registry.")
+ self._viking_fs = viking_fs
+ self._agfs = AsyncAGFSClient(viking_fs.agfs)
+ self._api_key_manager = api_key_manager
+ self._service = service
+
+ async def preflight(self) -> MigrationPlan:
+ plan = MigrationPlan()
+ registry_accounts = self._registry_account_ids()
+ physical_accounts = await self._physical_account_ids()
+ for account_id in sorted(physical_accounts - registry_accounts):
+ if await self._account_has_legacy_data(account_id):
+ plan.errors.append(
+ {
+ "account_id": account_id,
+ "reason": (
+ "legacy data exists under an account missing from the user registry"
+ ),
+ }
+ )
+
+ for account_id in sorted(registry_accounts):
+ plan.account_users[account_id] = set()
+ for user_id in sorted(self._registry_user_ids(account_id)):
+ self._ensure_plan_user(account_id, user_id, plan)
+ if await self._account_has_legacy_data(account_id):
+ for user_id in sorted(await self._physical_user_ids(account_id)):
+ self._ensure_plan_user(account_id, user_id, plan)
+ await self._plan_user_agent_data(account_id, plan)
+ await self._plan_agent_user_data(account_id, plan)
+ await self._plan_sessions(account_id, plan)
+ await self._plan_shared_agent_data(account_id, plan)
+ return plan
+
+ async def run(self) -> dict[str, Any]:
+ plan = await self.preflight()
+ if plan.errors:
+ raise FailedPreconditionError(
+ "Legacy migration preflight failed.",
+ details=plan.to_preflight_result(),
+ )
+
+ result = MigrationResult(
+ skipped=list(plan.skipped),
+ warnings=list(plan.warnings),
+ )
+ for account_id, user_id in sorted(plan.created_users):
+ if self._has_user(account_id, user_id):
+ continue
+ await self._api_key_manager.register_user(account_id, user_id, "user")
+ user_ctx = RequestContext(user=UserIdentifier(account_id, user_id), role=Role.USER)
+ await self._service.initialize_user_directories(user_ctx)
+ result.created_users.append({"account_id": account_id, "user_id": user_id})
+
+ for operation in plan.operations:
+ copied = await self._copy_tree(operation, result)
+ if copied.copied:
+ result.mark_operation(operation.category)
+ await self._copy_vectors(operation, copied, result)
+ return result.to_dict()
+
+ async def cleanup_preflight(self) -> LegacyCleanupPlan:
+ plan = LegacyCleanupPlan()
+ for account_id in sorted(await self._physical_account_ids()):
+ agent_path = f"/local/{account_id}/agent"
+ if await self._exists(agent_path):
+ plan.targets.append(self._cleanup_target(account_id, agent_path, "agent"))
+
+ session_path = f"/local/{account_id}/session"
+ if await self._exists(session_path):
+ plan.targets.append(self._cleanup_target(account_id, session_path, "session"))
+
+ user_root = f"/local/{account_id}/user"
+ for user_entry in await self._ls(user_root):
+ if not user_entry["is_dir"]:
+ continue
+ user_agent_path = f"{user_root}/{user_entry['name']}/agent"
+ if await self._exists(user_agent_path):
+ plan.targets.append(
+ self._cleanup_target(account_id, user_agent_path, "user_agent")
+ )
+ return plan
+
+ async def cleanup(self) -> dict[str, Any]:
+ plan = await self.cleanup_preflight()
+ result = LegacyCleanupResult()
+ for target in plan.targets:
+ if not await self._exists(target.source_path):
+ skipped = target_to_dict(target)
+ skipped["reason"] = "missing"
+ result.skipped.append(skipped)
+ continue
+ vector_result = await self._delete_vectors(target)
+ result.vector_records += vector_result.deleted
+ result.warnings.extend(vector_result.warnings)
+ if vector_result.failed:
+ skipped = target_to_dict(target)
+ skipped["reason"] = "vector cleanup failed"
+ result.skipped.append(skipped)
+ continue
+ await self._agfs.rm(target.source_path, recursive=True)
+ result.removed.append(target_to_dict(target))
+ return result.to_dict()
+
+ def _registry_account_ids(self) -> set[str]:
+ return {
+ str(item.get("account_id", ""))
+ for item in self._api_key_manager.get_accounts()
+ if item.get("account_id")
+ }
+
+ def _registry_user_ids(self, account_id: str) -> set[str]:
+ users = self._api_key_manager.get_users(
+ account_id,
+ limit=1_000_000,
+ expose_key=False,
+ )
+ return {str(item.get("user_id", "")) for item in users if item.get("user_id")}
+
+ def _has_user(self, account_id: str, user_id: str) -> bool:
+ has_user = getattr(self._api_key_manager, "has_user", None)
+ if callable(has_user):
+ return bool(has_user(account_id, user_id))
+ return user_id in self._registry_user_ids(account_id)
+
+ async def _physical_account_ids(self) -> set[str]:
+ entries = await self._ls("/local")
+ return {
+ entry["name"] for entry in entries if entry["is_dir"] and entry["name"] != "_system"
+ }
+
+ async def _physical_user_ids(self, account_id: str) -> set[str]:
+ entries = await self._ls(f"/local/{account_id}/user")
+ return {entry["name"] for entry in entries if entry["is_dir"]}
+
+ async def _account_has_legacy_data(self, account_id: str) -> bool:
+ for leaf in ("agent", "session"):
+ if await self._exists(f"/local/{account_id}/{leaf}"):
+ return True
+ user_root = f"/local/{account_id}/user"
+ for user_entry in await self._ls(user_root):
+ agent_root = f"{user_root}/{user_entry['name']}/agent"
+ if user_entry["is_dir"] and await self._exists(agent_root):
+ return True
+ return False
+
+ async def _plan_sessions(self, account_id: str, plan: MigrationPlan) -> None:
+ session_root = f"/local/{account_id}/session"
+ for entry in await self._ls(session_root):
+ if not entry["is_dir"]:
+ continue
+ source_path = f"{session_root}/{entry['name']}"
+ if await self._looks_like_session_dir(source_path):
+ await self._plan_one_session(
+ account_id,
+ session_id=entry["name"],
+ source_path=source_path,
+ owner_hint=None,
+ plan=plan,
+ )
+ continue
+ for nested in await self._ls(source_path):
+ if not nested["is_dir"]:
+ continue
+ nested_path = f"{source_path}/{nested['name']}"
+ if await self._looks_like_session_dir(nested_path):
+ await self._plan_one_session(
+ account_id,
+ session_id=nested["name"],
+ source_path=nested_path,
+ owner_hint=entry["name"],
+ plan=plan,
+ )
+
+ async def _plan_one_session(
+ self,
+ account_id: str,
+ *,
+ session_id: str,
+ source_path: str,
+ owner_hint: str | None,
+ plan: MigrationPlan,
+ ) -> None:
+ owner = await self._session_owner(source_path)
+ if not owner and owner_hint:
+ owner = owner_hint
+ users = plan.account_users.setdefault(account_id, set())
+ if not owner and len(users) == 1:
+ owner = next(iter(users))
+ if not owner:
+ plan.errors.append(
+ {
+ "account_id": account_id,
+ "session_id": session_id,
+ "source": self._path_to_uri(account_id, source_path),
+ "reason": "session owner cannot be inferred in a multi-user account",
+ }
+ )
+ return
+ if validate_user_id(owner):
+ plan.errors.append(
+ {
+ "account_id": account_id,
+ "session_id": session_id,
+ "user_id": owner,
+ "reason": "session owner user_id is invalid",
+ }
+ )
+ return
+ self._ensure_plan_user(account_id, owner, plan)
+ target_path = f"/local/{account_id}/user/{owner}/sessions/{session_id}"
+ plan.operations.append(
+ TreeCopy(
+ source_path=source_path,
+ target_path=target_path,
+ category="sessions",
+ source_uri=self._path_to_uri(account_id, source_path),
+ target_uri=f"viking://user/{owner}/sessions/{session_id}",
+ skip_tree_if_target_exists=False,
+ )
+ )
+
+ async def _session_owner(self, source_path: str) -> str:
+ data = await self._read_json_file(f"{source_path}/.meta.json")
+ if not isinstance(data, dict):
+ return ""
+ for key in (
+ "created_by_user_id",
+ "user_id",
+ "owner_user_id",
+ "created_by",
+ ):
+ value = data.get(key)
+ if isinstance(value, str) and value.strip():
+ return value.strip()
+ return ""
+
+ async def _looks_like_session_dir(self, path: str) -> bool:
+ for leaf in (".meta.json", "messages.jsonl", "history", "tool-results", "tools"):
+ if await self._exists(f"{path}/{leaf}"):
+ return True
+ return False
+
+ async def _plan_user_agent_data(self, account_id: str, plan: MigrationPlan) -> None:
+ user_root = f"/local/{account_id}/user"
+ for user_entry in await self._ls(user_root):
+ if not user_entry["is_dir"]:
+ continue
+ user_id = user_entry["name"]
+ agent_root = f"{user_root}/{user_id}/agent"
+ if not await self._exists(agent_root):
+ continue
+ if not self._ensure_plan_user(account_id, user_id, plan):
+ continue
+ for agent_entry in await self._ls(agent_root):
+ if agent_entry["is_dir"]:
+ await self._plan_agent_tree(
+ account_id,
+ agent_id=agent_entry["name"],
+ source_agent_path=f"{agent_root}/{agent_entry['name']}",
+ user_ids=[user_id],
+ plan=plan,
+ )
+
+ async def _plan_agent_user_data(self, account_id: str, plan: MigrationPlan) -> None:
+ agent_root = f"/local/{account_id}/agent"
+ for agent_entry in await self._ls(agent_root):
+ if not agent_entry["is_dir"]:
+ continue
+ agent_id = agent_entry["name"]
+ user_root = f"{agent_root}/{agent_id}/user"
+ for user_entry in await self._ls(user_root):
+ if not user_entry["is_dir"]:
+ continue
+ user_id = user_entry["name"]
+ if not self._ensure_plan_user(account_id, user_id, plan):
+ continue
+ await self._plan_agent_tree(
+ account_id,
+ agent_id=agent_id,
+ source_agent_path=f"{user_root}/{user_id}",
+ user_ids=[user_id],
+ plan=plan,
+ )
+
+ async def _plan_shared_agent_data(self, account_id: str, plan: MigrationPlan) -> None:
+ agent_root = f"/local/{account_id}/agent"
+ user_ids = sorted(plan.account_users.setdefault(account_id, set()))
+ for agent_entry in await self._ls(agent_root):
+ if not agent_entry["is_dir"]:
+ continue
+ agent_id = agent_entry["name"]
+ source_agent_path = f"{agent_root}/{agent_id}"
+ if not user_ids:
+ plan.warnings.append(
+ f"Skipped shared legacy agent {agent_id!r} "
+ f"in account {account_id!r}: no users exist."
+ )
+ continue
+ await self._plan_agent_tree(
+ account_id,
+ agent_id=agent_id,
+ source_agent_path=source_agent_path,
+ user_ids=user_ids,
+ plan=plan,
+ )
+
+ async def _plan_agent_tree(
+ self,
+ account_id: str,
+ *,
+ agent_id: str,
+ source_agent_path: str,
+ user_ids: list[str],
+ plan: MigrationPlan,
+ ) -> None:
+ memories_path = f"{source_agent_path}/memories"
+ if await self._exists(memories_path):
+ for user_id in user_ids:
+ plan.operations.append(
+ TreeCopy(
+ source_path=memories_path,
+ target_path=f"/local/{account_id}/user/{user_id}/peers/{agent_id}/memories",
+ category="agent_memories",
+ source_uri=self._path_to_uri(account_id, memories_path),
+ target_uri=f"viking://user/{user_id}/peers/{agent_id}/memories",
+ copy_contents=True,
+ )
+ )
+
+ skills_path = f"{source_agent_path}/skills"
+ if await self._exists(skills_path):
+ await self._plan_agent_skills(account_id, agent_id, skills_path, user_ids, plan)
+
+ instructions_path = f"{source_agent_path}/instructions"
+ if await self._exists(instructions_path):
+ plan.warnings.append(
+ f"Skipped legacy instructions for agent {agent_id!r} in account {account_id!r}."
+ )
+
+ async def _plan_agent_skills(
+ self,
+ account_id: str,
+ agent_id: str,
+ skills_path: str,
+ user_ids: list[str],
+ plan: MigrationPlan,
+ ) -> None:
+ for skill_entry in await self._ls(skills_path):
+ if not skill_entry["is_dir"]:
+ continue
+ skill_name = skill_entry["name"]
+ source_skill_path = f"{skills_path}/{skill_name}"
+ for user_id in user_ids:
+ target_skill_path = f"/local/{account_id}/user/{user_id}/skills/{skill_name}"
+ if await self._exists(target_skill_path):
+ plan.skipped.append(
+ {
+ "type": "skill",
+ "source": self._path_to_uri(account_id, source_skill_path),
+ "target": f"viking://user/{user_id}/skills/{skill_name}",
+ "reason": "target skill already exists",
+ }
+ )
+ continue
+ plan.operations.append(
+ TreeCopy(
+ source_path=source_skill_path,
+ target_path=target_skill_path,
+ category="agent_skills",
+ source_uri=self._path_to_uri(account_id, source_skill_path),
+ target_uri=f"viking://user/{user_id}/skills/{skill_name}",
+ skip_tree_if_target_exists=True,
+ )
+ )
+ if not await self._ls(skills_path):
+ plan.warnings.append(
+ f"Legacy skills directory for agent {agent_id!r} "
+ f"in account {account_id!r} is empty."
+ )
+
+ def _ensure_plan_user(self, account_id: str, user_id: str, plan: MigrationPlan) -> bool:
+ if error := validate_user_id(user_id):
+ detail = {
+ "account_id": account_id,
+ "user_id": user_id,
+ "reason": f"user_id is invalid: {error}",
+ }
+ if detail not in plan.errors:
+ plan.errors.append(detail)
+ return False
+ users = plan.account_users.setdefault(account_id, set())
+ if user_id in users:
+ return True
+ users.add(user_id)
+ if not self._has_user(account_id, user_id):
+ plan.created_users.add((account_id, user_id))
+ return True
+
+ def _cleanup_target(
+ self,
+ account_id: str,
+ source_path: str,
+ category: str,
+ ) -> LegacyCleanupTarget:
+ return LegacyCleanupTarget(
+ account_id=account_id,
+ source_path=source_path,
+ source_uri=self._path_to_uri(account_id, source_path),
+ category=category,
+ )
+
+ async def _copy_tree(self, operation: TreeCopy, result: MigrationResult) -> CopyResult:
+ if operation.skip_tree_if_target_exists and await self._exists(operation.target_path):
+ result.skipped.append(
+ {
+ "type": operation.category,
+ "source": operation.source_uri,
+ "target": operation.target_uri,
+ "reason": "target already exists; kept existing target",
+ }
+ )
+ return CopyResult()
+ account_id = self._account_id_from_path(operation.source_path)
+ if operation.copy_contents:
+ copied = CopyResult()
+ created_root = await self._mkdir_if_missing(operation.target_path)
+ for entry in await self._ls(operation.source_path):
+ source = f"{operation.source_path}/{entry['name']}"
+ target = f"{operation.target_path}/{entry['name']}"
+ child_result = await self._copy_path(
+ source,
+ target,
+ result,
+ account_id=account_id,
+ collect_vectors=not created_root,
+ )
+ copied.extend(child_result)
+ if created_root and copied.copied:
+ copied.vector_scopes.append(
+ VectorCopyScope(
+ source_uri=operation.source_uri,
+ target_uri=operation.target_uri,
+ recursive=True,
+ )
+ )
+ return copied
+ return await self._copy_path(
+ operation.source_path,
+ operation.target_path,
+ result,
+ account_id=account_id,
+ collect_vectors=True,
+ )
+
+ async def _copy_path(
+ self,
+ source_path: str,
+ target_path: str,
+ result: MigrationResult,
+ *,
+ account_id: str,
+ collect_vectors: bool,
+ ) -> CopyResult:
+ stat = await self._stat(source_path)
+ if not stat:
+ result.skipped.append(
+ {"type": "path", "source": source_path, "target": target_path, "reason": "missing"}
+ )
+ return CopyResult()
+ if stat["is_dir"]:
+ created = await self._mkdir_if_missing(target_path)
+ copied = CopyResult(copied=created)
+ if created:
+ result.directories += 1
+ for entry in await self._ls(source_path):
+ source = f"{source_path}/{entry['name']}"
+ target = f"{target_path}/{entry['name']}"
+ child_result = await self._copy_path(
+ source,
+ target,
+ result,
+ account_id=account_id,
+ collect_vectors=collect_vectors and not created,
+ )
+ copied.extend(child_result)
+ if collect_vectors and created and copied.copied:
+ copied.vector_scopes.append(
+ VectorCopyScope(
+ source_uri=self._path_to_uri(account_id, source_path),
+ target_uri=self._path_to_uri(account_id, target_path),
+ recursive=True,
+ )
+ )
+ return copied
+ if await self._exists(target_path):
+ result.skipped.append(
+ {
+ "type": "file",
+ "source": source_path,
+ "target": target_path,
+ "reason": "target already exists; kept existing target",
+ }
+ )
+ return CopyResult()
+ await self._ensure_parent_dirs(target_path)
+ await self._agfs.write(target_path, await self._agfs.read(source_path))
+ result.files += 1
+ copied = CopyResult(copied=True)
+ if collect_vectors:
+ copied.vector_scopes.append(
+ VectorCopyScope(
+ source_uri=self._path_to_uri(account_id, source_path),
+ target_uri=self._path_to_uri(account_id, target_path),
+ recursive=False,
+ )
+ )
+ return copied
+
+ async def _read_json_file(self, path: str) -> Any:
+ try:
+ raw = await self._agfs.read(path)
+ except Exception:
+ return None
+ if isinstance(raw, bytes):
+ text = raw.decode("utf-8")
+ elif hasattr(raw, "content"):
+ text = raw.content.decode("utf-8")
+ else:
+ text = str(raw)
+ try:
+ return json.loads(text)
+ except json.JSONDecodeError:
+ return None
+
+ async def _copy_vectors(
+ self,
+ operation: TreeCopy,
+ copied: CopyResult,
+ result: MigrationResult,
+ ) -> None:
+ if operation.category == "sessions" or not copied.vector_scopes:
+ return
+ vector_store = getattr(self._service, "vikingdb_manager", None)
+ account_id = self._account_id_from_path(operation.source_path)
+ vector_result = VectorMigrationResult()
+ seen: set[tuple[str, str, bool]] = set()
+ for scope in copied.vector_scopes:
+ key = (scope.source_uri, scope.target_uri, scope.recursive)
+ if key in seen:
+ continue
+ seen.add(key)
+ vector_result.extend(
+ await copy_vector_records(
+ vector_store,
+ account_id=account_id,
+ source_uri=scope.source_uri,
+ target_uri=scope.target_uri,
+ recursive=scope.recursive,
+ )
+ )
+ result.vector_records += vector_result.copied
+ result.skipped_vector_records += vector_result.skipped
+ result.warnings.extend(vector_result.warnings)
+
+ async def _delete_vectors(self, target: LegacyCleanupTarget) -> VectorMigrationResult:
+ vector_store = getattr(self._service, "vikingdb_manager", None)
+ return await delete_vector_records(
+ vector_store,
+ account_id=target.account_id,
+ uri=target.source_uri,
+ recursive=True,
+ )
+
+ async def _ls(self, path: str) -> list[dict[str, Any]]:
+ try:
+ entries = await self._agfs.ls(path)
+ except Exception:
+ return []
+ normalized = []
+ for entry in entries:
+ name = entry.get("name", "")
+ if not name or name in {".", ".."}:
+ continue
+ normalized.append(
+ {
+ "name": name,
+ "is_dir": bool(entry.get("isDir", entry.get("is_dir", False))),
+ }
+ )
+ return normalized
+
+ async def _stat(self, path: str) -> dict[str, Any] | None:
+ try:
+ stat = await self._agfs.stat(path)
+ except Exception:
+ return None
+ return {"is_dir": bool(stat.get("isDir", stat.get("is_dir", False)))}
+
+ async def _exists(self, path: str) -> bool:
+ return await self._stat(path) is not None
+
+ async def _mkdir_if_missing(self, path: str) -> bool:
+ if await self._exists(path):
+ return False
+ await self._ensure_parent_dirs(path)
+ try:
+ await self._agfs.mkdir(path)
+ return True
+ except Exception as exc:
+ if "exist" in str(exc).lower() or "already" in str(exc).lower():
+ return False
+ raise
+
+ async def _ensure_parent_dirs(self, path: str) -> None:
+ parent = path.rsplit("/", 1)[0]
+ if not parent or parent == path:
+ return
+ parts = [part for part in parent.strip("/").split("/") if part]
+ current = ""
+ for part in parts:
+ current = f"{current}/{part}" if current else f"/{part}"
+ await self._mkdir_if_missing(current)
+
+ def _path_to_uri(self, account_id: str, path: str) -> str:
+ prefix = f"/local/{account_id}/"
+ if path.startswith(prefix):
+ return "viking://" + path[len(prefix) :].strip("/")
+ return path
+
+ def _account_id_from_path(self, path: str) -> str:
+ parts = [part for part in path.strip("/").split("/") if part]
+ if len(parts) >= 2 and parts[0] == "local":
+ return parts[1]
+ return ""
diff --git a/openviking/service/session_service.py b/openviking/service/session_service.py
index c2c139d47..806af8ffd 100644
--- a/openviking/service/session_service.py
+++ b/openviking/service/session_service.py
@@ -191,7 +191,7 @@ class SessionService:
"""
self._ensure_initialized()
session_base_uri = canonical_session_uri(ctx)
- sessions = []
+ sessions_by_id: Dict[str, Dict[str, Any]] = {}
try:
entries = await self._viking_fs.ls(session_base_uri, ctx=ctx)
@@ -199,16 +199,28 @@ class SessionService:
name = entry.get("name", "")
if name in [".", ".."]:
continue
- sessions.append(
- {
- "session_id": name,
- "uri": f"{session_base_uri}/{name}",
- "is_dir": entry.get("isDir", False),
- }
- )
+ sessions_by_id[name] = {
+ "session_id": name,
+ "uri": f"{session_base_uri}/{name}",
+ "is_dir": entry.get("isDir", False),
+ }
except Exception:
logger.debug("Failed to list sessions", exc_info=True)
- return sessions
+
+ try:
+ entries = await self._viking_fs.ls("viking://session", ctx=ctx)
+ for entry in entries:
+ name = entry.get("name", "")
+ if name in [".", ".."] or name in sessions_by_id:
+ continue
+ sessions_by_id[name] = {
+ "session_id": name,
+ "uri": entry.get("uri", f"viking://session/{name}"),
+ "is_dir": entry.get("isDir", False),
+ }
+ except Exception:
+ logger.debug("Failed to list legacy sessions", exc_info=True)
+ return list(sessions_by_id.values())
async def delete(self, session_id: str, ctx: RequestContext) -> bool:
"""Delete a session.
diff --git a/openviking/service/task_store.py b/openviking/service/task_store.py
index 384708259..d2312b62d 100644
--- a/openviking/service/task_store.py
+++ b/openviking/service/task_store.py
@@ -11,6 +11,9 @@ from typing import Any, Dict, List, Optional, Protocol
from openviking.pyagfs import AsyncAGFSClient
from openviking.pyagfs.exceptions import AGFSAlreadyExistsError
+SYSTEM_TASK_ACCOUNT_ID = "_system"
+SYSTEM_TASK_USER_ID = "root"
+
class TaskStore(Protocol):
async def create(self, task: Any) -> None: ...
@@ -122,6 +125,8 @@ class PersistentTaskStore:
return f"{self.ROOT_PREFIX}/{account_id}"
def _system_dir(self, account_id: str) -> str:
+ if account_id == SYSTEM_TASK_ACCOUNT_ID:
+ return self._account_dir(account_id)
return f"{self._account_dir(account_id)}/{self.SYSTEM_DIRNAME}"
def _task_root_dir(self, account_id: str) -> str:
diff --git a/openviking/service/task_tracker.py b/openviking/service/task_tracker.py
index 40683c0d8..134c09414 100644
--- a/openviking/service/task_tracker.py
+++ b/openviking/service/task_tracker.py
@@ -61,6 +61,7 @@ class TaskRecord:
d["status"] = self.status.value
d["created_at_iso"] = datetime.fromtimestamp(self.created_at, tz=timezone.utc).isoformat()
d["updated_at_iso"] = datetime.fromtimestamp(self.updated_at, tz=timezone.utc).isoformat()
+ d["result"] = _sanitize_task_result(d.get("result"))
d.pop("account_id", None)
d.pop("user_id", None)
return d
@@ -103,6 +104,7 @@ _SENSITIVE_PATTERNS = re.compile(
)
_MAX_ERROR_LEN = 500
+_SENSITIVE_RESULT_KEYS = {"user_key"}
def _sanitize_error(error: str) -> str:
@@ -113,6 +115,19 @@ def _sanitize_error(error: str) -> str:
return sanitized
+def _sanitize_task_result(result: Any) -> Any:
+ """Remove sensitive fields from task results before exposing snapshots."""
+ if isinstance(result, dict):
+ return {
+ key: _sanitize_task_result(value)
+ for key, value in result.items()
+ if key not in _SENSITIVE_RESULT_KEYS
+ }
+ if isinstance(result, list):
+ return [_sanitize_task_result(item) for item in result]
+ return result
+
+
# ── TaskTracker ──
@@ -342,6 +357,7 @@ class TaskTracker:
task = await self._load_for_update(task_id, account_id, user_id)
if task:
task.status = TaskStatus.COMPLETED
+ task.stage = "completed"
task.result = result
task.updated_at = time.time()
await self._store.update(task)
@@ -361,6 +377,7 @@ class TaskTracker:
task = await self._load_for_update(task_id, account_id, user_id)
if task:
task.status = TaskStatus.FAILED
+ task.stage = "failed"
task.error = _sanitize_error(error)
task.updated_at = time.time()
await self._store.update(task)
@@ -483,7 +500,9 @@ class TaskTracker:
@staticmethod
def _copy(task: TaskRecord) -> TaskRecord:
"""Return a defensive copy of a TaskRecord."""
- return deepcopy(task)
+ copied = deepcopy(task)
+ copied.result = _sanitize_task_result(copied.result)
+ return copied
def count(self) -> int:
"""Return total task count."""
diff --git a/openviking/session/memory/memory_updater.py b/openviking/session/memory/memory_updater.py
index b7c0eac2c..7880344e3 100644
--- a/openviking/session/memory/memory_updater.py
+++ b/openviking/session/memory/memory_updater.py
@@ -382,9 +382,7 @@ class MessageRange:
@staticmethod
def _speaker_for(message: Message) -> str:
- return (
- getattr(message, "peer_id", None) or getattr(message, "role_id", None) or message.role
- )
+ return getattr(message, "peer_id", None) or message.role
def _can_merge_messages(self, previous: Message, current: Message) -> bool:
previous_meta = self._chunk_meta_for(previous)
diff --git a/openviking/session/memory_policy.py b/openviking/session/memory_policy.py
index 3c30c360f..44a2f66bb 100644
--- a/openviking/session/memory_policy.py
+++ b/openviking/session/memory_policy.py
@@ -42,7 +42,7 @@ class MemoryPolicy:
"""Effective memory policy for one commit."""
self_enabled: bool = True
- peer_enabled: bool = False
+ peer_enabled: bool = True
memory_types: Optional[set[str]] = None
@classmethod
@@ -64,7 +64,7 @@ class MemoryPolicy:
)
return cls(
self_enabled=_target_enabled(data.get("self"), default_enabled=True),
- peer_enabled=_target_enabled(data.get("peer"), default_enabled=False),
+ peer_enabled=_target_enabled(data.get("peer"), default_enabled=True),
memory_types=_parse_memory_types(data.get("memory_types")),
)
diff --git a/openviking/session/session.py b/openviking/session/session.py
index c4faed666..c36c2b483 100644
--- a/openviking/session/session.py
+++ b/openviking/session/session.py
@@ -14,7 +14,7 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional
from uuid import uuid4
from openviking.core.namespace import canonical_session_uri
-from openviking.core.peer_id import normalize_peer_id
+from openviking.core.peer_id import normalize_peer_id, safe_peer_id
from openviking.message import Message, Part
from openviking.message.part import ContextPart, TextPart, ToolPart
from openviking.server.config import ToolOutputExternalizationConfig
@@ -83,7 +83,11 @@ 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 := safe_peer_id(getattr(message, "peer_id", None)))
+ }
@dataclass(frozen=True)
diff --git a/openviking/storage/vector_migration.py b/openviking/storage/vector_migration.py
new file mode 100644
index 000000000..89ab4dbf5
--- /dev/null
+++ b/openviking/storage/vector_migration.py
@@ -0,0 +1,256 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Helpers for copying and deleting vector records during namespace migration."""
+
+from __future__ import annotations
+
+import hashlib
+from dataclasses import dataclass, field
+from typing import Any
+
+from openviking.core.namespace import context_type_for_uri, owner_fields_for_uri
+from openviking.server.identity import RequestContext, Role
+from openviking.storage.expr import And, Contains, Eq, Or, PathScope
+from openviking.utils.time_utils import get_current_timestamp
+from openviking_cli.session.user_id import UserIdentifier
+from openviking_cli.utils.uri import VikingURI
+
+VECTOR_MIGRATION_OUTPUT_FIELDS = [
+ "id",
+ "uri",
+ "type",
+ "context_type",
+ "vector",
+ "sparse_vector",
+ "created_at",
+ "updated_at",
+ "active_count",
+ "level",
+ "name",
+ "description",
+ "tags",
+ "abstract",
+ "account_id",
+ "owner_user_id",
+ "owner_space",
+]
+
+_VECTOR_PAYLOAD_FIELDS = ("vector", "sparse_vector")
+_MAX_VECTOR_RECORDS_PER_SCOPE = 100_000
+
+
+@dataclass
+class VectorMigrationResult:
+ copied: int = 0
+ deleted: int = 0
+ skipped: int = 0
+ failed: int = 0
+ warnings: list[str] = field(default_factory=list)
+
+ def extend(self, other: "VectorMigrationResult") -> None:
+ self.copied += other.copied
+ self.deleted += other.deleted
+ self.skipped += other.skipped
+ self.failed += other.failed
+ self.warnings.extend(other.warnings)
+
+
+def _root_ctx(account_id: str) -> RequestContext:
+ return RequestContext(user=UserIdentifier(account_id, "default"), role=Role.ROOT)
+
+
+def _normalize_uri(uri: str) -> str:
+ return VikingURI.normalize(uri).rstrip("/")
+
+
+def _seed_uri_for_id(uri: str, level: Any) -> str:
+ try:
+ level_int = int(level)
+ except (TypeError, ValueError):
+ level_int = 2
+
+ if level_int == 0:
+ return uri if uri.endswith("/.abstract.md") else f"{uri}/.abstract.md"
+ if level_int == 1:
+ return uri if uri.endswith("/.overview.md") else f"{uri}/.overview.md"
+ return uri
+
+
+def _vector_record_id(account_id: str, uri: str, level: Any) -> str:
+ seed_uri = _seed_uri_for_id(uri, level)
+ return hashlib.md5(f"{account_id}:{seed_uri}".encode("utf-8")).hexdigest()
+
+
+def _has_vector_payload(record: dict[str, Any]) -> bool:
+ for field_name in _VECTOR_PAYLOAD_FIELDS:
+ value = record.get(field_name)
+ if isinstance(value, (list, dict)) and value:
+ return True
+ return False
+
+
+def _uri_in_scope(uri: str, scope_uri: str, *, recursive: bool) -> bool:
+ return (
+ uri == scope_uri
+ or uri.startswith(scope_uri + "#")
+ or (recursive and uri.startswith(scope_uri + "/"))
+ )
+
+
+def _rewrite_uri(uri: str, source_uri: str, target_uri: str) -> str:
+ if uri == source_uri:
+ return target_uri
+ if uri.startswith(source_uri + "/") or uri.startswith(source_uri + "#"):
+ return target_uri + uri[len(source_uri) :]
+ return uri
+
+
+async def _records_in_scope(
+ vector_store: Any,
+ *,
+ account_id: str,
+ uri: str,
+ recursive: bool,
+) -> list[dict[str, Any]]:
+ filters = [Eq("uri", uri), Contains("uri", uri + "#")]
+ if recursive:
+ filters.append(PathScope("uri", uri, depth=-1))
+
+ ctx = _root_ctx(account_id)
+ records = await vector_store.filter(
+ filter=And([Eq("account_id", account_id), Or(filters)]),
+ limit=_MAX_VECTOR_RECORDS_PER_SCOPE,
+ output_fields=VECTOR_MIGRATION_OUTPUT_FIELDS,
+ ctx=ctx,
+ )
+ return [
+ record
+ for record in records
+ if isinstance(record.get("uri"), str)
+ and _uri_in_scope(record["uri"], uri, recursive=recursive)
+ ]
+
+
+async def copy_vector_records(
+ vector_store: Any,
+ *,
+ account_id: str,
+ source_uri: str,
+ target_uri: str,
+ recursive: bool,
+) -> VectorMigrationResult:
+ """Copy vector records from one URI scope to another without re-embedding."""
+ result = VectorMigrationResult()
+ if (
+ not vector_store
+ or not hasattr(vector_store, "filter")
+ or not hasattr(vector_store, "upsert")
+ ):
+ result.warnings.append(f"Skipped vector copy for {source_uri}: vector store is unavailable")
+ return result
+
+ source_uri = _normalize_uri(source_uri)
+ target_uri = _normalize_uri(target_uri)
+ ctx = _root_ctx(account_id)
+ try:
+ records = await _records_in_scope(
+ vector_store,
+ account_id=account_id,
+ uri=source_uri,
+ recursive=recursive,
+ )
+ except Exception as exc:
+ result.failed += 1
+ result.warnings.append(f"Failed to read vectors for {source_uri}: {exc}")
+ return result
+
+ if len(records) >= _MAX_VECTOR_RECORDS_PER_SCOPE:
+ result.warnings.append(
+ f"Vector copy for {source_uri} reached the per-scope record limit "
+ f"({_MAX_VECTOR_RECORDS_PER_SCOPE}); run reindex if records are missing"
+ )
+
+ timestamp = get_current_timestamp()
+ for record in records:
+ source_record_uri = record["uri"]
+ if not _has_vector_payload(record):
+ result.skipped += 1
+ continue
+
+ rewritten_uri = _rewrite_uri(source_record_uri, source_uri, target_uri)
+ owner_fields = owner_fields_for_uri(
+ rewritten_uri,
+ user=ctx.user,
+ account_id=account_id,
+ )
+ level = record.get("level", 2)
+ payload = {
+ key: value
+ for key, value in record.items()
+ if key not in {"id", "uri", "account_id", "owner_user_id", "owner_space", "_score"}
+ and value is not None
+ }
+ payload.update(
+ {
+ "id": _vector_record_id(account_id, rewritten_uri, level),
+ "uri": rewritten_uri,
+ "account_id": account_id,
+ "owner_user_id": owner_fields.get("owner_user_id"),
+ "owner_space": owner_fields.get("owner_user_id") or "",
+ "context_type": context_type_for_uri(rewritten_uri),
+ "created_at": timestamp,
+ "updated_at": timestamp,
+ "active_count": 0,
+ }
+ )
+ try:
+ await vector_store.upsert(payload, ctx=ctx)
+ result.copied += 1
+ except Exception as exc:
+ result.failed += 1
+ result.warnings.append(
+ f"Failed to copy vector {source_record_uri} to {rewritten_uri}: {exc}"
+ )
+ return result
+
+
+async def delete_vector_records(
+ vector_store: Any,
+ *,
+ account_id: str,
+ uri: str,
+ recursive: bool = True,
+) -> VectorMigrationResult:
+ """Delete vector records for a legacy URI scope."""
+ result = VectorMigrationResult()
+ if (
+ not vector_store
+ or not hasattr(vector_store, "filter")
+ or not hasattr(vector_store, "delete")
+ ):
+ result.warnings.append(f"Skipped vector cleanup for {uri}: vector store is unavailable")
+ return result
+
+ uri = _normalize_uri(uri)
+ ctx = _root_ctx(account_id)
+ try:
+ records = await _records_in_scope(
+ vector_store,
+ account_id=account_id,
+ uri=uri,
+ recursive=recursive,
+ )
+ except Exception as exc:
+ result.failed += 1
+ result.warnings.append(f"Failed to read vectors for cleanup {uri}: {exc}")
+ return result
+
+ ids = sorted({str(record["id"]) for record in records if record.get("id")})
+ if not ids:
+ return result
+ try:
+ result.deleted = int(await vector_store.delete(ids, ctx=ctx) or 0)
+ except Exception as exc:
+ result.failed += len(ids)
+ result.warnings.append(f"Failed to delete vectors for {uri}: {exc}")
+ return result
diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.py
index 796e4f0d6..3bc90b3b1 100644
--- a/openviking/storage/viking_fs.py
+++ b/openviking/storage/viking_fs.py
@@ -338,12 +338,21 @@ class VikingFS:
normalized_uri, real_ctx
):
raise PermissionDeniedError(f"Access denied for {uri}", resource=normalized_uri)
+ self._ensure_supported_write_namespace(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",
resource=normalized_uri,
)
+ def _ensure_supported_write_namespace(self, normalized_uri: str) -> None:
+ parts = [p for p in normalized_uri[len("viking://") :].strip("/").split("/") if p]
+ if parts and parts[0] in {"agent", "session"}:
+ raise PermissionDeniedError(
+ f"Writing {normalized_uri} is not supported; use user-owned namespaces instead.",
+ resource=normalized_uri,
+ )
+
# ========== AGFS Basic Commands ==========
async def read(
@@ -355,12 +364,26 @@ class VikingFS:
) -> bytes:
"""Read file"""
self._ensure_access(uri, ctx)
- path = self._uri_to_path(uri, ctx=ctx)
+ real_ctx = self._ctx_or_default(ctx)
+ primary_path = self._uri_to_path(uri, ctx=ctx)
# Decryption + offset/size slicing now happen inside the ragfs encryption layer
# (when configured); the plaintext stack reads bytes directly. Either way, pass the
# offset/size through and let the Rust layer return the requested slice.
- result = await self._async_agfs.read(path, offset, size)
+ last_not_found: Optional[Exception] = None
+ for path in self._session_read_paths(uri, ctx=ctx):
+ if path != primary_path and not await self._legacy_session_path_visible(path, real_ctx):
+ continue
+ try:
+ result = await self._async_agfs.read(path, offset, size)
+ break
+ except Exception as exc:
+ if is_not_found_error(exc):
+ last_not_found = exc
+ continue
+ raise
+ else:
+ raise NotFoundError(uri, "file") from last_not_found
if isinstance(result, bytes):
raw = result
elif result is not None and hasattr(result, "content"):
@@ -881,8 +904,36 @@ class VikingFS:
field is not included.
"""
self._ensure_access(uri, ctx)
- path = self._uri_to_path(uri, ctx=ctx)
- result = await self._async_agfs.stat(path)
+ real_ctx = self._ctx_or_default(ctx)
+ primary_path = self._uri_to_path(uri, ctx=ctx)
+ path = primary_path
+ last_not_found: Optional[Exception] = None
+ for candidate_path in self._session_read_paths(uri, ctx=ctx):
+ if candidate_path != primary_path and not await self._legacy_session_path_visible(
+ candidate_path, real_ctx
+ ):
+ continue
+ try:
+ result = await self._async_agfs.stat(candidate_path)
+ path = candidate_path
+ break
+ except Exception as exc:
+ if is_not_found_error(exc):
+ last_not_found = exc
+ continue
+ raise
+ else:
+ if self._is_legacy_session_root_uri(uri):
+ now = datetime.now(timezone.utc).isoformat()
+ return {
+ "name": "session",
+ "size": 0,
+ "mode": 0o755,
+ "modTime": now,
+ "isDir": True,
+ "isLocked": False,
+ }
+ raise NotFoundError(uri, "file") from last_not_found
if isinstance(result, dict):
result["isLocked"] = await self._is_path_locked_async(path)
# Add count for directories if vector store available
@@ -890,7 +941,6 @@ class VikingFS:
try:
vector_store = self._get_vector_store()
if vector_store:
- real_ctx = self._ctx_or_default(ctx)
target_canonical_uri = canonicalize_uri(
self._path_to_uri(path, ctx=real_ctx), real_ctx
)
@@ -1146,8 +1196,20 @@ class VikingFS:
must guarantee that the URI points to a directory.
"""
self._ensure_access(uri, ctx)
- path = self._uri_to_path(uri, ctx=ctx)
- return await self._read_abstract_file(path, uri, ctx=ctx)
+ real_ctx = self._ctx_or_default(ctx)
+ primary_path = self._uri_to_path(uri, ctx=ctx)
+ for path in self._session_read_paths(uri, ctx=ctx):
+ if path != primary_path and not await self._legacy_session_path_visible(path, real_ctx):
+ continue
+ try:
+ if not await self._agfs_path_exists(path):
+ continue
+ return await self._read_abstract_file(path, uri, ctx=ctx)
+ except Exception as exc:
+ if is_not_found_error(exc):
+ continue
+ raise
+ return f"# {uri} [Directory abstract is not ready]"
async def abstract(
self,
@@ -1160,14 +1222,33 @@ class VikingFS:
the endpoint remains usable for both file and directory URIs.
"""
self._ensure_access(uri, ctx)
- path = self._uri_to_path(uri, ctx=ctx)
- try:
- info = await self._async_agfs.stat(path)
- except Exception as exc:
- mapped = map_exception(exc, resource=uri)
- if mapped is not None:
- raise mapped from exc
- raise
+ real_ctx = self._ctx_or_default(ctx)
+ primary_path = self._uri_to_path(uri, ctx=ctx)
+ path = primary_path
+ last_exc: Optional[Exception] = None
+ for candidate_path in self._session_read_paths(uri, ctx=ctx):
+ if candidate_path != primary_path and not await self._legacy_session_path_visible(
+ candidate_path, real_ctx
+ ):
+ continue
+ try:
+ info = await self._async_agfs.stat(candidate_path)
+ path = candidate_path
+ break
+ except Exception as exc:
+ if is_not_found_error(exc):
+ last_exc = exc
+ continue
+ mapped = map_exception(exc, resource=uri)
+ if mapped is not None:
+ raise mapped from exc
+ raise
+ else:
+ if last_exc is not None:
+ mapped = map_exception(last_exc, resource=uri)
+ if mapped is not None:
+ raise mapped from last_exc
+ raise NotFoundError(uri, "directory") from last_exc
if not info.get("isDir", info.get("is_dir")):
parent_path = path.rsplit("/", 1)[0] or "/"
parent_uri = self._path_to_uri(parent_path, ctx=ctx)
@@ -1190,14 +1271,33 @@ class VikingFS:
the endpoint remains usable for both file and directory URIs.
"""
self._ensure_access(uri, ctx=ctx)
- path = self._uri_to_path(uri, ctx=ctx)
- try:
- info = await self._async_agfs.stat(path)
- except Exception as exc:
- mapped = map_exception(exc, resource=uri)
- if mapped is not None:
- raise mapped from exc
- raise
+ real_ctx = self._ctx_or_default(ctx)
+ primary_path = self._uri_to_path(uri, ctx=ctx)
+ path = primary_path
+ last_exc: Optional[Exception] = None
+ for candidate_path in self._session_read_paths(uri, ctx=ctx):
+ if candidate_path != primary_path and not await self._legacy_session_path_visible(
+ candidate_path, real_ctx
+ ):
+ continue
+ try:
+ info = await self._async_agfs.stat(candidate_path)
+ path = candidate_path
+ break
+ except Exception as exc:
+ if is_not_found_error(exc):
+ last_exc = exc
+ continue
+ mapped = map_exception(exc, resource=uri)
+ if mapped is not None:
+ raise mapped from exc
+ raise
+ else:
+ if last_exc is not None:
+ mapped = map_exception(last_exc, resource=uri)
+ if mapped is not None:
+ raise mapped from last_exc
+ raise NotFoundError(uri, "directory") from last_exc
if not info.get("isDir", info.get("is_dir")):
parent_path = path.rsplit("/", 1)[0] or "/"
parent_uri = self._path_to_uri(parent_path, ctx=ctx)
@@ -1472,7 +1572,7 @@ class VikingFS:
"""Create relation (maintained in .relations.json)."""
if isinstance(uris, str):
uris = [uris]
- self._ensure_access(from_uri, ctx)
+ self._ensure_mutable_access(from_uri, ctx)
for uri in uris:
self._ensure_access(uri, ctx)
@@ -1495,7 +1595,7 @@ class VikingFS:
ctx: Optional[RequestContext] = None,
) -> None:
"""Delete relation."""
- self._ensure_access(from_uri, ctx)
+ self._ensure_mutable_access(from_uri, ctx)
self._ensure_access(uri, ctx)
from_path = self._uri_to_path(from_uri, ctx=ctx)
@@ -1623,8 +1723,21 @@ class VikingFS:
When node_limit is None (full-tree callers), no limit is pushed down.
level_limit IS always passed to Rust.
"""
- path = self._uri_to_path(uri, ctx=ctx)
real_ctx = self._ctx_or_default(ctx)
+ primary_path = self._uri_to_path(uri, ctx=ctx)
+ path: Optional[str] = None
+ for candidate_path in self._session_read_paths(uri, ctx=ctx):
+ if candidate_path != primary_path and not await self._legacy_session_path_visible(
+ candidate_path, real_ctx
+ ):
+ continue
+ if await self._agfs_path_exists(candidate_path):
+ path = candidate_path
+ break
+ if path is None:
+ if self._is_legacy_session_root_uri(uri):
+ return
+ raise NotFoundError(uri, "directory")
if node_limit is None:
raw_limit: Optional[int] = None
@@ -1645,7 +1758,16 @@ class VikingFS:
break
if not self._is_tree_entry_visible(entry, path, real_ctx):
continue
- entry_uri = self._path_to_uri(entry["path"], ctx=ctx)
+ if path != primary_path and not await self._legacy_session_path_visible(
+ entry["path"], real_ctx
+ ):
+ continue
+ entry_uri = self._session_alias_uri_for_path(
+ request_uri=uri,
+ base_path=path,
+ entry_path=entry["path"],
+ ctx=ctx,
+ )
visible.append((entry, entry_uri))
# If we still lack enough visible entries but Rust returned a full
@@ -1691,6 +1813,12 @@ class VikingFS:
"""
real_ctx = self._ctx_or_default(ctx)
account_id = real_ctx.account_id
+ normalized_uri, legacy_parts = self._normalized_uri_parts(uri)
+ if legacy_parts and legacy_parts[0] == "agent":
+ safe_parts = [
+ self._shorten_component(p, self._MAX_FILENAME_BYTES) for p in legacy_parts
+ ]
+ return f"/local/{account_id}/{'/'.join(safe_parts)}"
canonical_uri = canonicalize_uri(uri, real_ctx)
_, parts = self._normalized_uri_parts(canonical_uri)
if not parts:
@@ -1699,6 +1827,206 @@ class VikingFS:
safe_parts = [self._shorten_component(p, self._MAX_FILENAME_BYTES) for p in parts]
return f"/local/{account_id}/{'/'.join(safe_parts)}"
+ def _legacy_session_path(self, uri: str, ctx: Optional[RequestContext] = None) -> str:
+ """Map a legacy viking://session URI to its pre-user-namespace path."""
+ real_ctx = self._ctx_or_default(ctx)
+ _, parts = self._normalized_uri_parts(uri)
+ safe_parts = [self._shorten_component(p, self._MAX_FILENAME_BYTES) for p in parts]
+ return f"/local/{real_ctx.account_id}/{'/'.join(safe_parts)}"
+
+ def _legacy_current_user_session_path(
+ self, uri: str, ctx: Optional[RequestContext] = None
+ ) -> Optional[str]:
+ """Return the legacy nested /session/{user_id}/{session_id} candidate."""
+ real_ctx = self._ctx_or_default(ctx)
+ _, parts = self._normalized_uri_parts(uri)
+ if len(parts) <= 1 or parts[0] != "session":
+ return None
+ nested_parts = ["session", real_ctx.user.user_id, *parts[1:]]
+ safe_parts = [self._shorten_component(p, self._MAX_FILENAME_BYTES) for p in nested_parts]
+ return f"/local/{real_ctx.account_id}/{'/'.join(safe_parts)}"
+
+ def _is_legacy_session_uri(self, uri: str) -> bool:
+ _, parts = self._normalized_uri_parts(uri)
+ return bool(parts and parts[0] == "session")
+
+ def _is_legacy_session_root_uri(self, uri: str) -> bool:
+ _, parts = self._normalized_uri_parts(uri)
+ return parts == ["session"]
+
+ def _session_read_paths(self, uri: str, ctx: Optional[RequestContext] = None) -> List[str]:
+ """Return read candidates for a URI, with legacy session fallback paths."""
+ paths = [self._uri_to_path(uri, ctx=ctx)]
+ if not self._is_legacy_session_uri(uri):
+ return paths
+
+ for candidate in (
+ self._legacy_session_path(uri, ctx=ctx),
+ self._legacy_current_user_session_path(uri, ctx=ctx),
+ ):
+ if candidate and candidate not in paths:
+ paths.append(candidate)
+ return paths
+
+ def _session_alias_uri_for_path(
+ self,
+ *,
+ request_uri: str,
+ base_path: str,
+ entry_path: str,
+ ctx: Optional[RequestContext],
+ ) -> str:
+ if not self._is_legacy_session_uri(request_uri):
+ return self._path_to_uri(entry_path, ctx=ctx)
+ base = base_path.rstrip("/")
+ rel_path = entry_path[len(base) :].strip("/") if entry_path.startswith(base) else ""
+ if not rel_path:
+ return VikingURI.normalize(request_uri).rstrip("/")
+ return f"{VikingURI.normalize(request_uri).rstrip('/')}/{rel_path}"
+
+ async def _agfs_path_exists(self, path: str) -> bool:
+ try:
+ await self._async_agfs.stat(path)
+ return True
+ except Exception as exc:
+ if is_not_found_error(exc):
+ return False
+ raise
+
+ async def _looks_like_legacy_session_dir(self, path: str) -> bool:
+ for leaf in (".meta.json", "messages.jsonl", "history", "tool-results", "tools"):
+ if await self._agfs_path_exists(f"{path}/{leaf}"):
+ return True
+ return False
+
+ async def _legacy_session_owner(self, session_root_path: str) -> str:
+ try:
+ raw = self._handle_agfs_read(
+ await self._async_agfs.read(f"{session_root_path}/.meta.json")
+ )
+ except Exception as exc:
+ if is_not_found_error(exc):
+ return ""
+ raise
+ try:
+ data = json.loads(self._decode_bytes(raw))
+ except json.JSONDecodeError:
+ return ""
+ if not isinstance(data, dict):
+ return ""
+ for key in ("created_by_user_id", "user_id", "owner_user_id", "created_by"):
+ value = data.get(key)
+ if isinstance(value, str) and value.strip():
+ return value.strip()
+ return ""
+
+ async def _legacy_session_visible(
+ self,
+ session_root_path: str,
+ ctx: RequestContext,
+ *,
+ owner_hint: Optional[str] = None,
+ ) -> bool:
+ if ctx.role == Role.ROOT:
+ return True
+ owner = await self._legacy_session_owner(session_root_path)
+ if owner:
+ return owner == ctx.user.user_id
+ if owner_hint:
+ return owner_hint == ctx.user.user_id
+ return True
+
+ async def _legacy_session_path_visible(self, path: str, ctx: RequestContext) -> bool:
+ parts = [p for p in path.strip("/").split("/") if p]
+ try:
+ session_index = parts.index("session")
+ except ValueError:
+ return True
+ suffix = parts[session_index + 1 :]
+ if not suffix:
+ return True
+
+ root_prefix = "/" + "/".join(parts[: session_index + 1])
+ direct_root = f"{root_prefix}/{suffix[0]}"
+ if await self._looks_like_legacy_session_dir(direct_root):
+ return await self._legacy_session_visible(direct_root, ctx)
+
+ if len(suffix) >= 2:
+ nested_root = f"{root_prefix}/{suffix[0]}/{suffix[1]}"
+ if await self._looks_like_legacy_session_dir(nested_root):
+ return await self._legacy_session_visible(
+ nested_root,
+ ctx,
+ owner_hint=suffix[0],
+ )
+ return True
+
+ async def _legacy_session_root_items(
+ self,
+ path: str,
+ ctx: RequestContext,
+ ) -> List[tuple[Dict[str, Any], str]]:
+ try:
+ entries = await self._ls_entries(path)
+ except Exception as exc:
+ if is_not_found_error(exc):
+ return []
+ raise
+
+ items: List[tuple[Dict[str, Any], str]] = []
+ for entry in entries:
+ name = entry.get("name", "")
+ if not name or name in {".", ".."} or not entry.get("isDir"):
+ continue
+ child_path = f"{path.rstrip('/')}/{name}"
+ if await self._looks_like_legacy_session_dir(child_path):
+ if await self._legacy_session_visible(child_path, ctx):
+ items.append((entry, f"viking://session/{name}"))
+ continue
+
+ if ctx.role != Role.ROOT and name != ctx.user.user_id:
+ continue
+ try:
+ nested_entries = await self._ls_entries(child_path)
+ except Exception as exc:
+ if is_not_found_error(exc):
+ continue
+ raise
+ for nested in nested_entries:
+ nested_name = nested.get("name", "")
+ if not nested_name or nested_name in {".", ".."} or not nested.get("isDir"):
+ continue
+ nested_path = f"{child_path.rstrip('/')}/{nested_name}"
+ if not await self._looks_like_legacy_session_dir(nested_path):
+ continue
+ if await self._legacy_session_visible(nested_path, ctx, owner_hint=name):
+ items.append((nested, f"viking://session/{nested_name}"))
+ return items
+
+ async def _session_root_items(
+ self,
+ uri: str,
+ ctx: RequestContext,
+ ) -> List[tuple[Dict[str, Any], str]]:
+ primary_path = self._uri_to_path(uri, ctx=ctx)
+ by_name: Dict[str, tuple[Dict[str, Any], str]] = {}
+ try:
+ for entry in await self._ls_entries(primary_path, ctx=ctx):
+ name = entry.get("name", "")
+ if not name or name in {".", ".."}:
+ continue
+ by_name[name] = (entry, f"viking://session/{name}")
+ except Exception as exc:
+ if not is_not_found_error(exc):
+ raise
+
+ legacy_path = self._legacy_session_path(uri, ctx=ctx)
+ for entry, entry_uri in await self._legacy_session_root_items(legacy_path, ctx):
+ name = entry.get("name", "")
+ if name and name not in by_name:
+ by_name[name] = (entry, entry_uri)
+ return list(by_name.values())
+
_ROOT_PATH = "/local"
async def _ls_entries(
@@ -1774,8 +2102,16 @@ class VikingFS:
return ctx.role == Role.ROOT
if scope == "_system":
return False
+ if scope == "agent":
+ return self._is_legacy_agent_accessible(parts, ctx)
return namespace_is_accessible(normalized_uri, ctx)
+ @staticmethod
+ def _is_legacy_agent_accessible(parts: List[str], ctx: RequestContext) -> bool:
+ if not ctx.actor_peer_id or len(parts) < 2:
+ return True
+ return parts[1] == ctx.actor_peer_id
+
def _handle_agfs_read(self, result: Union[bytes, Any, None]) -> bytes:
"""Handle AGFSClient read return types consistently."""
if isinstance(result, bytes):
@@ -2095,13 +2431,24 @@ class VikingFS:
FileNotFoundError: If the file does not exist.
"""
self._ensure_access(uri, ctx)
- path = self._uri_to_path(uri, ctx=ctx)
+ real_ctx = self._ctx_or_default(ctx)
+ primary_path = self._uri_to_path(uri, ctx=ctx)
# Verify the file exists before reading, because AGFS read returns
# empty bytes for non-existent files instead of raising an error.
- try:
- stat = await self._async_agfs.stat(path)
- except Exception:
- raise NotFoundError(uri, "file")
+ last_not_found: Optional[Exception] = None
+ for path in self._session_read_paths(uri, ctx=ctx):
+ if path != primary_path and not await self._legacy_session_path_visible(path, real_ctx):
+ continue
+ try:
+ stat = await self._async_agfs.stat(path)
+ break
+ except Exception as exc:
+ if is_not_found_error(exc):
+ last_not_found = exc
+ continue
+ raise
+ else:
+ raise NotFoundError(uri, "file") from last_not_found
if isinstance(stat, dict) and stat.get("isDir", False):
raise InvalidArgumentError(
f"Cannot read directory as file: {uri}",
@@ -2133,11 +2480,22 @@ class VikingFS:
) -> bytes:
"""Read single binary file."""
self._ensure_access(uri, ctx)
- path = self._uri_to_path(uri, ctx=ctx)
- try:
- stat = await self._async_agfs.stat(path)
- except Exception:
- raise NotFoundError(uri, "file")
+ real_ctx = self._ctx_or_default(ctx)
+ primary_path = self._uri_to_path(uri, ctx=ctx)
+ last_not_found: Optional[Exception] = None
+ for path in self._session_read_paths(uri, ctx=ctx):
+ if path != primary_path and not await self._legacy_session_path_visible(path, real_ctx):
+ continue
+ try:
+ stat = await self._async_agfs.stat(path)
+ break
+ except Exception as exc:
+ if is_not_found_error(exc):
+ last_not_found = exc
+ continue
+ raise
+ else:
+ raise NotFoundError(uri, "file") from last_not_found
if isinstance(stat, dict) and stat.get("isDir", False):
raise InvalidArgumentError(
f"Cannot read directory as file: {uri}",
@@ -2235,16 +2593,43 @@ class VikingFS:
ctx: Optional[RequestContext] = None,
) -> List[Dict[str, Any]]:
"""List directory contents (URI version)."""
- path = self._uri_to_path(uri, ctx=ctx)
real_ctx = self._ctx_or_default(ctx)
- try:
- entries = await self._ls_entries(path, ctx=ctx)
- except Exception:
- raise NotFoundError(uri, "directory")
+ if self._is_legacy_session_root_uri(uri):
+ entry_items = await self._session_root_items(uri, real_ctx)
+ else:
+ primary_path = self._uri_to_path(uri, ctx=ctx)
+ last_not_found: Optional[Exception] = None
+ for path in self._session_read_paths(uri, ctx=ctx):
+ if path != primary_path and not await self._legacy_session_path_visible(
+ path, real_ctx
+ ):
+ continue
+ try:
+ entries = await self._ls_entries(path, ctx=ctx)
+ entry_items = [
+ (
+ entry,
+ self._session_alias_uri_for_path(
+ request_uri=uri,
+ base_path=path,
+ entry_path=f"{path.rstrip('/')}/{entry.get('name', '')}",
+ ctx=ctx,
+ ),
+ )
+ for entry in entries
+ ]
+ break
+ except Exception as exc:
+ if is_not_found_error(exc):
+ last_not_found = exc
+ continue
+ raise
+ else:
+ raise NotFoundError(uri, "directory") from last_not_found
# basic info
fallback_time = datetime.now(timezone.utc)
all_entries = []
- for entry in entries:
+ for entry, entry_uri in entry_items:
if len(all_entries) >= node_limit:
break
name = entry.get("name", "")
@@ -2261,7 +2646,7 @@ class VikingFS:
parsed_time = datetime.fromtimestamp(entry["mtime"], tz=timezone.utc)
is_dir = entry.get("isDir", False)
new_entry = {
- "uri": self._path_to_uri(f"{path}/{name}", ctx=ctx),
+ "uri": entry_uri,
"size": 0 if is_dir else entry.get("size", 0),
"isDir": is_dir,
"modTime": format_iso8601(parsed_time),
@@ -2285,18 +2670,48 @@ class VikingFS:
ctx: Optional[RequestContext] = None,
) -> List[Dict[str, Any]]:
"""List directory contents (URI version)."""
- path = self._uri_to_path(uri, ctx=ctx)
real_ctx = self._ctx_or_default(ctx)
try:
- entries = await self._ls_entries(path, ctx=ctx)
+ if self._is_legacy_session_root_uri(uri):
+ entry_items = await self._session_root_items(uri, real_ctx)
+ else:
+ primary_path = self._uri_to_path(uri, ctx=ctx)
+ last_not_found: Optional[Exception] = None
+ for path in self._session_read_paths(uri, ctx=ctx):
+ if path != primary_path and not await self._legacy_session_path_visible(
+ path, real_ctx
+ ):
+ continue
+ try:
+ entries = await self._ls_entries(path, ctx=ctx)
+ entry_items = [
+ (
+ entry,
+ self._session_alias_uri_for_path(
+ request_uri=uri,
+ base_path=path,
+ entry_path=f"{path.rstrip('/')}/{entry.get('name', '')}",
+ ctx=ctx,
+ ),
+ )
+ for entry in entries
+ ]
+ break
+ except Exception as exc:
+ if is_not_found_error(exc):
+ last_not_found = exc
+ continue
+ raise
+ else:
+ raise NotFoundError(uri, "directory") from last_not_found
# AGFS returns read-only structure, need to create new dict
all_entries = []
- for entry in entries:
+ for entry, entry_uri in entry_items:
if len(all_entries) >= node_limit:
break
name = entry.get("name", "")
new_entry = dict(entry) # Copy original data
- new_entry["uri"] = self._path_to_uri(f"{path}/{name}", ctx=ctx)
+ new_entry["uri"] = entry_uri
if not self._is_accessible(new_entry["uri"], real_ctx):
continue
if entry.get("isDir"):
@@ -2426,7 +2841,7 @@ class VikingFS:
) -> None:
"""Write context to AGFS (L0/L1/L2)."""
- 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 844acb8f0..fd9a18e80 100644
--- a/openviking/sync_client.py
+++ b/openviking/sync_client.py
@@ -23,8 +23,17 @@ class SyncOpenViking:
Wraps AsyncOpenViking with synchronous methods.
"""
- 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)
+ def __init__(
+ self,
+ path: Optional[str] = None,
+ actor_peer_id: Optional[str] = None,
+ agent_id: Optional[str] = None,
+ ):
+ self._async_client = AsyncOpenViking(
+ path=path,
+ actor_peer_id=actor_peer_id,
+ agent_id=agent_id,
+ )
self._initialized = False
def initialize(self) -> None:
diff --git a/openviking_cli/client/http.py b/openviking_cli/client/http.py
index ab9fef997..c290b300a 100644
--- a/openviking_cli/client/http.py
+++ b/openviking_cli/client/http.py
@@ -13,7 +13,7 @@ from typing import Any, Dict, List, Optional, Union
import httpx
-from openviking.core.peer_id import normalize_peer_id
+from openviking.core.peer_id import normalize_peer_selector
from openviking.telemetry import TelemetryRequest, normalize_telemetry_request
from openviking.utils.search_filters import SearchContextTypeInput
from openviking_cli.client.base import BaseClient
@@ -146,6 +146,7 @@ class AsyncHTTPClient(BaseClient):
account: Optional[str] = None,
user: Optional[str] = None,
actor_peer_id: Optional[str] = None,
+ agent_id: Optional[str] = None,
timeout: float = 60.0,
extra_headers: Optional[Dict[str, str]] = None,
profile_enabled: Optional[bool] = None,
@@ -159,6 +160,7 @@ class AsyncHTTPClient(BaseClient):
account: Optional account identity header for trusted deployments.
user: Optional user identity header for trusted deployments.
actor_peer_id: Optional peer actor scope header.
+ agent_id: Legacy alias for actor_peer_id.
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.
"""
@@ -169,7 +171,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 (actor_peer_id is None and agent_id is None)
or timeout == 60.0
or extra_headers is None
)
@@ -181,8 +183,9 @@ 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:
+ if actor_peer_id is None and agent_id is None:
actor_peer_id = cli_config.actor_peer_id
+ agent_id = cli_config.agent_id
if timeout == 60.0: # only override default with config value
timeout = cli_config.timeout
if extra_headers is None:
@@ -201,7 +204,10 @@ 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)
+ if actor_peer_id and agent_id:
+ raise ValueError("actor_peer_id cannot be used with legacy agent_id")
+ self._legacy_agent_id = normalize_peer_selector(None, agent_id=agent_id)
+ self._actor_peer_id = normalize_peer_selector(actor_peer_id, agent_id=agent_id)
self._user = UserIdentifier.the_default_user()
self._timeout = timeout
self._extra_headers = extra_headers
@@ -307,6 +313,31 @@ class AsyncHTTPClient(BaseClient):
return result
+ def _attach_legacy_agent_scope(self, payload: Dict[str, Any]) -> Dict[str, Any]:
+ if self._legacy_agent_id:
+ payload["agent_id"] = self._legacy_agent_id
+ return payload
+
+ def _attach_legacy_message_scope(self, payload: Dict[str, Any]) -> Dict[str, Any]:
+ if not self._legacy_agent_id:
+ return payload
+ if payload.get("peer_id") is not None:
+ raise InvalidArgumentError(
+ "peer_id cannot be used when client is configured with legacy agent_id"
+ )
+ if payload.get("role") == "assistant":
+ payload["agent_id"] = self._legacy_agent_id
+ return payload
+
+ def _batch_message_payloads(self, messages: list[dict]) -> list[dict]:
+ if not self._legacy_agent_id:
+ return messages
+ scoped_messages = []
+ for message in messages:
+ payload = dict(message)
+ scoped_messages.append(self._attach_legacy_message_scope(payload))
+ return scoped_messages
+
def _raise_exception(self, error: Dict[str, Any]) -> None:
"""Raise appropriate exception based on error code."""
code = error.get("code", "UNKNOWN")
@@ -473,7 +504,7 @@ class AsyncHTTPClient(BaseClient):
Result dict with session_id, message_count, and added count.
"""
telemetry = self._validate_telemetry(telemetry)
- payload: Dict[str, Any] = {"messages": messages}
+ payload: Dict[str, Any] = {"messages": self._batch_message_payloads(messages)}
if telemetry is not False:
payload["telemetry"] = telemetry
@@ -704,15 +735,17 @@ class AsyncHTTPClient(BaseClient):
telemetry = self._validate_telemetry(telemetry)
normalized_target = self._normalize_target_uri(target_uri)
actual_limit = node_limit if node_limit is not None else limit
- payload = {
- "query": query,
- "target_uri": normalized_target,
- "limit": actual_limit,
- "score_threshold": score_threshold,
- "filter": filter,
- "context_type": context_type,
- "telemetry": telemetry,
- }
+ payload = self._attach_legacy_agent_scope(
+ {
+ "query": query,
+ "target_uri": normalized_target,
+ "limit": actual_limit,
+ "score_threshold": score_threshold,
+ "filter": filter,
+ "context_type": context_type,
+ "telemetry": telemetry,
+ }
+ )
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 {})
@@ -735,16 +768,18 @@ class AsyncHTTPClient(BaseClient):
normalized_target = self._normalize_target_uri(target_uri)
actual_limit = node_limit if node_limit is not None else limit
sid = session_id or (session.session_id if session else None)
- payload = {
- "query": query,
- "target_uri": normalized_target,
- "session_id": sid,
- "limit": actual_limit,
- "score_threshold": score_threshold,
- "filter": filter,
- "context_type": context_type,
- "telemetry": telemetry,
- }
+ payload = self._attach_legacy_agent_scope(
+ {
+ "query": query,
+ "target_uri": normalized_target,
+ "session_id": sid,
+ "limit": actual_limit,
+ "score_threshold": score_threshold,
+ "filter": filter,
+ "context_type": context_type,
+ "telemetry": telemetry,
+ }
+ )
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 {})
@@ -953,6 +988,7 @@ class AsyncHTTPClient(BaseClient):
payload["peer_id"] = peer_id
if telemetry is not False:
payload["telemetry"] = telemetry
+ payload = self._attach_legacy_message_scope(payload)
response = await self._http.post(
f"/api/v1/sessions/{session_id}/messages",
@@ -1206,6 +1242,12 @@ class AsyncHTTPClient(BaseClient):
)
return self._handle_response(response)
+ async def admin_migrate(self, cleanup: bool = False) -> Dict[str, Any]:
+ """Start legacy data migration or legacy namespace cleanup."""
+ action = "cleanup" if cleanup else "migrate"
+ response = await self._http.post("/api/v1/admin/migrate", json={"action": action})
+ return self._handle_response(response)
+
# ============= New methods for BaseClient interface =============
def session(self, session_id: Optional[str] = None, must_exist: bool = False) -> Any:
diff --git a/openviking_cli/client/sync_http.py b/openviking_cli/client/sync_http.py
index 8bd1047a5..4c2482cb0 100644
--- a/openviking_cli/client/sync_http.py
+++ b/openviking_cli/client/sync_http.py
@@ -37,6 +37,7 @@ class SyncHTTPClient:
account: Optional[str] = None,
user: Optional[str] = None,
actor_peer_id: Optional[str] = None,
+ agent_id: Optional[str] = None,
timeout: float = 60.0,
extra_headers: Optional[Dict[str, str]] = None,
profile_enabled: Optional[bool] = None,
@@ -48,6 +49,7 @@ class SyncHTTPClient:
account=account,
user=user,
actor_peer_id=actor_peer_id,
+ agent_id=agent_id,
timeout=timeout,
extra_headers=extra_headers,
profile_enabled=profile_enabled,
@@ -553,6 +555,10 @@ class SyncHTTPClient:
"""Regenerate a user's API key. Old key is immediately invalidated."""
return run_async(self._async_client.admin_regenerate_key(account_id, user_id))
+ def admin_migrate(self, cleanup: bool = False) -> Dict[str, Any]:
+ """Start legacy data migration or legacy namespace cleanup."""
+ return run_async(self._async_client.admin_migrate(cleanup=cleanup))
+
# ============= Debug =============
def health(self) -> bool:
diff --git a/openviking_cli/utils/config/ovcli_config.py b/openviking_cli/utils/config/ovcli_config.py
index c33e8fcc8..5461418d7 100644
--- a/openviking_cli/utils/config/ovcli_config.py
+++ b/openviking_cli/utils/config/ovcli_config.py
@@ -31,6 +31,7 @@ class OVCLIConfig(BaseModel):
account: Optional[str] = None
user: Optional[str] = None
actor_peer_id: Optional[str] = None
+ agent_id: Optional[str] = None
timeout: float = 60.0
profile: bool = False
upload: Optional[OVCLIUploadConfig] = None
@@ -49,6 +50,12 @@ class OVCLIConfig(BaseModel):
data["extra_headers"] = extra_header
return data
+ @model_validator(mode="after")
+ def reject_mixed_actor_and_agent_identity(self) -> "OVCLIConfig":
+ if self.actor_peer_id is not None and self.agent_id is not None:
+ raise ValueError("actor_peer_id cannot be used with legacy agent_id")
+ return self
+
def load_ovcli_config(config_path: Optional[str] = None) -> Optional[OVCLIConfig]:
"""Load ovcli.conf if present and validate it strictly."""
diff --git a/openviking_cli/utils/uri.py b/openviking_cli/utils/uri.py
index eefdeb6cd..aac1a1858 100644
--- a/openviking_cli/utils/uri.py
+++ b/openviking_cli/utils/uri.py
@@ -22,6 +22,7 @@ class VikingURI:
- user: User scope (viking://user/...), including sessions under
viking://user/{user_id}/sessions/{session_id}
- session: Legacy alias for user sessions (viking://session/{session_id}/...)
+ - agent: Legacy read-only agent scope (viking://agent/{agent_id}/...)
- queue: Queue scope (viking://queue/...)
Examples:
@@ -38,7 +39,7 @@ class VikingURI:
"user",
}
PUBLIC_SCOPES = frozenset(LISTABLE_SCOPES)
- LEGACY_SCOPES = frozenset({"session"})
+ LEGACY_SCOPES = frozenset({"agent", "session"})
INTERNAL_SCOPES = frozenset({"temp", "queue", "upload"})
# All valid scopes that can be addressed by the URI parser/storage internals.
# Public API handlers must not use this as their external whitelist.
diff --git a/tests/client/test_http_client_config.py b/tests/client/test_http_client_config.py
index 617776c8a..65f4a596f 100644
--- a/tests/client/test_http_client_config.py
+++ b/tests/client/test_http_client_config.py
@@ -7,6 +7,7 @@ import httpx
import pytest
from openviking_cli.client.http import AsyncHTTPClient
+from openviking_cli.exceptions import InvalidArgumentError
from openviking_cli.retrieve.types import ContextType
from openviking_cli.utils.config import OPENVIKING_CLI_CONFIG_ENV
@@ -89,6 +90,42 @@ def test_async_http_client_explicit_values_override_ovcli_config(tmp_path, monke
assert client._profile_enabled is False
+def test_async_http_client_loads_agent_id_from_ovcli_config(tmp_path, monkeypatch):
+ config_path = tmp_path / "ovcli.conf"
+ config_path.write_text(
+ json.dumps(
+ {
+ "url": "http://config-host:1933",
+ "api_key": "config-key",
+ "agent_id": "legacy-agent",
+ }
+ )
+ )
+ monkeypatch.setenv(OPENVIKING_CLI_CONFIG_ENV, str(config_path))
+
+ client = AsyncHTTPClient()
+
+ assert client._actor_peer_id == "legacy-agent"
+ assert client._legacy_agent_id == "legacy-agent"
+
+
+def test_async_http_client_rejects_mixed_config_agent_and_actor_peer(tmp_path, monkeypatch):
+ config_path = tmp_path / "ovcli.conf"
+ config_path.write_text(
+ json.dumps(
+ {
+ "url": "http://config-host:1933",
+ "actor_peer_id": "actor-a",
+ "agent_id": "legacy-agent",
+ }
+ )
+ )
+ monkeypatch.setenv(OPENVIKING_CLI_CONFIG_ENV, str(config_path))
+
+ with pytest.raises(ValueError, match="actor_peer_id cannot be used with legacy agent_id"):
+ AsyncHTTPClient()
+
+
@pytest.mark.asyncio
async def test_async_http_client_omits_identity_headers_when_unconfigured(tmp_path, monkeypatch):
captured: dict[str, object] = {}
@@ -149,6 +186,31 @@ async def test_async_http_client_sends_configured_identity_headers(tmp_path, mon
}
+async def test_async_http_client_sends_agent_id_as_actor_peer_header(tmp_path, monkeypatch):
+ captured: dict[str, object] = {}
+ config_path = tmp_path / "ovcli.conf"
+ config_path.write_text("{}")
+ monkeypatch.setenv(OPENVIKING_CLI_CONFIG_ENV, str(config_path))
+
+ class FakeAsyncClient:
+ def __init__(self, **kwargs):
+ captured.update(kwargs)
+
+ monkeypatch.setattr("openviking_cli.client.http.httpx.AsyncClient", FakeAsyncClient)
+
+ client = AsyncHTTPClient(
+ url="http://explicit-host:1933",
+ api_key="explicit-key",
+ agent_id="legacy-agent",
+ timeout=33.0,
+ extra_headers={},
+ )
+ await client.initialize()
+
+ assert captured["headers"]["X-OpenViking-Actor-Peer"] == "legacy-agent"
+
+
def test_async_http_client_rejects_unknown_ovcli_field(tmp_path, monkeypatch):
config_path = tmp_path / "ovcli.conf"
config_path.write_text(json.dumps({"ur": "http://localhost:1933"}))
@@ -334,6 +396,26 @@ async def test_async_http_client_find_does_not_send_peer_id(tmp_path, monkeypatc
]
+async def test_async_http_client_legacy_agent_find_sends_agent_id(tmp_path, monkeypatch):
+ config_path = tmp_path / "ovcli.conf"
+ config_path.write_text("{}")
+ monkeypatch.setenv(OPENVIKING_CLI_CONFIG_ENV, str(config_path))
+
+ http = FakeSearchHTTP()
+ client = AsyncHTTPClient(
+ url="http://explicit-host:1933",
+ api_key="key",
+ agent_id="legacy-agent",
+ )
+ client._http = http
+
+ await client.find("invoice")
+
+ assert http.calls[0][1]["agent_id"] == "legacy-agent"
+ assert "peer_id" not in http.calls[0][1]
+
+
@pytest.mark.asyncio
async def test_async_http_client_search_does_not_send_peer_id(tmp_path, monkeypatch):
config_path = tmp_path / "ovcli.conf"
@@ -367,6 +449,60 @@ async def test_async_http_client_search_does_not_send_peer_id(tmp_path, monkeypa
]
+async def test_async_http_client_legacy_agent_add_message_sends_agent_id_for_assistant(
+ tmp_path,
+ monkeypatch,
+):
+ config_path = tmp_path / "ovcli.conf"
+ config_path.write_text("{}")
+ monkeypatch.setenv(OPENVIKING_CLI_CONFIG_ENV, str(config_path))
+
+ http = FakeSearchHTTP()
+ client = AsyncHTTPClient(
+ url="http://explicit-host:1933",
+ api_key="key",
+ agent_id="legacy-agent",
+ )
+ client._http = http
+
+ await client.add_message("session-1", "assistant", content="hello")
+ await client.add_message("session-1", "user", content="hi")
+
+ assert http.calls[0] == (
+ "/api/v1/sessions/session-1/messages",
+ {"role": "assistant", "content": "hello", "agent_id": "legacy-agent"},
+ )
+ assert http.calls[1] == (
+ "/api/v1/sessions/session-1/messages",
+ {"role": "user", "content": "hi"},
+ )
+
+
+async def test_async_http_client_legacy_agent_add_message_rejects_peer_id(tmp_path, monkeypatch):
+ config_path = tmp_path / "ovcli.conf"
+ config_path.write_text("{}")
+ monkeypatch.setenv(OPENVIKING_CLI_CONFIG_ENV, str(config_path))
+
+ http = FakeSearchHTTP()
+ client = AsyncHTTPClient(
+ url="http://explicit-host:1933",
+ api_key="key",
+ agent_id="legacy-agent",
+ )
+ client._http = http
+
+ with pytest.raises(InvalidArgumentError, match="peer_id cannot be used"):
+ await client.add_message(
+ "session-1",
+ "assistant",
+ content="hello",
+ peer_id="legacy-agent",
+ )
+ assert http.calls == []
+
+
@pytest.mark.asyncio
async def test_async_http_client_find_sends_context_type(tmp_path, monkeypatch):
config_path = tmp_path / "ovcli.conf"
diff --git a/tests/client/test_lifecycle.py b/tests/client/test_lifecycle.py
index 93e4472a6..5d3d29df4 100644
--- a/tests/client/test_lifecycle.py
+++ b/tests/client/test_lifecycle.py
@@ -5,7 +5,10 @@
from pathlib import Path
+import pytest
+
from openviking import AsyncOpenViking
+from openviking_cli.exceptions import InvalidArgumentError
class TestClientInitialization:
@@ -27,6 +30,61 @@ class TestClientInitialization:
await uninitialized_client.initialize()
assert uninitialized_client._client is not None
+ async def test_agent_id_alias_sets_actor_peer_scope(self, test_data_dir: Path):
+ await AsyncOpenViking.reset()
+
+ client = AsyncOpenViking(path=str(test_data_dir), agent_id="legacy-agent")
+
+ assert client._client._ctx.actor_peer_id == "legacy-agent"
+ assert client._client._ctx.legacy_agent_id == "legacy-agent"
+
+ await AsyncOpenViking.reset()
+
+ async def test_agent_id_alias_must_match_actor_peer_id(self, test_data_dir: Path):
+ await AsyncOpenViking.reset()
+
+ try:
+ try:
+ AsyncOpenViking(
+ path=str(test_data_dir),
+ actor_peer_id="actor-a",
+ agent_id="actor-b",
+ )
+ except ValueError as exc:
+ assert "actor_peer_id cannot be used with legacy agent_id" in str(exc)
+ else:
+ raise AssertionError("mismatched agent_id should fail")
+ finally:
+ await AsyncOpenViking.reset()
+
+ async def test_agent_id_alias_tags_assistant_messages_only(self, test_data_dir: Path):
+ await AsyncOpenViking.reset()
+
+ client = AsyncOpenViking(path=str(test_data_dir), agent_id="legacy-agent")
+ try:
+ await client.add_message("legacy-session", "user", content="hi")
+ await client.add_message("legacy-session", "assistant", content="hello")
+
+ session = await client._client._service.sessions.get(
+ "legacy-session",
+ client._client._ctx,
+ auto_create=False,
+ )
+ assert [message.peer_id for message in session.messages] == [
+ None,
+ "legacy-agent",
+ ]
+
+ with pytest.raises(InvalidArgumentError, match="peer_id cannot be used"):
+ await client.add_message(
+ "legacy-session",
+ "assistant",
+ content="again",
+ peer_id="legacy-agent",
+ )
+ finally:
+ await AsyncOpenViking.reset()
+
class TestClientClose:
"""Test Client close"""
diff --git a/tests/server/test_actor_peer_retrieval_targets.py b/tests/server/test_actor_peer_retrieval_targets.py
index 5d5a18e86..e09f8a604 100644
--- a/tests/server/test_actor_peer_retrieval_targets.py
+++ b/tests/server/test_actor_peer_retrieval_targets.py
@@ -17,16 +17,27 @@ 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:
+def _ctx(
+ actor_peer_id: str | None = None,
+ legacy_agent_id: str | None = None,
+) -> RequestContext:
return RequestContext(
user=UserIdentifier("acct", "support_bot"),
role=Role.USER,
actor_peer_id=actor_peer_id,
+ legacy_agent_id=legacy_agent_id,
)
-def _target_dirs(target_uri="", actor_peer_id: str | None = None):
- return resolve_retrieval_targets(target_uri, _ctx(actor_peer_id)).target_directories
+def _target_dirs(
+ target_uri="",
+ actor_peer_id: str | None = None,
+ legacy_agent_id: str | None = None,
+):
+ return resolve_retrieval_targets(
+ target_uri,
+ _ctx(actor_peer_id, legacy_agent_id),
+ ).target_directories
def test_owner_default_search_targets_owner_memory_resources_and_skills():
@@ -51,6 +62,25 @@ def test_actor_default_search_keeps_user_view_and_filters_peer_collection():
]
+def test_legacy_agent_default_search_includes_unmigrated_agent_context():
+ targets = _target_dirs(
+ actor_peer_id="web-visitor-alice",
+ legacy_agent_id="web-visitor-alice",
+ )
+
+ assert targets == [
+ "viking://resources",
+ "viking://user/support_bot/memories",
+ "viking://user/support_bot/resources",
+ "viking://user/support_bot/skills",
+ "viking://user/support_bot/peers/web-visitor-alice/memories",
+ "viking://user/support_bot/peers/web-visitor-alice/resources",
+ "viking://agent/web-visitor-alice/memories",
+ "viking://agent/web-visitor-alice/resources",
+ "viking://agent/web-visitor-alice/skills",
+ ]
+
+
def test_actor_search_keeps_explicit_resource_target():
targets = _target_dirs("viking://resources/docs", actor_peer_id="web-visitor-alice")
@@ -78,6 +108,17 @@ def test_actor_default_memory_targets_actor_peer_memory():
]
+def test_legacy_agent_default_memory_targets_unmigrated_agent_memory():
+ assert default_target_directories(
+ _ctx("web-visitor-alice", legacy_agent_id="web-visitor-alice"),
+ context_type=ContextType.MEMORY,
+ ) == [
+ "viking://user/support_bot/memories",
+ "viking://user/support_bot/peers/web-visitor-alice/memories",
+ "viking://agent/web-visitor-alice/memories",
+ ]
+
+
def test_actor_skill_defaults_keep_user_skills():
assert default_target_directories(
_ctx("web-visitor-alice"), context_type=ContextType.SKILL
@@ -132,6 +173,32 @@ def test_actor_explicit_other_peer_memory_target_is_denied():
)
+def test_explicit_legacy_agent_memory_target_includes_migrated_peer_memory():
+ targets = _target_dirs("viking://agent/web-visitor-alice/memories")
+
+ assert targets == [
+ "viking://agent/web-visitor-alice/memories",
+ "viking://user/support_bot/peers/web-visitor-alice/memories",
+ ]
+
+
+def test_explicit_legacy_agent_skill_target_includes_migrated_user_skills():
+ targets = _target_dirs("viking://agent/web-visitor-alice/skills")
+
+ assert targets == [
+ "viking://agent/web-visitor-alice/skills",
+ "viking://user/support_bot/skills",
+ ]
+
+
+def test_actor_explicit_other_legacy_agent_target_is_denied():
+ with pytest.raises(PermissionDeniedError, match="another legacy agent"):
+ _target_dirs(
+ "viking://agent/web-visitor-bob/memories",
+ actor_peer_id="web-visitor-alice",
+ )
+
+
def test_owner_peer_collection_targets_all_peer_contexts():
assert _target_dirs("viking://user/support_bot/peers") == [
"viking://user/support_bot/peers",
diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.py
index 62e5c4e42..3a7edec2e 100644
--- a/tests/server/test_admin_api.py
+++ b/tests/server/test_admin_api.py
@@ -3,9 +3,12 @@
"""Tests for Admin API endpoints (openviking/server/routers/admin.py)."""
+import asyncio
+import json
import uuid
import httpx
+import pytest
import pytest_asyncio
from fastapi import FastAPI
from fastapi import Request as FastAPIRequest
@@ -19,7 +22,11 @@ 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
+from openviking.service.task_store import (
+ SYSTEM_TASK_ACCOUNT_ID,
+ SYSTEM_TASK_USER_ID,
+)
+from openviking_cli.exceptions import OpenVikingError, PermissionDeniedError
from openviking_cli.session.user_id import UserIdentifier
@@ -41,11 +48,21 @@ class _FakeAGFS:
return self._files[path]
def write(self, path, content, **_kwargs):
+ self.ensure_parent_dirs(path)
self._files[path] = content
def mkdir(self, path, **_kwargs):
self._dirs.add(path)
+ def ensure_parent_dirs(self, path, **_kwargs):
+ parent = path.rsplit("/", 1)[0]
+ if not parent:
+ return
+ current = ""
+ for part in [part for part in parent.strip("/").split("/") if part]:
+ current = f"{current}/{part}" if current else f"/{part}"
+ self._dirs.add(current)
+
class _FakeVikingFS:
def __init__(self):
@@ -151,6 +168,49 @@ def trusted_headers(
return headers
+async def _agfs_exists(service: OpenVikingService, path: str) -> bool:
+ try:
+ await service.viking_fs._async_agfs.stat(path)
+ except Exception:
+ return False
+ return True
+
+
+async def _agfs_mkdirp(service: OpenVikingService, path: str) -> None:
+ parts = [part for part in path.strip("/").split("/") if part]
+ current = ""
+ for part in parts:
+ current = f"{current}/{part}" if current else f"/{part}"
+ if await _agfs_exists(service, current):
+ continue
+ await service.viking_fs._async_agfs.mkdir(current)
+
+
+async def _agfs_write(service: OpenVikingService, path: str, content: str) -> None:
+ await _agfs_mkdirp(service, path.rsplit("/", 1)[0])
+ await service.viking_fs._async_agfs.write(path, content.encode("utf-8"))
+
+
+async def _agfs_read_text(service: OpenVikingService, path: str) -> str:
+ raw = await service.viking_fs._async_agfs.read(path)
+ if isinstance(raw, bytes):
+ return raw.decode("utf-8")
+ if hasattr(raw, "content"):
+ return raw.content.decode("utf-8")
+ return str(raw)
+
+
+async def _wait_for_task(client: httpx.AsyncClient, task_id: str) -> dict:
+ for _ in range(100):
+ resp = await client.get(f"/api/v1/tasks/{task_id}", headers=root_headers())
+ assert resp.status_code == 200
+ task = resp.json()["result"]
+ if task["status"] in {"completed", "failed"}:
+ return task
+ await asyncio.sleep(0.01)
+ raise AssertionError(f"Task {task_id} did not finish")
+
+
# ---- Account CRUD ----
@@ -566,6 +626,413 @@ async def test_no_auth_admin_api_returns_401(admin_client: httpx.AsyncClient):
assert resp.status_code == 401
+# ---- Legacy migration ----
+
+
+async def test_user_role_cannot_run_legacy_migration(admin_client: httpx.AsyncClient):
+ """Legacy migration is ROOT-only."""
+ acct = _uid()
+ await admin_client.post(
+ "/api/v1/admin/accounts",
+ json={"account_id": acct, "admin_user_id": "alice"},
+ headers=root_headers(),
+ )
+ resp = await admin_client.post(
+ f"/api/v1/admin/accounts/{acct}/users",
+ json={"user_id": "bob", "role": "user"},
+ headers=root_headers(),
+ )
+ bob_key = resp.json()["result"]["user_key"]
+
+ resp = await admin_client.post(
+ "/api/v1/admin/migrate",
+ headers={"X-API-Key": bob_key},
+ )
+ assert resp.status_code == 403
+
+
+async def test_legacy_migration_preflight_failure_does_not_create_task(
+ admin_client: httpx.AsyncClient,
+ admin_service: OpenVikingService,
+):
+ """Ambiguous session ownership fails preflight before task creation."""
+ acct = _uid()
+ await admin_client.post(
+ "/api/v1/admin/accounts",
+ json={"account_id": acct, "admin_user_id": "alice"},
+ headers=root_headers(),
+ )
+ await admin_client.post(
+ f"/api/v1/admin/accounts/{acct}/users",
+ json={"user_id": "bob", "role": "user"},
+ headers=root_headers(),
+ )
+ await _agfs_write(admin_service, f"/local/{acct}/session/orphan/messages.jsonl", "{}\n")
+
+ resp = await admin_client.post("/api/v1/admin/migrate", headers=root_headers())
+ assert resp.status_code == 412
+ error = resp.json()["error"]
+ assert error["code"] == "FAILED_PRECONDITION"
+ assert error["details"]["operation_count"] == 0
+ assert error["details"]["errors"][0]["session_id"] == "orphan"
+
+ tasks_resp = await admin_client.get(
+ "/api/v1/tasks?task_type=legacy_migration",
+ headers=root_headers(),
+ )
+ assert tasks_resp.status_code == 200
+ assert tasks_resp.json()["result"] == []
+
+
+async def test_legacy_migration_task_migrates_legacy_data(
+ admin_client: httpx.AsyncClient,
+ admin_app,
+ admin_service: OpenVikingService,
+):
+ """ROOT migrate fans out shared agent data and moves sessions under users."""
+ acct = _uid()
+ await admin_client.post(
+ "/api/v1/admin/accounts",
+ json={"account_id": acct, "admin_user_id": "alice"},
+ headers=root_headers(),
+ )
+ register_bob = await admin_client.post(
+ f"/api/v1/admin/accounts/{acct}/users",
+ json={"user_id": "bob", "role": "user"},
+ headers=root_headers(),
+ )
+ bob_key = register_bob.json()["result"]["user_key"]
+
+ await _agfs_write(
+ admin_service,
+ f"/local/{acct}/agent/code-agent/memories/facts/project.md",
+ "shared fact",
+ )
+ await _agfs_write(
+ admin_service,
+ f"/local/{acct}/agent/code-agent/skills/code-review/SKILL.md",
+ "legacy skill",
+ )
+ await _agfs_write(
+ admin_service,
+ f"/local/{acct}/agent/code-agent/instructions/system.md",
+ "do not migrate",
+ )
+ await _agfs_write(
+ admin_service,
+ f"/local/{acct}/user/bob/skills/code-review/SKILL.md",
+ "existing skill",
+ )
+ await _agfs_write(
+ admin_service,
+ f"/local/{acct}/session/sess-001/.meta.json",
+ json.dumps({"created_by_user_id": "alice"}),
+ )
+ await _agfs_write(
+ admin_service,
+ f"/local/{acct}/session/sess-001/messages.jsonl",
+ '{"role":"user"}\n',
+ )
+ await _agfs_write(
+ admin_service,
+ f"/local/{acct}/session/sess-002/.meta.json",
+ json.dumps({"user_id": "charlie"}),
+ )
+ await _agfs_write(
+ admin_service,
+ f"/local/{acct}/session/sess-002/messages.jsonl",
+ '{"role":"assistant"}\n',
+ )
+
+ resp = await admin_client.post("/api/v1/admin/migrate", headers=root_headers())
+ assert resp.status_code == 200
+ task_id = resp.json()["result"]["task_id"]
+ assert await _agfs_exists(
+ admin_service,
+ f"/local/{SYSTEM_TASK_ACCOUNT_ID}/tasks/{SYSTEM_TASK_USER_ID}/{task_id}.json",
+ )
+ hidden_resp = await admin_client.get(f"/api/v1/tasks/{task_id}", headers={"X-API-Key": bob_key})
+ assert hidden_resp.status_code == 404
+
+ task = await _wait_for_task(admin_client, task_id)
+ assert task["status"] == "completed"
+ result = task["result"]
+ created_user = next(item for item in result["created_users"] if item["user_id"] == "charlie")
+ assert created_user["account_id"] == acct
+ assert "user_key" not in created_user
+ assert result["migrated"]["operations"]["agent_memories"] == 3
+ assert result["migrated"]["operations"]["agent_skills"] == 2
+ assert result["migrated"]["operations"]["sessions"] == 2
+ assert any(item["reason"] == "target skill already exists" for item in result["skipped"])
+ assert any("Skipped legacy instructions" in item for item in result["warnings"])
+
+ manager = admin_app.state.api_key_manager
+ assert manager.has_user(acct, "charlie")
+ for user_id in ("alice", "bob", "charlie"):
+ assert (
+ await _agfs_read_text(
+ admin_service,
+ f"/local/{acct}/user/{user_id}/peers/code-agent/memories/facts/project.md",
+ )
+ == "shared fact"
+ )
+ assert (
+ await _agfs_read_text(
+ admin_service,
+ f"/local/{acct}/user/alice/skills/code-review/SKILL.md",
+ )
+ == "legacy skill"
+ )
+ assert (
+ await _agfs_read_text(
+ admin_service,
+ f"/local/{acct}/user/bob/skills/code-review/SKILL.md",
+ )
+ == "existing skill"
+ )
+ assert (
+ await _agfs_read_text(
+ admin_service,
+ f"/local/{acct}/user/alice/sessions/sess-001/messages.jsonl",
+ )
+ == '{"role":"user"}\n'
+ )
+ assert (
+ await _agfs_read_text(
+ admin_service,
+ f"/local/{acct}/user/charlie/sessions/sess-002/messages.jsonl",
+ )
+ == '{"role":"assistant"}\n'
+ )
+ assert not await _agfs_exists(
+ admin_service,
+ f"/local/{acct}/user/alice/peers/code-agent/instructions/system.md",
+ )
+
+
+async def test_legacy_migration_covers_all_accounts_and_agent_user_layout(
+ admin_client: httpx.AsyncClient,
+ admin_app,
+ admin_service: OpenVikingService,
+):
+ """One ROOT migration scans all accounts and handles agent/user scoped legacy data."""
+ acct = _uid()
+ other_acct = _uid()
+ await admin_client.post(
+ "/api/v1/admin/accounts",
+ json={"account_id": acct, "admin_user_id": "admin"},
+ headers=root_headers(),
+ )
+ await admin_client.post(
+ "/api/v1/admin/accounts",
+ json={"account_id": other_acct, "admin_user_id": "dana"},
+ headers=root_headers(),
+ )
+ await _agfs_write(
+ admin_service,
+ f"/local/{acct}/user/charlie/memories/.overview.md",
+ "legacy physical user",
+ )
+ await _agfs_write(
+ admin_service,
+ f"/local/{acct}/agent/code-agent/memories/facts/shared.md",
+ "shared fact",
+ )
+ await _agfs_write(
+ admin_service,
+ f"/local/{acct}/agent/review-agent/user/charlie/memories/facts/private.md",
+ "private fact",
+ )
+ await _agfs_write(
+ admin_service,
+ f"/local/{acct}/agent/review-agent/user/charlie/skills/review/SKILL.md",
+ "review skill",
+ )
+ await _agfs_write(
+ admin_service,
+ f"/local/{other_acct}/agent/code-agent/memories/facts/other.md",
+ "other account fact",
+ )
+
+ resp = await admin_client.post("/api/v1/admin/migrate", headers=root_headers())
+ assert resp.status_code == 200
+ task = await _wait_for_task(admin_client, resp.json()["result"]["task_id"])
+ assert task["status"] == "completed"
+
+ result = task["result"]
+ assert any(
+ item["account_id"] == acct and item["user_id"] == "charlie"
+ for item in result["created_users"]
+ )
+ manager = admin_app.state.api_key_manager
+ assert manager.has_user(acct, "charlie")
+ assert (
+ await _agfs_read_text(
+ admin_service,
+ f"/local/{acct}/user/admin/peers/code-agent/memories/facts/shared.md",
+ )
+ == "shared fact"
+ )
+ assert (
+ await _agfs_read_text(
+ admin_service,
+ f"/local/{acct}/user/charlie/peers/code-agent/memories/facts/shared.md",
+ )
+ == "shared fact"
+ )
+ assert (
+ await _agfs_read_text(
+ admin_service,
+ f"/local/{acct}/user/charlie/peers/review-agent/memories/facts/private.md",
+ )
+ == "private fact"
+ )
+ assert (
+ await _agfs_read_text(
+ admin_service,
+ f"/local/{acct}/user/charlie/skills/review/SKILL.md",
+ )
+ == "review skill"
+ )
+ assert not await _agfs_exists(
+ admin_service,
+ f"/local/{acct}/user/admin/peers/review-agent/memories/facts/private.md",
+ )
+ assert (
+ await _agfs_read_text(
+ admin_service,
+ f"/local/{other_acct}/user/dana/peers/code-agent/memories/facts/other.md",
+ )
+ == "other account fact"
+ )
+
+
+async def test_legacy_cleanup_removes_only_legacy_namespaces(
+ admin_client: httpx.AsyncClient,
+ admin_service: OpenVikingService,
+):
+ """Cleanup removes legacy agent/session roots without deleting migrated user data."""
+ acct = _uid()
+ other_acct = _uid()
+ await admin_client.post(
+ "/api/v1/admin/accounts",
+ json={"account_id": acct, "admin_user_id": "alice"},
+ headers=root_headers(),
+ )
+ await admin_client.post(
+ "/api/v1/admin/accounts",
+ json={"account_id": other_acct, "admin_user_id": "dana"},
+ headers=root_headers(),
+ )
+ await _agfs_write(
+ admin_service,
+ f"/local/{acct}/agent/code-agent/memories/facts/old.md",
+ "legacy agent",
+ )
+ await _agfs_write(
+ admin_service,
+ f"/local/{acct}/session/sess-001/messages.jsonl",
+ '{"role":"user"}\n',
+ )
+ await _agfs_write(
+ admin_service,
+ f"/local/{acct}/user/alice/agent/review-agent/memories/facts/old.md",
+ "legacy user agent",
+ )
+ await _agfs_write(
+ admin_service,
+ f"/local/{acct}/user/alice/peers/code-agent/memories/facts/new.md",
+ "new peer data",
+ )
+ await _agfs_write(
+ admin_service,
+ f"/local/{acct}/user/alice/sessions/sess-001/messages.jsonl",
+ '{"role":"assistant"}\n',
+ )
+ await _agfs_write(
+ admin_service,
+ f"/local/{other_acct}/agent/code-agent/memories/facts/old.md",
+ "other legacy agent",
+ )
+
+ resp = await admin_client.post(
+ "/api/v1/admin/migrate",
+ json={"action": "cleanup"},
+ headers=root_headers(),
+ )
+ assert resp.status_code == 200
+ task = await _wait_for_task(admin_client, resp.json()["result"]["task_id"])
+ assert task["status"] == "completed"
+ assert task["task_type"] == "legacy_cleanup"
+ assert task["result"]["cleanup"]["directories"] == 4
+ removed = {
+ (item["account_id"], item["source"]) for item in task["result"]["cleanup"]["targets"]
+ }
+ assert (acct, "viking://agent") in removed
+ assert (acct, "viking://session") in removed
+ assert (acct, "viking://user/alice/agent") in removed
+ assert (other_acct, "viking://agent") in removed
+
+ assert not await _agfs_exists(admin_service, f"/local/{acct}/agent")
+ assert not await _agfs_exists(admin_service, f"/local/{acct}/session")
+ assert not await _agfs_exists(admin_service, f"/local/{acct}/user/alice/agent")
+ assert not await _agfs_exists(admin_service, f"/local/{other_acct}/agent")
+ assert (
+ await _agfs_read_text(
+ admin_service,
+ f"/local/{acct}/user/alice/peers/code-agent/memories/facts/new.md",
+ )
+ == "new peer data"
+ )
+ assert (
+ await _agfs_read_text(
+ admin_service,
+ f"/local/{acct}/user/alice/sessions/sess-001/messages.jsonl",
+ )
+ == '{"role":"assistant"}\n'
+ )
+
+
+async def test_legacy_agent_and_session_uri_reads_are_read_only(
+ admin_service: OpenVikingService,
+):
+ """Old agent/session URIs remain readable but not mutable."""
+ ctx = RequestContext(user=UserIdentifier("default", "admin_user"), role=Role.USER)
+ await _agfs_write(
+ admin_service,
+ "/local/default/agent/code-agent/memories/facts/project.md",
+ "legacy agent fact",
+ )
+ await _agfs_write(
+ admin_service,
+ "/local/default/session/old-session/messages.jsonl",
+ '{"role":"user"}\n',
+ )
+
+ assert (
+ await admin_service.viking_fs.read_file(
+ "viking://agent/code-agent/memories/facts/project.md",
+ ctx=ctx,
+ )
+ == "legacy agent fact"
+ )
+ assert (
+ await admin_service.viking_fs.read_file(
+ "viking://session/old-session/messages.jsonl",
+ ctx=ctx,
+ )
+ == '{"role":"user"}\n'
+ )
+ with pytest.raises(PermissionDeniedError):
+ await admin_service.viking_fs.write_file(
+ "viking://agent/code-agent/memories/facts/new.md",
+ "blocked",
+ ctx=ctx,
+ )
+ with pytest.raises(PermissionDeniedError):
+ await admin_service.viking_fs.mkdir("viking://session/new-session", ctx=ctx)
+
+
@pytest_asyncio.fixture(scope="function")
async def trusted_admin_app(admin_service):
config = ServerConfig(auth_mode="trusted", root_api_key=ROOT_KEY)
diff --git a/tests/server/test_peer_id_compat.py b/tests/server/test_peer_id_compat.py
new file mode 100644
index 000000000..8321bed05
--- /dev/null
+++ b/tests/server/test_peer_id_compat.py
@@ -0,0 +1,93 @@
+# 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_selector,
+)
+from openviking.server.identity import RequestContext, Role
+from openviking.server.routers.search import (
+ FindRequest,
+ SearchRequest,
+ _ctx_with_legacy_actor_peer,
+)
+from openviking.server.routers.sessions import AddMessageRequest
+from openviking_cli.exceptions import InvalidArgumentError
+from openviking_cli.session.user_id import UserIdentifier
+
+
+def test_normalize_peer_selector_accepts_legacy_agent_uri():
+ assert normalize_peer_selector(None, agent_uri="viking://agent/code-agent/skills") == (
+ "code-agent"
+ )
+
+
+def test_normalize_peer_selector_rejects_peer_id_with_legacy_agent_id():
+ with pytest.raises(ValueError, match="peer_id cannot be used"):
+ normalize_peer_selector("review-agent", agent_id="code-agent")
+
+
+def test_normalize_peer_selector_rejects_mismatched_agent_id_and_uri():
+ with pytest.raises(ValueError, match="legacy agent_id must match agent_uri"):
+ normalize_peer_selector(
+ None,
+ agent_id="code-agent",
+ agent_uri="viking://agent/review-agent/skills",
+ )
+
+
+def test_search_request_maps_legacy_agent_uri_to_agent_id():
+ request = SearchRequest.model_validate(
+ {"query": "invoice", "agent_uri": "viking://agent/code-agent/skills"}
+ )
+
+ assert request.agent_id == "code-agent"
+
+
+def test_find_request_rejects_unpublished_peer_id_body_field():
+ with pytest.raises(ValueError):
+ FindRequest.model_validate({"query": "invoice", "peer_id": "code-agent"})
+
+
+def test_add_message_request_maps_legacy_agent_id_to_peer_id():
+ request = AddMessageRequest.model_validate(
+ {"role": "assistant", "content": "hello", "agent_id": "code-agent"}
+ )
+
+ assert request.peer_id == "code-agent"
+
+
+def test_add_message_request_rejects_peer_id_with_legacy_agent_id():
+ with pytest.raises(ValueError, match="peer_id cannot be used"):
+ AddMessageRequest.model_validate(
+ {
+ "role": "assistant",
+ "content": "hello",
+ "peer_id": "code-agent",
+ "agent_id": "code-agent",
+ }
+ )
+
+
+def test_legacy_search_peer_sets_actor_peer_context():
+ ctx = RequestContext(user=UserIdentifier("acct", "alice"), role=Role.USER)
+
+ scoped = _ctx_with_legacy_actor_peer(ctx, "code-agent")
+
+ assert scoped.actor_peer_id == "code-agent"
+ assert scoped.legacy_agent_id == "code-agent"
+ assert ctx.actor_peer_id is None
+
+
+def test_legacy_search_peer_must_match_actor_peer_context():
+ ctx = RequestContext(
+ user=UserIdentifier("acct", "alice"),
+ role=Role.USER,
+ actor_peer_id="actor-a",
+ )
+
+ with pytest.raises(InvalidArgumentError, match="actor_peer_id cannot be used"):
+ _ctx_with_legacy_actor_peer(ctx, "actor-b")
diff --git a/tests/service/test_session_service_metrics.py b/tests/service/test_session_service_metrics.py
index 8fa3e5ff6..2f4ee4a60 100644
--- a/tests/service/test_session_service_metrics.py
+++ b/tests/service/test_session_service_metrics.py
@@ -82,4 +82,45 @@ async def test_sessions_returns_empty_and_logs_when_storage_listing_fails(
result = await service.sessions(ctx)
assert result == []
- debug.assert_called_once()
+ assert debug.call_count == 2
+
+
+async def test_sessions_merges_canonical_and_legacy_session_scope():
+ service = SessionService(viking_fs=Mock())
+ ctx = _make_ctx()
+
+ async def _ls(uri, ctx):
+ if uri == "viking://user/alice/sessions":
+ return [
+ {"name": "duplicate", "isDir": True},
+ {"name": "new-session", "isDir": True},
+ ]
+ if uri == "viking://session":
+ return [
+ {"name": "duplicate", "uri": "viking://session/duplicate", "isDir": True},
+ {"name": "legacy-session", "uri": "viking://session/legacy-session", "isDir": True},
+ ]
+ raise AssertionError(uri)
+
+ service._viking_fs.ls = AsyncMock(side_effect=_ls)
+
+ result = await service.sessions(ctx)
+
+ assert result == [
+ {
+ "session_id": "duplicate",
+ "uri": "viking://user/alice/sessions/duplicate",
+ "is_dir": True,
+ },
+ {
+ "session_id": "new-session",
+ "uri": "viking://user/alice/sessions/new-session",
+ "is_dir": True,
+ },
+ {
+ "session_id": "legacy-session",
+ "uri": "viking://session/legacy-session",
+ "is_dir": True,
+ },
+ ]
diff --git a/tests/session/test_session_commit.py b/tests/session/test_session_commit.py
index 98e0f40dc..bad2258ae 100644
--- a/tests/session/test_session_commit.py
+++ b/tests/session/test_session_commit.py
@@ -395,6 +395,10 @@ class TestCommit:
):
"""Second commit should pass the latest completed archive overview into Phase 2."""
session = client.session(session_id="latest_overview_threading_test")
+ session._meta.memory_policy = {
+ "peer": {"enabled": False},
+ "memory_types": ["profile"],
+ }
session.add_message("user", [TextPart("First round message")])
session.add_message("assistant", [TextPart("First round response")])
diff --git a/tests/storage/test_vector_migration.py b/tests/storage/test_vector_migration.py
new file mode 100644
index 000000000..3374419e7
--- /dev/null
+++ b/tests/storage/test_vector_migration.py
@@ -0,0 +1,164 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+import pytest
+
+from openviking.storage.vector_migration import copy_vector_records, delete_vector_records
+
+
+class FakeVectorStore:
+ def __init__(self, records):
+ self.records = [dict(record) for record in records]
+ self.upserts = []
+ self.deleted_ids = []
+
+ async def filter(self, **_kwargs):
+ return [dict(record) for record in self.records]
+
+ async def upsert(self, data, *, ctx):
+ self.upserts.append(dict(data))
+ return data["id"]
+
+ async def delete(self, ids, *, ctx):
+ self.deleted_ids.extend(ids)
+ return len(ids)
+
+
+async def test_copy_vector_records_rewrites_file_and_chunk_uris():
+ store = FakeVectorStore(
+ [
+ {
+ "id": "old-file",
+ "uri": "viking://agent/code-agent/memories/facts/project.md",
+ "account_id": "acct",
+ "owner_user_id": None,
+ "context_type": "memory",
+ "level": 2,
+ "abstract": "project",
+ "vector": [0.1, 0.2],
+ },
+ {
+ "id": "old-chunk",
+ "uri": "viking://agent/code-agent/memories/facts/project.md#chunk_0000",
+ "account_id": "acct",
+ "context_type": "memory",
+ "level": 2,
+ "abstract": "chunk",
+ "vector": [0.3, 0.4],
+ },
+ {
+ "id": "outside",
+ "uri": "viking://agent/code-agent/memories/facts/other.md",
+ "account_id": "acct",
+ "context_type": "memory",
+ "level": 2,
+ "abstract": "other",
+ "vector": [0.5, 0.6],
+ },
+ ]
+ )
+
+ result = await copy_vector_records(
+ store,
+ account_id="acct",
+ source_uri="viking://agent/code-agent/memories/facts/project.md",
+ target_uri="viking://user/alice/peers/code-agent/memories/facts/project.md",
+ recursive=False,
+ )
+
+ assert result.copied == 2
+ assert result.skipped == 0
+ assert {record["uri"] for record in store.upserts} == {
+ "viking://user/alice/peers/code-agent/memories/facts/project.md",
+ "viking://user/alice/peers/code-agent/memories/facts/project.md#chunk_0000",
+ }
+ assert {record["owner_user_id"] for record in store.upserts} == {"alice"}
+ assert {record["context_type"] for record in store.upserts} == {"memory"}
+ assert all(record["active_count"] == 0 for record in store.upserts)
+ assert all(record["id"] not in {"old-file", "old-chunk"} for record in store.upserts)
+
+
+async def test_copy_vector_records_rewrites_directory_subtree_and_skips_scalar_only_records():
+ store = FakeVectorStore(
+ [
+ {
+ "id": "old-dir",
+ "uri": "viking://agent/code-agent/skills/review",
+ "account_id": "acct",
+ "context_type": "skill",
+ "level": 0,
+ "abstract": "review skill",
+ "vector": [0.1, 0.2],
+ },
+ {
+ "id": "old-file",
+ "uri": "viking://agent/code-agent/skills/review/SKILL.md",
+ "account_id": "acct",
+ "context_type": "skill",
+ "level": 2,
+ "abstract": "skill body",
+ "vector": [0.3, 0.4],
+ },
+ {
+ "id": "no-vector",
+ "uri": "viking://agent/code-agent/skills/review/README.md",
+ "account_id": "acct",
+ "context_type": "skill",
+ "level": 2,
+ "abstract": "no vector",
+ },
+ ]
+ )
+
+ result = await copy_vector_records(
+ store,
+ account_id="acct",
+ source_uri="viking://agent/code-agent/skills/review",
+ target_uri="viking://user/alice/skills/review",
+ recursive=True,
+ )
+
+ assert result.copied == 2
+ assert result.skipped == 1
+ assert {record["uri"] for record in store.upserts} == {
+ "viking://user/alice/skills/review",
+ "viking://user/alice/skills/review/SKILL.md",
+ }
+ assert {record["context_type"] for record in store.upserts} == {"skill"}
+
+
+async def test_delete_vector_records_deletes_records_in_scope_only():
+ store = FakeVectorStore(
+ [
+ {
+ "id": "old-dir",
+ "uri": "viking://agent/code-agent/memories",
+ "account_id": "acct",
+ "vector": [0.1, 0.2],
+ },
+ {
+ "id": "old-file",
+ "uri": "viking://agent/code-agent/memories/facts/project.md",
+ "account_id": "acct",
+ "vector": [0.3, 0.4],
+ },
+ {
+ "id": "new-file",
+ "uri": "viking://user/alice/peers/code-agent/memories/facts/project.md",
+ "account_id": "acct",
+ "vector": [0.5, 0.6],
+ },
+ ]
+ )
+
+ result = await delete_vector_records(
+ store,
+ account_id="acct",
+ uri="viking://agent/code-agent/memories",
+ )
+
+ assert result.deleted == 2
+ assert store.deleted_ids == ["old-dir", "old-file"]
diff --git a/tests/storage/test_viking_fs_actor_peer_view.py b/tests/storage/test_viking_fs_actor_peer_view.py
index 9f98e5f4a..019ed1e25 100644
--- a/tests/storage/test_viking_fs_actor_peer_view.py
+++ b/tests/storage/test_viking_fs_actor_peer_view.py
@@ -5,7 +5,7 @@ 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.exceptions import NotFoundError, PermissionDeniedError
from openviking_cli.session.user_id import UserIdentifier
_MOD_TIME = "2026-01-01T00:00:00Z"
@@ -14,11 +14,32 @@ _MOD_TIME = "2026-01-01T00:00:00Z"
class _MemoryAGFS:
def __init__(self):
self.files = {
+ "/local/acct/agent/customer-wang-yue/memories/profile.md": b"legacy-wang",
+ "/local/acct/agent/customer-zhang-xiaoxiao/memories/profile.md": b"legacy-zhang",
"/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",
+ "/local/acct/user/support_bot/sessions/duplicate/messages.jsonl": (
+ b'{"role":"user","content":"new"}\n'
+ ),
+ "/local/acct/user/support_bot/sessions/new-session/messages.jsonl": (
+ b'{"role":"user","content":"new only"}\n'
+ ),
+ "/local/acct/session/duplicate/messages.jsonl": (
+ b'{"role":"user","content":"legacy duplicate"}\n'
+ ),
+ "/local/acct/session/legacy-session/messages.jsonl": (
+ b'{"role":"user","content":"legacy"}\n'
+ ),
+ "/local/acct/session/other-owned/.meta.json": b'{"created_by_user_id":"other"}',
+ "/local/acct/session/other-owned/messages.jsonl": (
+ b'{"role":"user","content":"other"}\n'
+ ),
+ "/local/acct/session/support_bot/nested-session/messages.jsonl": (
+ b'{"role":"user","content":"nested"}\n'
+ ),
}
self.dirs = set()
for path in self.files:
@@ -163,6 +184,52 @@ async def test_actor_peer_view_filters_ls_peer_collection(fs, actor_ctx):
]
+async def test_actor_peer_view_filters_legacy_agent_collection(fs, actor_ctx):
+ entries = await fs.ls("viking://agent", ctx=actor_ctx)
+
+ assert [entry["uri"] for entry in entries] == ["viking://agent/customer-wang-yue"]
+ assert (
+ await fs.read_file(
+ "viking://agent/customer-wang-yue/memories/profile.md",
+ ctx=actor_ctx,
+ )
+ == "legacy-wang"
+ )
+ with pytest.raises(PermissionDeniedError):
+ await fs.read_file(
+ "viking://agent/customer-zhang-xiaoxiao/memories/profile.md",
+ ctx=actor_ctx,
+ )
+
+
+async def test_legacy_session_scope_merges_new_and_unmigrated_sessions(fs, actor_ctx):
+ entries = await fs.ls("viking://session", ctx=actor_ctx)
+
+ assert [entry["uri"] for entry in entries] == [
+ "viking://session/duplicate",
+ "viking://session/new-session",
+ "viking://session/legacy-session",
+ "viking://session/nested-session",
+ ]
+
+ assert (
+ await fs.read_file("viking://session/duplicate/messages.jsonl", ctx=actor_ctx)
+ == '{"role":"user","content":"new"}\n'
+ )
+ assert (
+ await fs.read_file("viking://session/legacy-session/messages.jsonl", ctx=actor_ctx)
+ == '{"role":"user","content":"legacy"}\n'
+ )
+ assert (
+ await fs.read_file("viking://session/nested-session/messages.jsonl", ctx=actor_ctx)
+ == '{"role":"user","content":"nested"}\n'
+ )
+ with pytest.raises(NotFoundError):
+ await fs.read_file("viking://session/other-owned/messages.jsonl", ctx=actor_ctx)
+
+
@pytest.mark.asyncio
async def test_actor_peer_view_filters_tree_from_user_root(fs, actor_ctx):
entries = await fs.tree(
diff --git a/tests/test_task_tracker.py b/tests/test_task_tracker.py
index 2e4729454..e8eb48fb9 100644
--- a/tests/test_task_tracker.py
+++ b/tests/test_task_tracker.py
@@ -151,9 +151,30 @@ async def test_complete_task(tracker: TaskTracker):
retrieved = await tracker.get(task.task_id)
assert retrieved is not None
assert retrieved.status == TaskStatus.COMPLETED
+ assert retrieved.stage == "completed"
assert retrieved.result == {"memories_extracted": 3}
+async def test_task_result_redacts_user_key(tracker: TaskTracker):
+ task = await tracker.create("legacy_migration", **_owner_kwargs())
+ await tracker.complete(
+ task.task_id,
+ {
+ "created_users": [{"account_id": "acme", "user_id": "bob", "user_key": "secret-key"}],
+ "nested": {"user_key": "nested-secret"},
+ },
+ )
+
+ retrieved = await tracker.get(task.task_id)
+
+ assert retrieved is not None
+ assert retrieved.result == {
+ "created_users": [{"account_id": "acme", "user_id": "bob"}],
+ "nested": {},
+ }
+ assert "user_key" not in json.dumps(retrieved.to_dict())
+
+
async def test_fail_task(tracker: TaskTracker):
task = await tracker.create("session_commit", **_owner_kwargs())
await tracker.start(task.task_id)
@@ -161,6 +182,7 @@ async def test_fail_task(tracker: TaskTracker):
retrieved = await tracker.get(task.task_id)
assert retrieved is not None
assert retrieved.status == TaskStatus.FAILED
+ assert retrieved.stage == "failed"
assert "LLM timeout" in retrieved.error
diff --git a/tests/unit/session/test_memory_policy.py b/tests/unit/session/test_memory_policy.py
index f46f1dbd9..2576d2254 100644
--- a/tests/unit/session/test_memory_policy.py
+++ b/tests/unit/session/test_memory_policy.py
@@ -10,14 +10,21 @@ from openviking.session.memory_policy import MemoryPolicy
from openviking_cli.exceptions import InvalidArgumentError
-def test_memory_policy_defaults_to_self_only():
+def test_memory_policy_defaults_to_self_and_peer():
policy = MemoryPolicy.from_dict(None)
assert policy.self_enabled is True
- assert policy.peer_enabled is False
+ assert policy.peer_enabled is True
assert policy.memory_types is None
+def test_memory_policy_can_disable_peer_memory():
+ policy = MemoryPolicy.from_dict({"peer": {"enabled": False}})
+
+ assert policy.self_enabled is True
+ assert policy.peer_enabled is False
+
+
def test_memory_policy_uses_top_level_memory_types():
policy = MemoryPolicy.from_dict(
{
diff --git a/tests/unit/test_namespace_uri_classification.py b/tests/unit/test_namespace_uri_classification.py
index 512f93f52..eb758efca 100644
--- a/tests/unit/test_namespace_uri_classification.py
+++ b/tests/unit/test_namespace_uri_classification.py
@@ -37,6 +37,9 @@ def test_context_type_for_uri_uses_path_segments():
context_type_for_uri("viking://user/support_bot/peers/web-visitor-alice/resources/faq.md")
== "resource"
)
+ assert context_type_for_uri("viking://agent/code-agent/memories/profile.md") == "memory"
+ assert context_type_for_uri("viking://agent/code-agent/resources/faq.md") == "resource"
+ assert context_type_for_uri("viking://agent/code-agent/skills/demo") == "skill"
assert context_type_for_uri("viking://resources/memories-report.md") == "resource"
assert context_type_for_uri("viking://user/alice/resources/skills-report.md") == "resource"
diff --git a/tests/unit/test_uri_validation.py b/tests/unit/test_uri_validation.py
index fe63758fe..6314cd5e9 100644
--- a/tests/unit/test_uri_validation.py
+++ b/tests/unit/test_uri_validation.py
@@ -16,6 +16,7 @@ from openviking_cli.exceptions import InvalidURIError
"resources/docs",
"/resources/docs",
"viking://session/s1",
+ "viking://agent/code-agent/memories/facts/project.md",
"viking://",
],
)