Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(acl): 增加资源 ACL、用户组授权与向量权限过滤 (#3213)
Qin Haojiee357af6ac708
diff --git a/crates/ov_cli/README.md b/crates/ov_cli/README.mdindex 189c044ed..ce42a041a 100644--- a/crates/ov_cli/README.md+++ b/crates/ov_cli/README.md@@ -227,6 +227,7 @@ Use `--sudo` for commands that require the configured `root_api_key`.- `admin remove-user` - Remove a user.- `admin set-role` - Change a user's role. ROOT only.- `admin regenerate-key` - Rotate a user's API key.+- `admin set-account-settings` - Update allowlisted account settings.- `admin migrate` - Migrate legacy agent/session data. ROOT only.- `system` - Administrative system utility commands.- `reindex` - Rebuild semantic and vector artifacts for a URI.diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex 81204ccac..c4968b5e0 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -433,6 +433,40 @@ impl HttpClient {self.post("/api/v1/fs/attrs/set_tags", &body).await}+ pub async fn acl_get(&self, uri: &str) -> Result<Value> {+ self.get("/api/v1/acl", &[("uri".to_string(), uri.to_string())])+ .await+ }++ pub async fn acl_set(&self, uri: &str, entries: Vec<Value>) -> Result<Value> {+ self.put(+ "/api/v1/acl",+ &serde_json::json!({"uri": uri, "entries": entries}),+ )+ .await+ }++ pub async fn acl_grant(&self, uri: &str, principal: &str, level: &str) -> Result<Value> {+ self.post(+ "/api/v1/acl/grant",+ &serde_json::json!({"uri": uri, "principal": principal, "level": level}),+ )+ .await+ }++ pub async fn acl_revoke(&self, uri: &str, principal: &str) -> Result<Value> {+ self.post(+ "/api/v1/acl/revoke",+ &serde_json::json!({"uri": uri, "principal": principal}),+ )+ .await+ }++ pub async fn acl_delete(&self, uri: &str) -> Result<Value> {+ self.delete("/api/v1/acl", &[("uri".to_string(), uri.to_string())])+ .await+ }+fn build_write_body(uri: &str,content: &str,@@ -1442,6 +1476,24 @@ impl HttpClient {self.delete(&path, &[]).await}+ pub async fn admin_set_account_auto_protect_new_content(+ &self,+ account_id: &str,+ enabled: bool,+ ) -> Result<Value> {+ let path = format!("/api/v1/admin/accounts/{}/settings", account_id);+ self.patch(+ &path,+ &serde_json::json!({+ "resource_acl": {+ "auto_protect_new_content": enabled,+ }+ }),+ &[],+ )+ .await+ }+pub async fn admin_register_user(&self,account_id: &str,@@ -1522,6 +1574,60 @@ impl HttpClient {self.post(&path, &body).await}+ pub async fn admin_create_group(&self, account_id: &str, group_id: &str) -> Result<Value> {+ let path = format!("/api/v1/admin/accounts/{}/groups", account_id);+ self.post(&path, &serde_json::json!({"group_id": group_id}))+ .await+ }++ pub async fn admin_list_groups(&self, account_id: &str) -> Result<Value> {+ let path = format!("/api/v1/admin/accounts/{}/groups", account_id);+ self.get(&path, &[]).await+ }++ pub async fn admin_delete_group(&self, account_id: &str, group_id: &str) -> Result<Value> {+ let path = format!("/api/v1/admin/accounts/{}/groups/{}", account_id, group_id);+ self.delete(&path, &[]).await+ }++ pub async fn admin_list_group_members(+ &self,+ account_id: &str,+ group_id: &str,+ ) -> Result<Value> {+ let path = format!(+ "/api/v1/admin/accounts/{}/groups/{}/members",+ account_id, group_id+ );+ self.get(&path, &[]).await+ }++ pub async fn admin_add_group_member(+ &self,+ account_id: &str,+ group_id: &str,+ user_id: &str,+ ) -> Result<Value> {+ let path = format!(+ "/api/v1/admin/accounts/{}/groups/{}/members/{}",+ account_id, group_id, user_id+ );+ self.put(&path, &serde_json::json!({})).await+ }++ pub async fn admin_remove_group_member(+ &self,+ account_id: &str,+ group_id: &str,+ user_id: &str,+ ) -> Result<Value> {+ let path = format!(+ "/api/v1/admin/accounts/{}/groups/{}/members/{}",+ account_id, group_id, user_id+ );+ self.delete(&path, &[]).await+ }+pub async fn admin_migrate(&self, cleanup: bool) -> Result<Value> {let action = if cleanup { "cleanup" } else { "migrate" };self.post(@@ -2348,7 +2454,7 @@ mod tests {}#[tokio::test]- async fn admin_seed_payloads_are_sent() {+ async fn admin_request_payloads_are_sent() {let (base_url, request_rx) = spawn_request_capture_server().await;let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None);client@@ -2378,6 +2484,16 @@ mod tests {let request = request_rx.await.expect("request should be captured");assert!(request.starts_with("POST /api/v1/admin/accounts/acct/users/alice/key "));assert!(request.contains(r#""seed":"new-seed""#));++ let (base_url, request_rx) = spawn_request_capture_server().await;+ let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None);+ client+ .admin_set_account_auto_protect_new_content("acct", true)+ .await+ .expect("set account settings should succeed");+ let request = request_rx.await.expect("request should be captured");+ assert!(request.starts_with("PATCH /api/v1/admin/accounts/acct/settings "));+ assert!(request.contains(r#""resource_acl":{"auto_protect_new_content":true}"#));}#[test]diff --git a/crates/ov_cli/src/commands/acl.rs b/crates/ov_cli/src/commands/acl.rsnew file mode 100644index 000000000..9fbf147a6--- /dev/null+++ b/crates/ov_cli/src/commands/acl.rs@@ -0,0 +1,75 @@+use crate::client::HttpClient;+use crate::error::{Error, Result};+use crate::output::{OutputFormat, output_success};+use serde_json::{Value, json};++fn show(value: Value, output_format: OutputFormat, compact: bool) -> Result<()> {+ output_success(value, output_format, compact);+ Ok(())+}++pub async fn get(+ client: &HttpClient,+ uri: &str,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ show(client.acl_get(uri).await?, output_format, compact)+}++pub async fn set(+ client: &HttpClient,+ uri: &str,+ raw_entries: Vec<String>,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ let mut entries = Vec::new();+ for raw in raw_entries {+ let Some((principal, level)) = raw.split_once('=') else {+ return Err(Error::Client(format!(+ "Invalid ACL entry '{raw}'. Expected principal=read|write|manage."+ )));+ };+ entries.push(json!({"principal": principal, "level": level}));+ }+ show(client.acl_set(uri, entries).await?, output_format, compact)+}++pub async fn grant(+ client: &HttpClient,+ uri: &str,+ principal: &str,+ level: &str,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ show(+ client.acl_grant(uri, principal, level).await?,+ output_format,+ compact,+ )+}++pub async fn revoke(+ client: &HttpClient,+ uri: &str,+ principal: &str,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ show(+ client.acl_revoke(uri, principal).await?,+ output_format,+ compact,+ )+}++pub async fn remove(+ client: &HttpClient,+ uri: &str,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ show(client.acl_delete(uri).await?, output_format, compact)+}diff --git a/crates/ov_cli/src/commands/admin.rs b/crates/ov_cli/src/commands/admin.rsindex 3c80c8f39..3a435fefd 100644--- a/crates/ov_cli/src/commands/admin.rs+++ b/crates/ov_cli/src/commands/admin.rs@@ -133,6 +133,102 @@ pub async fn remove_user(Ok(())}+pub async fn create_group(+ client: &HttpClient,+ account_id: &str,+ group_id: &str,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ show_admin(+ client.admin_create_group(account_id, group_id).await?,+ output_format,+ compact,+ )+}++pub async fn list_groups(+ client: &HttpClient,+ account_id: &str,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ show_admin(+ client.admin_list_groups(account_id).await?,+ output_format,+ compact,+ )+}++pub async fn list_group_members(+ client: &HttpClient,+ account_id: &str,+ group_id: &str,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ show_admin(+ client+ .admin_list_group_members(account_id, group_id)+ .await?,+ output_format,+ compact,+ )+}++pub async fn add_group_member(+ client: &HttpClient,+ account_id: &str,+ group_id: &str,+ user_id: &str,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ show_admin(+ client+ .admin_add_group_member(account_id, group_id, user_id)+ .await?,+ output_format,+ compact,+ )+}++pub async fn remove_group_member(+ client: &HttpClient,+ account_id: &str,+ group_id: &str,+ user_id: &str,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ show_admin(+ client+ .admin_remove_group_member(account_id, group_id, user_id)+ .await?,+ output_format,+ compact,+ )+}++pub async fn delete_group(+ client: &HttpClient,+ account_id: &str,+ group_id: &str,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ show_admin(+ client.admin_delete_group(account_id, group_id).await?,+ output_format,+ compact,+ )+}++fn show_admin(value: Value, output_format: OutputFormat, compact: bool) -> Result<()> {+ output_success(&value, output_format, compact);+ Ok(())+}+pub async fn set_role(client: &HttpClient,account_id: &str,@@ -162,6 +258,22 @@ pub async fn regenerate_key(Ok(())}+pub async fn set_account_settings(+ client: &HttpClient,+ account_id: &str,+ auto_protect_new_content: bool,+ output_format: OutputFormat,+ compact: bool,+) -> Result<()> {+ show_admin(+ client+ .admin_set_account_auto_protect_new_content(account_id, auto_protect_new_content)+ .await?,+ output_format,+ compact,+ )+}+fn print_admin_user_key_notice(response: &Value,output_format: OutputFormat,diff --git a/crates/ov_cli/src/commands/filesystem.rs b/crates/ov_cli/src/commands/filesystem.rsindex 80ad88cfc..1ad1c6951 100644--- a/crates/ov_cli/src/commands/filesystem.rs+++ b/crates/ov_cli/src/commands/filesystem.rs@@ -215,6 +215,11 @@ fn entry_metadata(object: Option<&serde_json::Map<String, Value>>) -> Vec<String.to_string(),];+ if entry_access_denied(object) {+ metadata.push(theme::warning("permission denied").bold().to_string());+ return metadata;+ }+if !entry_is_dir(object)&& let Some(size) = object.and_then(|object| object.get("size"))@@ -251,6 +256,11 @@ fn append_entry_abstract(fn tree_metadata(object: Option<&serde_json::Map<String, Value>>) -> Vec<String> {let mut metadata = Vec::new();+ if entry_access_denied(object) {+ metadata.push("permission denied".to_string());+ return metadata;+ }+if !entry_is_dir(object)&& let Some(size) = object.and_then(|object| object.get("size"))@@ -306,6 +316,13 @@ fn entry_is_dir(object: Option<&serde_json::Map<String, Value>>) -> bool {.unwrap_or(false)}+fn entry_access_denied(object: Option<&serde_json::Map<String, Value>>) -> bool {+ object+ .and_then(|object| object.get("access"))+ .and_then(Value::as_str)+ == Some("denied")+}+fn entry_string<'a>(object: Option<&'a serde_json::Map<String, Value>>,key: &str,@@ -527,6 +544,11 @@ mod tests {"isDir": true,"modTime": "2026-05-25","abstract": "# viking://user/default/memories [Directory abstract is not ready]"+ },+ {+ "uri": "viking://resources/restricted",+ "isDir": true,+ "access": "denied"}]);@@ -536,6 +558,8 @@ mod tests {assert!(rendered.contains("viking://resources"));assert!(rendered.contains("The resources directory is a centralized collection"));assert!(rendered.contains("2. dir · 2026-05-25"));+ assert!(rendered.contains("3. dir · permission denied"));+ assert!(rendered.contains("viking://resources/restricted"));assert!(!rendered.contains("Directory abstract is not ready"));assert!(!rendered.contains("uri size isDir"));for line in rendered.lines() {@@ -610,6 +634,12 @@ mod tests {"modTime": "2026-05-25","rel_path": "program","abstract": ""+ },+ {+ "uri": "viking://user/haozhe/memories/entities/restricted",+ "isDir": true,+ "rel_path": "restricted",+ "access": "denied"}]);@@ -619,6 +649,8 @@ mod tests {assert!(rendered.contains(" 2026_fifa_world_cup.md"));assert!(rendered.contains("1.3 KB 2026-05-25"));assert!(rendered.contains("program/"));+ assert!(rendered.contains("restricted/"));+ assert!(rendered.contains("permission denied"));assert!(!rendered.contains("1. dir"));assert!(!rendered.contains("2. file"));assert!(!rendered.contains("Directory abstract is not ready"));diff --git a/crates/ov_cli/src/commands/mod.rs b/crates/ov_cli/src/commands/mod.rsindex 0a5b999bb..cb445dc94 100644--- a/crates/ov_cli/src/commands/mod.rs+++ b/crates/ov_cli/src/commands/mod.rs@@ -1,3 +1,4 @@+pub mod acl;pub mod admin;pub mod chat;pub mod compile;diff --git a/crates/ov_cli/src/error_ui.rs b/crates/ov_cli/src/error_ui.rsindex 7b8cc6327..05e3285d7 100644--- a/crates/ov_cli/src/error_ui.rs+++ b/crates/ov_cli/src/error_ui.rs@@ -432,9 +432,16 @@ fn contextual_help_command(command: &str) -> Option<String> {"migrate","register-user","list-users",+ "create-group",+ "list-groups",+ "list-group-members",+ "add-group-member",+ "remove-group-member",+ "delete-group","remove-user","set-role","regenerate-key",+ "set-account-settings",],)),"system" => Some(system_help_command(program, &tokens)),diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rsindex 04a1aeae8..8eb22c0bd 100644--- a/crates/ov_cli/src/handlers.rs+++ b/crates/ov_cli/src/handlers.rs@@ -672,6 +672,78 @@ pub async fn handle_admin(cmd: AdminCommands, ctx: CliContext) -> Result<()> {).await}+ AdminCommands::CreateGroup {+ account_id,+ group_id,+ } => {+ commands::admin::create_group(+ &client,+ &account_id,+ &group_id,+ ctx.output_format,+ ctx.compact,+ )+ .await+ }+ AdminCommands::ListGroups { account_id } => {+ commands::admin::list_groups(&client, &account_id, ctx.output_format, ctx.compact).await+ }+ AdminCommands::ListGroupMembers {+ account_id,+ group_id,+ } => {+ commands::admin::list_group_members(+ &client,+ &account_id,+ &group_id,+ ctx.output_format,+ ctx.compact,+ )+ .await+ }+ AdminCommands::AddGroupMember {+ account_id,+ group_id,+ user_id,+ } => {+ commands::admin::add_group_member(+ &client,+ &account_id,+ &group_id,+ &user_id,+ ctx.output_format,+ ctx.compact,+ )+ .await+ }+ AdminCommands::RemoveGroupMember {+ account_id,+ group_id,+ user_id,+ } => {+ commands::admin::remove_group_member(+ &client,+ &account_id,+ &group_id,+ &user_id,+ ctx.output_format,+ ctx.compact,+ )+ .await+ }+ AdminCommands::DeleteGroup {+ account_id,+ group_id,+ } => {+ commands::admin::delete_group(+ &client,+ &account_id,+ &group_id,+ ctx.output_format,+ ctx.compact,+ )+ .await+ }AdminCommands::RemoveUser {account_id,user_id,@@ -715,6 +787,19 @@ pub async fn handle_admin(cmd: AdminCommands, ctx: CliContext) -> Result<()> {).await}+ AdminCommands::SetAccountSettings {+ account_id,+ auto_protect_new_content,+ } => {+ commands::admin::set_account_settings(+ &client,+ &account_id,+ auto_protect_new_content,+ ctx.output_format,+ ctx.compact,+ )+ .await+ }}}@@ -1679,6 +1764,39 @@ pub async fn handle_attrs(uri: String, key: Option<String>, ctx: CliContext) ->.await}+pub async fn handle_acl(action: crate::AclCommands, ctx: CliContext) -> Result<()> {+ let client = ctx.get_client();+ match action {+ crate::AclCommands::Get { uri } => {+ commands::acl::get(&client, &uri, ctx.output_format, ctx.compact).await+ }+ crate::AclCommands::Set { uri, entries } => {+ commands::acl::set(&client, &uri, entries, ctx.output_format, ctx.compact).await+ }+ crate::AclCommands::Grant {+ uri,+ principal,+ level,+ } => {+ commands::acl::grant(+ &client,+ &uri,+ &principal,+ &level,+ ctx.output_format,+ ctx.compact,+ )+ .await+ }+ crate::AclCommands::Revoke { uri, principal } => {+ commands::acl::revoke(&client, &uri, &principal, ctx.output_format, ctx.compact).await+ }+ crate::AclCommands::Rm { uri } => {+ commands::acl::remove(&client, &uri, ctx.output_format, ctx.compact).await+ }+ }+}+pub async fn handle_grep(uri: String,exclude_uri: Option<String>,diff --git a/crates/ov_cli/src/help_ui.rs b/crates/ov_cli/src/help_ui.rsindex ad6a77e63..250e797ac 100644--- a/crates/ov_cli/src/help_ui.rs+++ b/crates/ov_cli/src/help_ui.rs@@ -71,8 +71,9 @@ const CORE_WORKFLOW: &[HelpCommand] = help_commands!["set-tags",];-const FILESYSTEM: &[HelpCommand] =- help_commands!["ls", "tree", "mkdir", "rm", "mv", "stat", "attrs", "get"];+const FILESYSTEM: &[HelpCommand] = help_commands![+ "ls", "tree", "mkdir", "rm", "mv", "stat", "attrs", "acl", "get"+];const SEARCH_CONTEXT: &[HelpCommand] = help_commands!["find", "search", "grep", "glob", "abstract", "overview", "read"@@ -345,6 +346,24 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[},],},+ CommandHelpSpec {+ path: &["acl"],+ purpose: "Get or update access permissions for a resource.",+ examples: &[+ HelpItem {+ label: "ov acl get viking://resources/project-a",+ description: "Show direct and effective permissions.",+ },+ HelpItem {+ label: "ov acl grant viking://resources/project-a --principal user:bob --level read",+ description: "Grant read access to a user.",+ },+ ],+ next_steps: &[HelpItem {+ label: "ov find \"query\" -u <uri>",+ description: "Search within the permitted resource tree.",+ }],+ },CommandHelpSpec {path: &["read"],purpose: "Read exact Level 2 file content from a Viking URI.",@@ -2321,6 +2340,7 @@ fn localized_command_description<'a>("rm" => "删除资源","mv" => "移动或重命名资源","stat" => "查看资源元数据",+ "acl" => "管理资源访问权限","get" => "下载文件","search" => "上下文感知检索","grep" => "模式搜索",@@ -2561,7 +2581,15 @@ fn version() -> String {fn is_bare_group_help_command(command: &str) -> bool {matches!(command,- "task" | "skills" | "session" | "snapshot" | "privacy" | "admin" | "system" | "observer"+ "task"+ | "skills"+ | "session"+ | "snapshot"+ | "privacy"+ | "acl"+ | "admin"+ | "system"+ | "observer")}diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex 76330307d..89c323303 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -289,6 +289,33 @@ enum AttrsCommands {},}+#[derive(Subcommand)]+enum AclCommands {+ Get {+ uri: String,+ },+ Set {+ uri: String,+ #[arg(long = "entry", required = true)]+ entries: Vec<String>,+ },+ Grant {+ uri: String,+ #[arg(long)]+ principal: String,+ #[arg(long)]+ level: String,+ },+ Revoke {+ uri: String,+ #[arg(long)]+ principal: String,+ },+ Rm {+ uri: String,+ },+}+// Commands are organized with category tags in their doc comments.//// # Command Tagging System@@ -593,6 +620,11 @@ enum Commands {#[command(subcommand)]action: AttrsCommands,},+ /// [Data] Manage resource ACL+ Acl {+ #[command(subcommand)]+ action: AclCommands,+ },/// [Data] Read file content (Level 2)Read {/// Viking URI@@ -1891,6 +1923,50 @@ enum AdminCommands {#[arg(long, default_value = "1", value_name = "n")]page: u32,},+ /// Create an empty account-scoped group+ CreateGroup {+ #[arg(value_name = "account-id")]+ account_id: String,+ #[arg(value_name = "group-id")]+ group_id: String,+ },+ /// List groups in an account+ ListGroups {+ #[arg(value_name = "account-id")]+ account_id: String,+ },+ /// List the users in a group+ ListGroupMembers {+ #[arg(value_name = "account-id")]+ account_id: String,+ #[arg(value_name = "group-id")]+ group_id: String,+ },+ /// Add an existing account user to a group+ AddGroupMember {+ #[arg(value_name = "account-id")]+ account_id: String,+ #[arg(value_name = "group-id")]+ group_id: String,+ #[arg(value_name = "user-id")]+ user_id: String,+ },+ /// Remove a user from a group+ RemoveGroupMember {+ #[arg(value_name = "account-id")]+ account_id: String,+ #[arg(value_name = "group-id")]+ group_id: String,+ #[arg(value_name = "user-id")]+ user_id: String,+ },+ /// Delete an empty group+ DeleteGroup {+ #[arg(value_name = "account-id")]+ account_id: String,+ #[arg(value_name = "group-id")]+ group_id: String,+ },/// Remove a user from an accountRemoveUser {/// Account ID@@ -1924,6 +2000,20 @@ enum AdminCommands {#[arg(long, value_name = "seed")]seed: Option<String>,},+ /// Update allowlisted settings for an account+ SetAccountSettings {+ /// Account ID+ #[arg(value_name = "account-id")]+ account_id: String,+ /// Automatically protect newly created shared content+ #[arg(+ long,+ required = true,+ action = ArgAction::Set,+ value_name = "true|false"+ )]+ auto_protect_new_content: bool,+ },}impl Commands {@@ -2513,9 +2603,16 @@ fn is_admin_subcommand(token: &str) -> bool {| "migrate"| "register-user"| "list-users"+ | "create-group"+ | "list-groups"+ | "list-group-members"+ | "add-group-member"+ | "remove-group-member"+ | "delete-group"| "remove-user"| "set-role"| "regenerate-key"+ | "set-account-settings")}@@ -3399,6 +3496,7 @@ async fn main() {recursive,} => handlers::handle_set_tags(uri, tags, mode, recursive, ctx).await,},+ Commands::Acl { action } => handlers::handle_acl(action, ctx).await,Commands::AddMemory { content } => handlers::handle_add_memory(content, ctx).await,Commands::Tui { uri } => handlers::handle_tui(uri, ctx).await,Commands::Chat {@@ -4137,9 +4235,16 @@ mod tests {&["ov", "admin", "migrate"],&["ov", "admin", "register-user"],&["ov", "admin", "list-users"],+ &["ov", "admin", "create-group"],+ &["ov", "admin", "list-groups"],+ &["ov", "admin", "list-group-members"],+ &["ov", "admin", "add-group-member"],+ &["ov", "admin", "remove-group-member"],+ &["ov", "admin", "delete-group"],&["ov", "admin", "remove-user"],&["ov", "admin", "set-role"],&["ov", "admin", "regenerate-key"],+ &["ov", "admin", "set-account-settings"],&["ov", "system", "wait"],&["ov", "system", "status"],&["ov", "system", "health"],diff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.mdindex fb9e31373..15cd2979a 100644--- a/docs/en/api/01-overview.md+++ b/docs/en/api/01-overview.md@@ -368,6 +368,16 @@ This catalog follows the routes actually mounted by the server. Each group headi| DELETE | `/api/v1/fs` | Delete a resource || POST | `/api/v1/fs/mv` | Move or rename a resource |+### [ACL](12-acl.md)++| Method | Path | Description |+|--------|------|-------------|+| GET | `/api/v1/acl` | Get direct, inherited, and effective ACLs |+| PUT | `/api/v1/acl` | Replace a resource's direct ACL |+| DELETE | `/api/v1/acl` | Clear a resource's direct ACL |+| POST | `/api/v1/acl/grant` | Set one principal's direct level |+| POST | `/api/v1/acl/revoke` | Remove one principal's direct grant |+### [Content](12-content.md)| Method | Path | Description |@@ -485,6 +495,12 @@ This catalog follows the routes actually mounted by the server. Each group headi| DELETE | `/api/v1/admin/accounts/{account_id}/users/{user_id}` | Remove a user || PUT | `/api/v1/admin/accounts/{account_id}/users/{user_id}/role` | Promote a user to ADMIN || POST | `/api/v1/admin/accounts/{account_id}/users/{user_id}/key` | Regenerate a user key |+| POST | `/api/v1/admin/accounts/{account_id}/groups` | Create a group |+| GET | `/api/v1/admin/accounts/{account_id}/groups` | List groups |+| DELETE | `/api/v1/admin/accounts/{account_id}/groups/{group_id}` | Delete a group |+| GET | `/api/v1/admin/accounts/{account_id}/groups/{group_id}/members` | List group members |+| PUT | `/api/v1/admin/accounts/{account_id}/groups/{group_id}/members/{user_id}` | Add a group member |+| DELETE | `/api/v1/admin/accounts/{account_id}/groups/{group_id}/members/{user_id}` | Remove a group member || GET | `/api/v1/privacy-configs` | List privacy configuration categories || GET | `/api/v1/privacy-configs/{category}` | List category targets || GET | `/api/v1/privacy-configs/{category}/{target_key}` | Get the active configuration |@@ -526,5 +542,5 @@ The sidebar is organized by responsibility rather than historical file size:| Retrieval | Semantic retrieval and code retrieval || Data Lifecycle | Watches, snapshots, and OVPack || Operations & Observability | System, tasks, Observer, and Metrics |-| Identity & Governance | Administration and privacy configuration |+| Identity & Governance | Administration, ACL, and privacy configuration || Protocols & Extensions | OpenViking Assets, WebDAV, and VikingBot API |diff --git a/docs/en/api/02-resources.md b/docs/en/api/02-resources.mdindex ef840a2a7..1029ba132 100644--- a/docs/en/api/02-resources.md+++ b/docs/en/api/02-resources.md@@ -184,6 +184,8 @@ This endpoint is the core entry point for resource management, supporting adding**Additional Notes**:- `to` and `parent` cannot be specified together. `to` is the final save location: a missing target is created, and an existing target is refreshed. If the target is a directory, old files or subdirectories that are not produced by the current import may be removed. `parent` is the destination directory, and is the right option for adding a new resource under an existing directory; use `create_parent=true` or CLI `--parent-auto-create` when that directory should be created automatically. When the imported `root_uri` is the same as `to`, semantic and vector processing reuse unchanged content and process only the changed parts.+- Creating a resource requires write access to its target parent; updating an existing explicit `to` requires write access to that target. These checks run before the task is queued. Automatic naming uses actual URI occupancy, so an unreadable collision selects `_1`, `_2`, and so on instead of attempting an overwrite.+- With `wait=false`, `status=accepted` means that preflight passed and the task was queued; it does not mean resource processing has completed. Use the returned `task_id` for the final status.- If both `to` and `parent` are omitted, the server may use the current user's `add_targets.resource_uri` override, then `server.user_config_defaults.add_targets.resource_uri`. If neither is set, legacy target resolution is unchanged.- Resource targets may use public `viking://resources/...`, the home alias `viking://~/resources/...`, explicit user `viking://user/{user_id}/resources/...`, or peer `viking://user/{user_id}/peers/{peer_id}/resources/...` paths. The home alias is expanded to the canonical path using the authenticated request identity; the uid-less spelling `viking://user/resources/...` is rejected with an error pointing at `viking://~/resources/...`.- `user_id` and `peer_id` path segments must be safe single-segment identifiers, for example `alice` or `web-visitor-alice`. Values with path separators, `.`, `..`, `:`, or `+` are rejected.@@ -543,12 +545,8 @@ ov add-resource ./documents/guide.md -p viking://resources/docs/{calendar:today}{"status": "ok","result": {- "status": "success",+ "status": "accepted","root_uri": "viking://resources/guide",- "temp_uri": "viking://temp/username/04291108_b62dc7/guide",- "source_path": "./documents/guide.md",- "meta": {},- "errors": [],"task_id": "uuid-xxx"}}@@ -561,7 +559,7 @@ Use the returned `task_id` to poll `/api/v1/tasks/{task_id}` for queue completio```Note: Resource is being processed in the background.Use 'ov wait' to wait for completion, or 'ov observer queue' to check status.-status success+status acceptedroot_uri viking://resources/01-overviewtask_id uuid-xxx```@@ -570,7 +568,7 @@ task_id uuid-xxx```json{- "status": "success",+ "status": "accepted","root_uri": "viking://resources/01-overview","task_id": "uuid-xxx"}@@ -580,7 +578,7 @@ task_id uuid-xxx| Field | Type | Description ||-------|------|-------------|-| `status` | string | Processing status: "success" or "error" |+| `status` | string | Processing status: `accepted` means queued, `success` means completed successfully, and `error` means failed. || `root_uri` | string | Final URI of the resource in OpenViking || `task_id` | string | (Optional, only when `wait=false`) Task ID for polling `/api/v1/tasks/{task_id}`. Non-Git imports use it for queue tracking; Git repository imports use it for full background import tracking. || `temp_uri` | string | Temporary URI produced during import |diff --git a/docs/en/api/03-filesystem.md b/docs/en/api/03-filesystem.mdindex b3702fb23..8c7a2e79c 100644--- a/docs/en/api/03-filesystem.md+++ b/docs/en/api/03-filesystem.md@@ -40,6 +40,26 @@ List directory contents.}```+If the caller can read the parent directory but cannot read one of its direct+children, `ls` still returns a name placeholder without size, modification+time, abstract, or storage metadata:++```python+{+ "name": "restricted",+ "isDir": True,+ "uri": "viking://resources/restricted",+ "access": "denied"+}+```++Content operations such as `stat` and `read` return HTTP 403 `PermissionDenied` for+that URI. Recursive listing retains the inaccessible directory itself but does+not descend into it, and search results omit unreadable content. This+discoverable-name behavior applies only to the shared+`viking://resources` namespace; private user and peer namespaces retain their+existing hiding rules.+**Python HTTP SDK**diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.mdindex 2e9fb7284..70471e31f 100644--- a/docs/en/api/08-admin.md+++ b/docs/en/api/08-admin.md@@ -1,6 +1,6 @@# Admin (Multi-tenant)-The Admin API manages accounts and users in a multi-tenant environment. It covers workspace (account) creation/deletion, user registration/removal, role changes, and API key regeneration.+The Admin API manages accounts, users, and groups in a multi-tenant environment. It covers workspace (account) creation/deletion, user registration/removal, group membership, role changes, and API key regeneration.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.@@ -21,6 +21,7 @@ For `/api/v1/admin/*`, `trusted` mode permits requests with no explicit identity| Create/delete workspace | Y | N | N || List workspaces | Y | N | N || Register/remove users | Y | Y (own account) | N |+| Manage groups and membership | Y | Y (own account) | N || List agents (deprecated, returns empty list) | Y | Y (own account) | N || Regenerate user key | Y | Y (own account) | N || Promote user to ADMIN | Y | Y (own account) | N |@@ -55,6 +56,32 @@ Configure `root_api_key` in `~/.openviking/ovcli.conf`:- `--sudo` only works with the commands above - using it with regular data commands will error- Must have `root_api_key` configured to use `--sudo`+## Groups++A group belongs to one account and lets one ACL principal grant access to multiple users. Its caller-supplied `group_id` follows the same identifier rules as `user_id` and is the account-unique, stable identifier; there is no separate group name. Only existing users from the same account can be members, and groups cannot be nested.++The server adds memberships to `RequestContext.group_ids` for each request. Adding or removing a member takes effect on the next request without rewriting resource ACL or context records. Removing a user also removes all memberships. A group must be empty before deletion.++| Method | Path | Description |+|--------|------|-------------|+| POST | `/api/v1/admin/accounts/{account_id}/groups` | Create an empty group with `{"group_id":"engineering"}` |+| GET | `/api/v1/admin/accounts/{account_id}/groups` | List groups |+| DELETE | `/api/v1/admin/accounts/{account_id}/groups/{group_id}` | Delete an empty group |+| GET | `/api/v1/admin/accounts/{account_id}/groups/{group_id}/members` | List members |+| PUT | `/api/v1/admin/accounts/{account_id}/groups/{group_id}/members/{user_id}` | Add a member idempotently; repeated calls return `added=true` |+| DELETE | `/api/v1/admin/accounts/{account_id}/groups/{group_id}/members/{user_id}` | Remove a member; repeated calls return `removed=false` |++```bash+ov --sudo admin create-group acme engineering+ov --sudo admin add-group-member acme engineering alice+ov acl grant viking://resources/project-a \+ --principal group:engineering --level read+ov --sudo admin remove-group-member acme engineering alice+ov --sudo admin delete-group acme engineering+```++The Python SDK exposes `admin_create_group`, `admin_list_groups`, `admin_list_group_members`, `admin_add_group_member`, `admin_remove_group_member`, and `admin_delete_group`. The Go SDK uses matching PascalCase method names.+## API Reference### get_agent_evolution_status@@ -103,15 +130,28 @@ Content-Type: application/json### account_settingsROOT can manage any account and ADMIN can manage only its own account. The-generic settings endpoint accepts only explicitly allowlisted fields; currently-only `agent_evolution.enabled` is writable.+generic settings endpoint accepts only explicitly allowlisted fields. It currently+allows `agent_evolution.enabled` and `resource_acl.auto_protect_new_content`.```httpGET /api/v1/admin/accounts/{account_id}/settingsPATCH /api/v1/admin/accounts/{account_id}/settingsContent-Type: application/json-{"agent_evolution": {"enabled": true}}+{+ "agent_evolution": {"enabled": true},+ "resource_acl": {"auto_protect_new_content": true}+}+```++`resource_acl.auto_protect_new_content` defaults to `false`. When enabled, newly+created shared files, directories, and `add-resource` roots grant their creator+direct `manage` while inheriting the parent ACL. Existing content is not migrated+or modified. Disabling it again affects only later creations; existing ACLs remain+effective.++```bash+ov --sudo admin set-account-settings acme --auto-protect-new-content true```Before an existing setting is replaced, it is backed up todiff --git a/docs/en/api/11-snapshot.md b/docs/en/api/11-snapshot.mdindex 5b19977bb..957f8d1fe 100644--- a/docs/en/api/11-snapshot.md+++ b/docs/en/api/11-snapshot.md@@ -23,6 +23,23 @@ In addition, account-level `.ovgitignore` exclusion rules can be managed (`get`/- **Forward-commit restore**: `restore` does **not** rewind or rewrite history. It reads the content at `source_commit`, writes the diff back into the workspace, and creates a **new commit on top of the current HEAD**. The new commit's parent is therefore the HEAD that existed before the restore — **not** `source_commit`. HEAD always advances monotonically and history is never lost.- **Scope**: `commit` can be limited to specific URIs via `paths`; `restore` can be limited to a subtree via `project_dir`, leaving files outside it untouched.+## ACL permissions++Snapshots use the current ACL at operation time. ACLs are not stored in snapshots, read from historical versions, or rolled back. Public resources without ACLs keep their legacy visibility; once ACL is enabled, these permissions apply:++| Operation | Required permission |+|-----------|---------------------|+| `show(path=...)` / `diff` / `log` | `read` |+| `commit` | `write`; directories recursively check every current descendant and fail as a whole if any node is denied |+| `restore` overwriting a file | `write` on the file |+| `restore` creating a file | `write` on the parent directory |+| `restore` deleting a file | `write` on the file |+| Read/write/delete `.ovgitignore` | ADMIN |++USER and ADMIN callers must provide `paths` for `commit` and `log`, `project_dir` for `restore`, and `path` for `show`; account-wide commit metadata lookup without `path` is reserved for local ROOT mode. A user can operate on accessible shared resources and their own `viking://user/{user_id}/...` space, but not another user's space. Directory operations preflight the complete scope instead of silently skipping denied descendants. `restore` authorizes every planned write and deletion before it mutates the workspace.++Existing nodes keep their current ACL after restore. Newly restored nodes inherit the current parent ACL; the user who runs `restore` is not granted `manage`. The background vector rebuild is system work for an already-authorized operation, so parent ACLs do not block it again.+## Implementation- HTTP routes: [snapshot.py](https://github.com/volcengine/OpenViking/blob/main/openviking/server/routers/snapshot.py), prefix `/api/v1/snapshot`.@@ -41,7 +58,7 @@ Save the current workspace state as a new snapshot.| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|| message | str | Yes | - | Commit message |-| paths | List[str] | No | null | `viking://` URIs to scope the snapshot to; entries may be files or directories. Directories are expanded recursively with the snapshot pruning rules applied. `null` snapshots the whole account tree. An empty list `[]` is forwarded as an explicit empty path set (no-op). A path that exists in neither the VFS nor the previous snapshot logs a warning and is treated as a no-op deletion |+| paths | List[str] | No | null | `viking://` URIs to scope the snapshot to; entries may be files or directories. Directories are expanded recursively with the snapshot pruning rules applied. USER/ADMIN callers must provide this field; `null` account-wide snapshots are reserved for local ROOT mode. An empty list `[]` is forwarded as an explicit empty path set (no-op). A path that exists in neither the VFS nor the previous snapshot logs a warning and is treated as a no-op deletion || branch | str | No | `main` | Branch to advance || author_name | str | No | null | Override the default author name (default `viking-bot`) || author_email | str | No | null | Override the default author email |@@ -125,7 +142,7 @@ Starting from a branch's HEAD, walk history along the first parent (`parents[0]`|-----------|------|----------|---------|-------------|| branch | str | No | `main` | Branch to walk || limit | int | No | 20 | Max commits to return. The HTTP endpoint accepts values from 1 to 500 |-| paths | List[str] | No | null | Return only commits that changed any specified `viking://` URI; files and directories are supported. At most 32 paths are accepted, and each account-relative path may contain at most 64 components. Pass multiple URIs to HTTP as repeated `paths` query parameters |+| paths | List[str] | No | null | Return only commits that changed any specified `viking://` URI; USER/ADMIN callers must provide it, while local ROOT mode may omit it for account-wide history. At most 32 paths are accepted, and each account-relative path may contain at most 64 components. Pass multiple URIs to HTTP as repeated `paths` query parameters |Filtering happens before the result limit is applied, so `limit=10` with `paths=[X]` returns up to 10 commits related to X rather than filtering only the 10 newest commits.@@ -219,12 +236,12 @@ View a commit's metadata; if `path` is given, return that file's content from th| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|| target_ref | str | Yes | - | Commit OID (abbreviated prefix allowed), branch name, or tag |-| path | str | No | null | `viking://` URI of a single file; omit to return commit metadata |+| path | str | No | null | `viking://` URI of a single file; omitting it returns commit metadata only in local ROOT mode |**Python HTTP SDK**```python-# View commit metadata+# View commit metadata (local ROOT mode only)meta = client.snapshot.show("3f2a1b9c")print(meta["message"], meta["parents"])@@ -247,7 +264,7 @@ GET /api/v1/snapshot/show?target_ref={ref}[&path={uri}]``````bash-# Commit metadata (returns JSON)+# Commit metadata (returns JSON; local ROOT mode only)curl -X GET "http://localhost:1933/api/v1/snapshot/show?target_ref=3f2a1b9c" \-H "X-API-Key: your-key"@@ -264,7 +281,7 @@ Without `path`, the response is commit metadata JSON. With `path`, the response**CLI**```bash-# Commit metadata+# Commit metadata (local ROOT mode only)ov snapshot show 3f2a1b9c -o json# Read file content (defaults to stdout; use --out-file to write to a local file)@@ -377,7 +394,7 @@ This is a **forward-commit restore**: it computes the diff between `source_commi| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|| source_commit | str | Yes | - | What to restore from: commit OID (abbreviated prefix allowed), branch name, or tag |-| project_dir | str | No | null | `viking://` URI of the subtree to restore; omit to restore the whole account tree |+| project_dir | str | No | null | `viking://` URI of the subtree to restore. USER/ADMIN callers must provide it; omitting it for a whole-account restore is reserved for local ROOT mode || branch | str | No | `main` | Branch to advance || dry_run | bool | No | false | Compute and return the diff only; write nothing || message | str | No | null | Message for the new commit; auto-generated when omitted |@@ -506,7 +523,7 @@ The `.ovgitignore` file at the account root is an account-level exclusion file.The syntax is a common glob subset: blank lines are ignored, `#`-prefixed lines are comments, leading/trailing whitespace is trimmed; `!` negation and backslash escaping are **unsupported**; the file is capped at 64 KiB (validated on write). Matching uses account-relative Git tree paths (`/`-separated).-Three methods are provided: `get_gitignore` (read, empty string when absent), `set_gitignore` (write), and `delete_gitignore` (delete, missing is success and idempotent). All three only need the account from the request context and take no path argument.+Three methods are provided: `get_gitignore` (read, empty string when absent), `set_gitignore` (write), and `delete_gitignore` (delete, missing is success and idempotent). All three require ADMIN permission, use the account from the request context, and take no path argument.### get_gitignore()@@ -665,7 +682,7 @@ client.write(mode="create",wait=True,)-v1 = client.snapshot.commit(message="v1 initial import")+v1 = client.snapshot.commit(message="v1 initial import", paths=[root])# 2. Modify and commit v2client.write(@@ -674,10 +691,10 @@ client.write(mode="replace",wait=True,)-v2 = client.snapshot.commit(message="v2 update")+v2 = client.snapshot.commit(message="v2 update", paths=[root])# 3. Walk history-for c in client.snapshot.log(limit=10):+for c in client.snapshot.log(limit=10, paths=[root]):print(c["oid"][:8], c["message"])# 4. Restore the workspace to v1 (creates a new commit on top of v2)@@ -693,6 +710,7 @@ For more end-to-end examples, see the [examples/snapshot/](https://github.com/vo| Scenario | HTTP Status | Error Code ||----------|-------------|------------|| Branch/commit not found, or `show`'s `path` does not exist in that commit | 404 | `NOT_FOUND` |+| A required operation scope is omitted, or the caller lacks the corresponding ACL permission | 403 | `PERMISSION_DENIED` || Branch concurrently advanced during restore (CAS conflict) | 409 | `CONFLICT` || `.ovgitignore` too large, non-UTF-8, or containing unsupported `!` negation/backslash escaping (validated at `commit` time) | 400 | `INVALID_ARGUMENT` || Request body contains an unknown field (request model is `extra="forbid"`) | 400 | `INVALID_ARGUMENT` |diff --git a/docs/en/api/12-acl.md b/docs/en/api/12-acl.mdnew file mode 100644index 000000000..e3dc2890f--- /dev/null+++ b/docs/en/api/12-acl.md@@ -0,0 +1,272 @@+# ACL API++The ACL API manages direct grants on shared `viking://resources/...` nodes and reports their inherited effective permissions. Private resources do not accept ACLs and must be moved into the shared scope to be shared.++Read [Resource Access Control (ACL)](../concepts/15-acl.md) for the permission and inheritance model.++## Endpoint Summary++| Method | Path | Description |+|--------|------|-------------|+| GET | `/api/v1/acl?uri={uri}` | Get direct, inherited, and effective ACLs |+| PUT | `/api/v1/acl` | Replace the node's direct ACL |+| DELETE | `/api/v1/acl?uri={uri}` | Clear the node's direct ACL |+| POST | `/api/v1/acl/grant` | Set one principal's direct level |+| POST | `/api/v1/acl/revoke` | Remove one principal's direct grant |++Every endpoint requires `manage` on the target node. Account `ADMIN`s implicitly manage shared resources.++`viking://resources` is a fixed shared scope and cannot carry a direct ACL. The+account setting `resource_acl.auto_protect_new_content` defaults to `false`: new+content under a parent without ACLs keeps the legacy shared behavior, while a new+file or directory under an ACL-controlled parent inherits the parent permissions+and grants its creator direct `manage`. When the setting is enabled, newly created+shared files, directories, and `add-resource` roots grant the creator direct+`manage` even under an ACL-free parent; existing content remains unchanged.+Descendants within an `add-resource` import only inherit that grant.++## Data Structures++### ACL entry++```json+{+ "principal": "user:bob",+ "level": "read"+}+```++| Field | Type | Description |+|-------|------|-------------|+| `principal` | string | `user:{user_id}`, `group:{group_id}`, or `user:*` |+| `level` | string | `read`, `write`, or `manage` |++The caller supplies the account-unique, stable `group_id` through the [Admin API](./08-admin.md#groups). A group has no separate display name. After a group is deleted, its old principal no longer matches any request unless the same `group_id` is created again.++### ACL report++```json+{+ "uri": "viking://resources/project-a",+ "acl_enabled": true,+ "direct_entries": [+ {"principal": "user:bob", "level": "read"}+ ],+ "inherited_entries": [+ {"principal": "group:engineering", "level": "write"}+ ],+ "effective_entries": [+ {"principal": "group:engineering", "level": "write"},+ {"principal": "user:bob", "level": "read"}+ ]+}+```++| Field | Description |+|-------|-------------|+| `direct_entries` | Entries set directly on this node |+| `inherited_entries` | Merged direct ACLs from all ancestors |+| `effective_entries` | The merged direct and inherited entries |+| `acl_enabled` | `true` when this node or an ancestor has a direct ACL; read-only and derived |++The account `ADMIN` implicit `manage` permission is not included in these lists.++## Get an ACL++```+GET /api/v1/acl?uri={uri}+```++GET can report an existing target that has no context record: `direct_entries` is empty and inherited permissions are resolved from existing ancestor contexts. Mutating ACL endpoints require a context record for the target.++```bash+curl "http://localhost:1933/api/v1/acl?uri=viking%3A%2F%2Fresources%2Fproject-a" \+ -H "X-API-Key: your-key"+```++**Python SDK**++```python+report = client.acl_get("viking://resources/project-a")+```++**Go SDK**++```go+report, err := client.ACL(ctx, "viking://resources/project-a")+```++## Replace a Direct ACL++```+PUT /api/v1/acl+```++Request body:++```json+{+ "uri": "viking://resources/project-a",+ "entries": [+ {"principal": "user:bob", "level": "read"},+ {"principal": "group:engineering", "level": "write"}+ ]+}+```++`entries` completely replaces this node's direct ACL without changing direct ACLs on ancestors or descendants. Duplicate principals keep their highest level. An empty list is equivalent to deleting this node's direct ACL.++```bash+curl -X PUT http://localhost:1933/api/v1/acl \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "uri": "viking://resources/project-a",+ "entries": [+ {"principal": "user:bob", "level": "read"},+ {"principal": "group:engineering", "level": "write"}+ ]+ }'+```++**Python SDK**++```python+report = client.acl_set(+ "viking://resources/project-a",+ [+ {"principal": "user:bob", "level": "read"},+ {"principal": "group:engineering", "level": "write"},+ ],+)+```++The asynchronous client uses the same method name:++```python+report = await client.acl_set(uri, entries)+```++**Go SDK**++```go+report, err := client.SetACL(ctx, "viking://resources/project-a", []openviking.ACLEntry{+ {Principal: "user:bob", Level: "read"},+ {Principal: "group:engineering", Level: "write"},+})+```++**CLI**++```bash+ov acl set viking://resources/project-a \+ --entry user:bob=read \+ --entry group:engineering=write+```++## Set One Principal's Level++```+POST /api/v1/acl/grant+```++```json+{+ "uri": "viking://resources/project-a",+ "principal": "user:bob",+ "level": "write"+}+```++This sets Bob's direct level on the current node to `write`. It updates an existing direct entry without changing other principals.++```bash+curl -X POST http://localhost:1933/api/v1/acl/grant \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "uri": "viking://resources/project-a",+ "principal": "user:bob",+ "level": "write"+ }'+```++```python+report = client.acl_grant(+ "viking://resources/project-a",+ principal="user:bob",+ level="write",+)+```++```bash+ov acl grant viking://resources/project-a --principal user:bob --level write+```++## Remove One Direct Grant++```+POST /api/v1/acl/revoke+```++```json+{+ "uri": "viking://resources/project-a",+ "principal": "user:bob"+}+```++`revoke` removes only Bob's direct entry on the current node. Any permission inherited by Bob from an ancestor remains effective.++```python+report = client.acl_revoke("viking://resources/project-a", principal="user:bob")+```++```bash+ov acl revoke viking://resources/project-a --principal user:bob+```++## Clear the Node's Direct ACL++```+DELETE /api/v1/acl?uri={uri}+```++This does not remove direct ACLs on descendants. The current node is recalculated from its ancestors, while each descendant continues to combine its own direct ACL with its ancestors.++```bash+curl -X DELETE \+ "http://localhost:1933/api/v1/acl?uri=viking%3A%2F%2Fresources%2Fproject-a" \+ -H "X-API-Key: your-key"+```++```python+report = client.acl_delete("viking://resources/project-a")+```++```bash+ov acl rm viking://resources/project-a+```++## Errors++The API checks manage permission before confirming existence to an authorized caller, preventing resource discovery through error types.++| Scenario | Error |+|----------|-------|+| URI is outside `viking://resources/...` | `INVALID_ARGUMENT` |+| Caller lacks manage | `PERMISSION_DENIED` |+| Authorized caller targets a URI that does not exist | `NOT_FOUND` |+| ACL mutation targets a URI without a context record | `INVALID_ARGUMENT`; index it first |+| Invalid `principal` syntax or `group:*` | `INVALID_ARGUMENT` |+| Level is not `read/write/manage` | `INVALID_ARGUMENT` |+| Request includes unknown fields such as `acl_enabled` | `INVALID_ARGUMENT` |++Direct and inherited ACL fields are both stored in context records. An update changes the target direct ACL and recalculates descendant inherited ACLs in one subtree batch; a failed write restores the previous context ACL fields.++## Related Documentation++- [Resource Access Control (ACL)](../concepts/15-acl.md) - Permissions, inheritance, and retrieval semantics+- [Authentication](../guides/04-authentication.md) - Request identity and account roles+- [Filesystem API](./03-filesystem.md) - ACL-controlled file operations+- [Retrieval API](./06-retrieval.md) - `find/search` endpointsdiff --git a/docs/en/api/12-content.md b/docs/en/api/12-content.mdindex fa70f1f03..5218610db 100644--- a/docs/en/api/12-content.md+++ b/docs/en/api/12-content.md@@ -577,7 +577,7 @@ This API operates on existing `viking://...` content. It does not import new fil**Authentication**-- HTTP endpoint: requires admin/root role when authentication is enabled. In `api_key` mode, use an admin key for tenant content; a raw root key cannot access tenant-scoped data.+- In `api_key` mode, shared `viking://resources/...` targets require an admin key. A regular user key may reindex only its own `viking://user/<user_id>/...` namespace, including the equivalent `viking://~/...` home alias. A root key cannot access tenant-scoped data APIs.- Python HTTP client / CLI: sends the current authenticated identity**Parameters**diff --git a/docs/en/concepts/04-viking-uri.md b/docs/en/concepts/04-viking-uri.mdindex 1054d8f42..7464adb57 100644--- a/docs/en/concepts/04-viking-uri.md+++ b/docs/en/concepts/04-viking-uri.md@@ -114,6 +114,8 @@ viking://~/resources/docs/ # Your private resource directoryviking://user/{user_id}/memories/ # Explicit user path (your own id; other ids need admin/root)```+`viking://resources/...` is the shared scope for the current account and supports per-directory or per-file [ACLs](./15-acl.md). `viking://user/{user}/resources/...` is private; move a resource into the shared scope to share it.+### User Skills and Peer Content```diff --git a/docs/en/concepts/11-multi-tenant.md b/docs/en/concepts/11-multi-tenant.mdindex cc9f598f5..19026a98a 100644--- a/docs/en/concepts/11-multi-tenant.md+++ b/docs/en/concepts/11-multi-tenant.md@@ -13,7 +13,7 @@ With multi-tenancy enabled, you can:- Serve multiple teams, customers, or applications from one OpenViking Server- Isolate different teams with `account`-- Share `resources` within the same `account`+- Share `resources` within the same `account`, with ACLs for per-directory or per-file grants- Isolate user memories and sessions with `user`- Manage permissions with ROOT / ADMIN / USER roles- Support different integration patterns such as OpenClaw plugin, Vikingbot, CLI, and HTTP SDKs@@ -75,7 +75,7 @@ If `auth_mode = "api_key"` and `root_api_key` is not configured, the server runs| Data type | Shared across accounts | Shared inside one account | Default isolation boundary ||-----------|------------------------|---------------------------|----------------------------|-| Shared resources (`viking://resources`) | No | Yes | account |+| Shared resources (`viking://resources`) | No | Shared by default; ACL can restrict | account / ACL || User resources (`viking://user/{user_id}/resources`) | No | No | user || Peer resources (`viking://user/{user_id}/peers/{peer_id}/resources`) | No | No | user / peer || Memories | No | No | user / peer |@@ -109,8 +109,9 @@ So multi-tenant isolation does not rely on a special public URI format. It relieFilesystem operations and semantic retrieval are tenant-aware:- Non-ROOT requests are automatically filtered by `account_id`-- `resources` can include account-shared resources-- `memory`, user resources, and `skill` are further filtered by the current user space+- `resources` includes account-shared resources by default and uses effective ACLs when configured+- User resources remain isolated to the current user space; move them to `viking://resources` to share them+- `memory` and `skill` remain filtered by the current user space- An actor peer filters `viking://user/{user}/peers` to one peer for filesystem and retrieval operationsThis keeps "what you can search" aligned with "what you can read."@@ -224,7 +225,7 @@ Characteristics of this model:- Simple integration, because the plugin does not manage account/user lifecycle- Best for "one OpenClaw instance maps to one OpenViking user identity"- `peer_prefix` distinguishes OpenClaw runtime identities when building peer/session metadata-- `resources` can be shared inside the same account, while user memory stays user-scoped+- `resources` are shared by default inside the same account and can be restricted with ACLs, while user memory stays user-scoped### Why the OpenClaw plugin usually does not set `account` / `user`@@ -265,7 +266,7 @@ Example config:Characteristics of this model:- Good for one bot service serving many chat users-- All users inside the same account share `resources`+- `resources` are shared by default inside the same account; ACLs can refine access to individual directories or files- User memories are isolated through auto-managed user identities- The bot takes on more tenant lifecycle management logic than the OpenClaw plugin@@ -321,6 +322,8 @@ That is only dev mode:- [Configuration](../guides/01-configuration.md) - `root_api_key` and `auth_mode`- [Admin API](../api/08-admin.md) - Admin API reference- [API Overview](../api/01-overview.md) - CLI and HTTP connection patterns+- [Resource Access Control (ACL)](./15-acl.md) - In-account resource grants, inheritance, and retrieval filtering+- [ACL API](../api/12-acl.md) - HTTP, SDK, and CLI interfaces- [Data Encryption](./10-encryption.md) - At-rest encryption in multi-tenant deployments- [Multi-tenant Example](https://github.com/volcengine/OpenViking/blob/main/examples/multi_tenant/README.md) - End-to-end management workflow- [OpenClaw Plugin](https://github.com/volcengine/OpenViking/blob/main/examples/openclaw-plugin/README.md) - OpenClaw integrationdiff --git a/docs/en/concepts/15-acl.md b/docs/en/concepts/15-acl.mdnew file mode 100644index 000000000..219a848af--- /dev/null+++ b/docs/en/concepts/15-acl.md@@ -0,0 +1,168 @@+# Resource Access Control (ACL)++OpenViking ACL shares directories or files from the shared resource scope with users or groups inside one account. ACL never changes the account boundary: every grant is limited to the current account.++ACL uses a collaborative-document inheritance model. A directory grant continuously applies to its descendants, while child directories and files can add direct grants. A child ACL does not replace grants inherited from ancestors.++## Supported URIs++ACL applies only to shared resources:++```text+viking://resources/...+```++- An account `ADMIN` implicitly has `manage` on `viking://resources/...`.+- `viking://resources` is a fixed shared scope and cannot carry a direct ACL. ACLs start on files and directories below it.+- `viking://user/{user_id}/resources/...` is private and does not accept ACLs. To share it, move the resource into a writable shared directory and inherit that directory's ACL.++Implicit management is not stored as an ACL entry and cannot be removed by ACL changes. It ensures that shared resources always have an identity that can establish or recover permissions.++## Principals and Levels++ACL entries use typed principals:++- `user:{user_id}`: a user in the current account.+- `group:{group_id}`: a caller-supplied, account-unique group ID.+- `user:*`: any user in the current account.++`group:*` is not supported. Groups are flat. Membership changes do not rewrite resource ACL or context records; they take effect when the next request builds `RequestContext.group_ids`.+Asynchronous parse and semantic tasks created by a request carry the same group identity. After an `add-resource` destination write has been authorized, automatic semantic maintenance preserves that identity and uses an explicit internal ACL bypass instead of changing the caller's role.++| Level | Allowed operations |+|-------|--------------------|+| `read` | Read, list, and `find/search/grep` |+| `write` | `read` capabilities plus write, create, file delete/move, and tag updates |+| `manage` | `write` capabilities plus directory delete/move and ACL management |++Each higher level includes the lower levels. A `manage` grant therefore includes `read` and `write`.++## Inheritance++A node's effective ACL is the union of every ancestor's direct ACL and the node's own direct ACL:++```text+effective(node) = UNION(direct_acl(each ancestor), direct_acl(node))+```++For example:++```text+read user:bob on viking://resources/A+write group:engineering on viking://resources/A/B+read user:carol on viking://resources/A/B/C/report.md+```++The effective permissions on `report.md` are:++- Bob: `read`+- Members of `engineering`: `write`+- Carol: `read`++Removing the group's direct ACL from `A/B` does not remove entries from `A` or `report.md`. Descendants only lose the permissions contributed by that entry.++## Default Behavior and `acl_enabled`++The account-level `resource_acl.auto_protect_new_content` setting is disabled by+default. While disabled, creating a file or directory under an ACL-free parent+keeps the existing URI namespace visibility and write rules. Under an+ACL-controlled parent, the creator receives direct `manage` and inherits the+parent permissions.++When enabled, a newly created shared file or directory grants its creator direct+`manage` on its first context record even under an ACL-free parent; parent+permissions are still merged as inherited ACL. Existing content is not migrated+or modified, and disabling the setting again affects only later creations.+`add-resource` treats only the generated import root (or the root file with+`no_split`) as the created node: the root gets the direct creator grant and+descendants only inherit it. Re-embedding or replacing an existing context record+does not change its direct ACL.++When the node or any ancestor has a direct ACL, the node enters the ACL-controlled domain:++```text+acl_enabled = true+```++`acl_enabled` is derived by the system and cannot be set by an API caller. It returns to `false` automatically after the last applicable direct ACL is removed.++## File Operations++All filesystem APIs use the same permission mapping:++| Operation | Required capability |+|-----------|---------------------|+| read, stat, list, tree, find, search, grep, glob, relations | read |+| write, create, mkdir, set tags | write |+| delete or move a file | write |+| delete or move a directory | manage on the directory and complete subtree |+| manage ACL | manage |+| move destination parent | write |++The server canonicalizes the URI, then uses one authorization entry point for account/owner/actor-peer boundaries, the effective ACL or legacy fallback, and write/delete namespace guards.++Under an ACL-controlled parent, or when the account enables+`auto_protect_new_content`, a new shared node is bootstrapped by its creator's+direct `manage` grant. Otherwise only the shared scope's implicit `manage` identity can+establish the first ACL. Later ACL changes require effective `manage` capability.++An ACL grant on a directory is inherited by every descendant. `list`, `tree`, and other batch results still check every returned node because an ACL-free directory may be visible under legacy URI rules while one of its descendants has entered the ACL-controlled domain through its own ACL.++Within the shared scope, a moved node keeps its direct ACL and recalculates inherited permissions from its new ancestors. A private resource moved into the shared scope carries no ACL and inherits the destination directory; a shared resource moved back to a private area has its ACL cleared.++Recursive tag updates, directory deletion, and directory moves validate the complete affected subtree first. The operation stops if any node lacks the required capability or the subtree cannot be scanned completely.++For a directory, `stat.count` uses the same path and ACL scalar filter and reports the number of context records visible to the caller.++## Retrieval Filtering++ACL data exists only in the context collection. Each context record stores direct and inherited permissions in native scalar fields:++```text+acl_enabled+acl_direct_grants+acl_inherited_grants+```++`acl_direct_grants` is the ACL assigned to the current node. `acl_inherited_grants` is the union of all ancestor direct ACLs. Each principal stores only its highest level as `{mask}:{principal}`: `1` means `read`, `3` means `write`, and `7` means `manage`. For example, `3:group:dev` gives `group:dev` `write` and therefore also `read`. Effective permission is the union of the two fields; there is no separate ACL collection.++The request principals are `user:{ctx.user_id}`, `user:*`, and one `group:{group_id}` for each ID in `ctx.group_ids`. For reads, `find/search` matches the `1`, `3`, and `7` tokens for each principal against both native `list<string>` grant fields within the `viking://resources` scope; private resources remain isolated by URI owner. Legacy records without ACL fields are treated as `acl_enabled=false`, so they do not require a full data backfill.++A retrieval target URI is only a search scope; the caller does not need to read the target node itself. A user can discover a deeply shared file even when intermediate directories are not readable.++Shared-scope context writes preserve an existing direct ACL for the same URI.+Under an ACL-controlled parent, or when the account enables+`auto_protect_new_content`, a newly created node receives direct `manage` for its+creator and derives inherited ACL fields from its parent; otherwise it remains+`acl_enabled=false`. Descendants created by `add-resource` only inherit from the+import root. Re-embedding and ordinary replacement writes cannot reset controlled+records to default visibility or modify ACLs through regular context fields.++## Example++Grant Bob read-only access to a directory:++```bash+ov acl grant viking://resources/project-a --principal user:bob --level read+```++Bob can read and retrieve descendants, but cannot write or delete them. Upgrade the grant to `write`:++```bash+ov acl grant viking://resources/project-a --principal user:bob --level write+```++Remove Bob's direct grant from this node:++```bash+ov acl revoke viking://resources/project-a --principal user:bob+```++If an ancestor still grants Bob access, that inherited permission remains effective.++## Related Documentation++- [ACL API](../api/12-acl.md) - HTTP, SDK, and CLI interfaces+- [Multi-Tenant](./11-multi-tenant.md) - Account, user, and role boundaries+- [Viking URI](./04-viking-uri.md) - URI namespaces+- [Retrieval](./07-retrieval.md) - Hierarchical retrieval flowdiff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.mdindex 52c0851fe..46cf0d77f 100644--- a/docs/en/guides/01-configuration.md+++ b/docs/en/guides/01-configuration.md@@ -1429,6 +1429,55 @@ Supports cloud-deployed VikingDB on Volcengine```</details>+##### ACL schema++ACL data exists only in the context collection. In addition to `acl_enabled: bool`, add these scalar-indexed `list<string>` fields:++```text+acl_direct_grants+acl_inherited_grants+```++Each element uses `{mask}:{principal}`: `1` means `read`, `3` means `write`, and `7` means `manage`.++Local backends add the fields to an existing collection and rebuild the scalar index during startup. Existing records are not rewritten; missing ACL fields read as `acl_enabled=false` and empty lists.++For existing remote collections, including Volcengine VikingDB, provision these fields and scalar indexes before startup; OpenViking validates but does not alter the remote schema. Volcengine API-key data-plane mode also requires the context collection and configured index to exist. See [Resource Access Control (ACL)](../concepts/15-acl.md) for permission semantics.++<details>+<summary><b>openGauss</b></summary>++Requires an openGauss server with native `vector` support and a remote-capable database user.+Install the optional driver with `pip install "openviking[opengauss]"`.+In the official container, the initial `omm` user may be restricted for remote login; create a normal user for OpenViking if needed.++```json+{+ "storage": {+ "vectordb": {+ "name": "context",+ "backend": "opengauss",+ "project": "default",+ "distance_metric": "cosine",+ "dimension": 1024,+ "opengauss": {+ "host": "127.0.0.1",+ "port": 5432,+ "user": "openviking",+ "password": "your-password",+ "db_name": "postgres",+ "schema": "public",+ "mode": "standalone"+ }+ }+ }+}+```++Set `mode` to `"distributed"` for openGauss distributed deployments; OpenViking will attempt to mark metadata tables as reference tables and distribute collection tables by `id`.+</details>++## Config FilesOpenViking uses two config files:diff --git a/docs/en/guides/04-authentication.md b/docs/en/guides/04-authentication.mdindex c95c9adde..ee5eb76eb 100644--- a/docs/en/guides/04-authentication.md+++ b/docs/en/guides/04-authentication.md@@ -72,6 +72,40 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts/acme/users \# Returns: {"result": {"account_id": "acme", "user_id": "bob", "user_key": "..."}}```+ACL groups are the exception: groups and memberships are maintained through the [Admin API](../api/08-admin.md#groups), and members must be registered users in the current account. Clients cannot assert groups through headers or token claims. After authentication, the server resolves the group registry into `RequestContext.group_ids` for that request.++Trusted deployments can also call Admin API through a trusted gateway. There are two supported patterns:++- 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 trusted upstream identity:++```bash+# First, register the gateway admin (do this once in api_key mode)+curl -X POST http://localhost:1933/api/v1/admin/accounts \+ -H "X-API-Key: your-secret-root-key" \+ -H "Content-Type: application/json" \+ -d '{"account_id": "platform", "admin_user_id": "gateway-admin"}'++# Then promote it to root if it needs cross-account admin access+curl -X PUT http://localhost:1933/api/v1/admin/accounts/platform/users/gateway-admin/role \+ -H "X-API-Key: your-secret-root-key" \+ -H "Content-Type: application/json" \+ -d '{"role": "root"}'++# Then, in trusted mode, use that identity to call Admin API+curl -X POST http://localhost:1933/api/v1/admin/accounts \+ -H "X-API-Key: your-secret-root-key" \+ -H "X-OpenViking-Account: platform" \+ -H "X-OpenViking-User: gateway-admin" \+ -H "Content-Type: application/json" \+ -d '{+ "account_id": "acme",+ "admin_user_id": "alice"+ }'+```+### Client UsageOpenViking accepts API keys via two headers:@@ -153,7 +187,12 @@ The `--sudo` flag:Tenant-scoped data APIs (for example `ls`, `find`, resources, and sessions) must use a key that is bound to an account/user in `api_key` mode. That can be a `USER` key or an `ADMIN` key; an `ADMIN` key accesses data as its own user and cannot switch identity with `X-OpenViking-Account` / `X-OpenViking-User`.-A `ROOT` key is not bound to a tenant user, so it cannot access tenant-scoped data APIs in `api_key` mode. If a deployment needs an upstream gateway to assert `account` / `user`, use `trusted` mode instead of passing identity headers with a root key.+ACL checks also use account groups resolved by the server. Membership changes take effect on the next request without issuing a new API key or modifying resource ACLs.++A `ROOT` key is not bound to a tenant user, so it cannot access tenant-scoped+data APIs in `api_key` mode. If a deployment needs an upstream gateway to assert+`account` / `user`, use `trusted` mode instead of passing identity headers with a+root key.## OIDC Authentication@@ -616,6 +655,8 @@ Or explicitly:| ADMIN | Own account | Regular operations + manage users in own account || USER | Own account | Regular operations (ls, read, find, sessions, etc.) |+Regular resource operations in this table are still subject to resource ACLs. Account roles determine identity administration and implicit management of public resources; [Resource Access Control (ACL)](../concepts/15-acl.md) determines `read/write/manage` permissions on individual directories and files.+In `trusted` mode, ordinary tenant requests default to `USER` unless the account/user is registered with a higher role or the gateway asserts `X-OpenViking-Role: admin` with the configured root API key. `X-OpenViking-Role: root` is rejected. Admin routes also allow a trusted ROOT fallback when no explicit identity is provided.## Unauthenticated Endpoints@@ -792,6 +833,7 @@ ov doctor## Related Documentation- [Multi-Tenant](../concepts/11-multi-tenant.md) - Multi-tenant capabilities, sharing boundaries, and integration patterns+- [Resource Access Control (ACL)](../concepts/15-acl.md) - Resource permissions inside an account- [Configuration](01-configuration.md) - Configuration file reference- [Deployment](03-deployment.md) - Server deployment- [API Overview](../api/01-overview.md) - API referencediff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.mdindex 278039a87..2b4dc43be 100644--- a/docs/zh/api/01-overview.md+++ b/docs/zh/api/01-overview.md@@ -363,6 +363,16 @@ JSON 输出 - 错误:| DELETE | `/api/v1/fs` | 删除资源 || POST | `/api/v1/fs/mv` | 移动或重命名资源 |+### [ACL](12-acl.md)++| 方法 | 路径 | 说明 |+|------|------|------|+| GET | `/api/v1/acl` | 获取资源的直接、继承和有效 ACL |+| PUT | `/api/v1/acl` | 替换资源的直接 ACL |+| DELETE | `/api/v1/acl` | 清空资源的直接 ACL |+| POST | `/api/v1/acl/grant` | 设置一个 principal 的直接权限级别 |+| POST | `/api/v1/acl/revoke` | 删除一个 principal 的直接授权 |+### [内容](12-content.md)| 方法 | 路径 | 说明 |@@ -480,6 +490,12 @@ JSON 输出 - 错误:| DELETE | `/api/v1/admin/accounts/{account_id}/users/{user_id}` | 移除用户 || PUT | `/api/v1/admin/accounts/{account_id}/users/{user_id}/role` | 将用户提升为 ADMIN || POST | `/api/v1/admin/accounts/{account_id}/users/{user_id}/key` | 重新生成用户 Key |+| POST | `/api/v1/admin/accounts/{account_id}/groups` | 创建用户组 |+| GET | `/api/v1/admin/accounts/{account_id}/groups` | 列出用户组 |+| DELETE | `/api/v1/admin/accounts/{account_id}/groups/{group_id}` | 删除用户组 |+| GET | `/api/v1/admin/accounts/{account_id}/groups/{group_id}/members` | 列出用户组成员 |+| PUT | `/api/v1/admin/accounts/{account_id}/groups/{group_id}/members/{user_id}` | 添加用户组成员 |+| DELETE | `/api/v1/admin/accounts/{account_id}/groups/{group_id}/members/{user_id}` | 移除用户组成员 || GET | `/api/v1/privacy-configs` | 列出隐私配置分类 || GET | `/api/v1/privacy-configs/{category}` | 列出分类目标 || GET | `/api/v1/privacy-configs/{category}/{target_key}` | 获取生效配置 |@@ -521,5 +537,5 @@ JSON 输出 - 错误:| 检索 | 语义检索、代码检索 || 数据生命周期 | Watch、快照、OVPack || 运维与观测 | 系统、任务、Observer、Metrics |-| 身份与治理 | 管理员、隐私配置 |+| 身份与治理 | 管理员、ACL、隐私配置 || 协议与扩展 | OpenViking Assets、WebDAV、VikingBot API |diff --git a/docs/zh/api/02-resources.md b/docs/zh/api/02-resources.mdindex 2acf9e5b1..83b1204f9 100644--- a/docs/zh/api/02-resources.md+++ b/docs/zh/api/02-resources.md@@ -179,6 +179,8 @@ URL/文件 Parser TreeBuilder AGFS Summarizer/Vector**补充说明**:- `to` 和 `parent` 不能同时使用。`to` 是最终保存位置:目标不存在就创建,目标已存在就覆盖该目标;如果目标是目录,目录里本次导入没有生成的旧文件或子目录会被删除。`parent` 是保存目录,适合向已有目录追加新资源;父目录不存在时使用 `create_parent=true` 或 CLI 的 `--parent-auto-create`。当导入后的 `root_uri` 与 `to` 相同时,语义与向量处理会复用未变化内容,只处理变化部分。+- 创建新资源要求目标父目录可写;显式更新已有 `to` 要求该目标可写。权限校验在任务入队前完成。自动命名按实际 URI 占用判断,即使同名资源不可读也会选择 `_1`、`_2` 等后缀,而不会尝试覆盖。+- `wait=false` 返回的 `status=accepted` 表示任务已通过预检查并入队,不表示资源处理已经完成;最终状态以对应 `task_id` 为准。- 如果同时省略 `to` 和 `parent`,服务端会先尝试使用当前用户的 `add_targets.resource_uri` 覆盖配置,再使用 `server.user_config_defaults.add_targets.resource_uri`。两者都没有配置时,保持旧的目标解析行为。- 资源目标可以使用公共 `viking://resources/...`、家目录别名 `viking://~/resources/...`、显式用户 `viking://user/{user_id}/resources/...`,或 peer 级 `viking://user/{user_id}/peers/{peer_id}/resources/...`。家目录别名会按请求身份展开为 canonical 路径;无 uid 的写法 `viking://user/resources/...` 会被拒绝,并提示改用 `viking://~/resources/...`。- `user_id` 和 `peer_id` 路径片段必须是安全的单段标识,例如 `alice` 或 `web-visitor-alice`。包含路径分隔符、`.`、`..`、`:` 或 `+` 的值会被拒绝。@@ -549,12 +551,8 @@ ov add-resource ./documents/guide.md -p viking://resources/docs/{calendar:today}{"status": "ok","result": {- "status": "success",+ "status": "accepted","root_uri": "viking://resources/guide",- "temp_uri": "viking://temp/username/04291108_b62dc7/guide",- "source_path": "./documents/guide.md",- "meta": {},- "errors": [],"task_id": "uuid-xxx"}}@@ -567,7 +565,7 @@ ov add-resource ./documents/guide.md -p viking://resources/docs/{calendar:today}```Note: Resource is being processed in the background.Use 'ov wait' to wait for completion, or 'ov observer queue' to check status.-status success+status acceptedroot_uri viking://resources/01-overviewtask_id uuid-xxx```@@ -576,7 +574,7 @@ task_id uuid-xxx```json{- "status": "success",+ "status": "accepted","root_uri": "viking://resources/01-overview","task_id": "uuid-xxx"}@@ -586,7 +584,7 @@ task_id uuid-xxx| 字段 | 类型 | 说明 ||------|------|------|-| `status` | string | 处理状态:"success" 成功,"error" 失败 |+| `status` | string | 处理状态:`accepted` 表示已入队,`success` 表示成功,`error` 表示失败 || `root_uri` | string | 资源在 OpenViking 中的最终 URI || `task_id` | string | (可选,仅当 `wait=false` 时)可轮询 `/api/v1/tasks/{task_id}` 的任务 ID。非 Git 导入用于队列跟踪;Git 仓库导入用于完整后台导入跟踪。 || `temp_uri` | string | 导入过程中生成的临时 URI |diff --git a/docs/zh/api/03-filesystem.md b/docs/zh/api/03-filesystem.mdindex 653c17ded..aac02e156 100644--- a/docs/zh/api/03-filesystem.md+++ b/docs/zh/api/03-filesystem.md@@ -41,6 +41,23 @@ OpenViking 提供类 Unix 的文件系统操作来管理上下文。}```+如果调用方可以读取父目录,但没有某个直接子项的读取权限,`ls` 仍会返回该+子项的名称占位,但不会返回大小、修改时间、摘要或存储元数据:++```python+{+ "name": "restricted",+ "isDir": True,+ "uri": "viking://resources/restricted",+ "access": "denied"+}+```++对这个 URI 调用 `stat`、`read` 等内容接口会返回 HTTP 403 `PermissionDenied`。递归+列举会保留无权限目录本身,但不会继续展开其内容,搜索结果也不会包含无权读取的+内容。该行为只适用于共享的+`viking://resources` 命名空间;个人和 peer 私有命名空间仍按原有规则隐藏。+**Python HTTP SDK**diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.mdindex cd3e95f65..b9be1f05f 100644--- a/docs/zh/api/08-admin.md+++ b/docs/zh/api/08-admin.md@@ -1,6 +1,6 @@# 管理员(多租户)-Admin API 用于多租户环境下的账户和用户管理。包括工作区(account)的创建与删除、用户注册与移除、角色变更、API Key 重新生成。+Admin API 用于多租户环境下的账户、用户和用户组管理。包括工作区(account)的创建与删除、用户注册与移除、用户组成员、角色变更、API Key 重新生成。该 API 适用于 `api_key` 和 `trusted` 两种模式下的管理链路:- 在 `api_key` 模式下,角色始终从 API Key 推导。@@ -21,6 +21,7 @@ Admin API 用于多租户环境下的账户和用户管理。包括工作区(a| 创建/删除工作区 | Y | N | N || 列出工作区 | Y | N | N || 注册/移除用户 | Y | Y(本 account) | N |+| 管理用户组和成员 | Y | Y(本 account) | N || 列出 agents(已废弃,返回空列表) | Y | Y(本 account) | N || 重新生成 User Key | Y | Y(本 account) | N || 将用户提升为 ADMIN | Y | Y(本 account) | N |@@ -55,6 +56,32 @@ Admin API 用于多租户环境下的账户和用户管理。包括工作区(a- `--sudo` 仅适用于上面的命令,用于普通数据命令会报错- 必须配置 `root_api_key` 才能使用 `--sudo`+## 用户组++用户组属于单个 account,用于通过一个 ACL principal 授权多个用户。`group_id` 由调用者创建时指定,使用与 `user_id` 相同的标识符规则,是 account 内唯一且稳定的标识;不存在单独的组名。组内只能加入当前 account 已存在的用户,不支持嵌套组。++成员关系由服务端加入每次请求的 `RequestContext.group_ids`。添加或移除成员从下一次请求开始生效,不重写资源 ACL 或 context 记录。用户被删除时会自动退出所有组;用户组必须为空才能删除。++| 方法 | 路径 | 说明 |+|------|------|------|+| POST | `/api/v1/admin/accounts/{account_id}/groups` | 创建空组,请求体为 `{"group_id":"engineering"}` |+| GET | `/api/v1/admin/accounts/{account_id}/groups` | 列出组 |+| DELETE | `/api/v1/admin/accounts/{account_id}/groups/{group_id}` | 删除空组 |+| GET | `/api/v1/admin/accounts/{account_id}/groups/{group_id}/members` | 列出成员 |+| PUT | `/api/v1/admin/accounts/{account_id}/groups/{group_id}/members/{user_id}` | 幂等添加成员;重复调用返回 `added=true` |+| DELETE | `/api/v1/admin/accounts/{account_id}/groups/{group_id}/members/{user_id}` | 移除成员;重复调用返回 `removed=false` |++```bash+ov --sudo admin create-group acme engineering+ov --sudo admin add-group-member acme engineering alice+ov acl grant viking://resources/project-a \+ --principal group:engineering --level read+ov --sudo admin remove-group-member acme engineering alice+ov --sudo admin delete-group acme engineering+```++Python SDK 提供对应的 `admin_create_group`、`admin_list_groups`、`admin_list_group_members`、`admin_add_group_member`、`admin_remove_group_member` 和 `admin_delete_group`;Go SDK 使用相同名称的 PascalCase 方法。+## API 参考### get_agent_evolution_status@@ -102,14 +129,26 @@ Content-Type: application/json### account_settingsROOT 可管理任意 account,ADMIN 仅可管理自己所属的 account。通用配置接口仅允许-显式列入白名单的字段;当前只允许修改 `agent_evolution.enabled`。+显式列入白名单的字段;当前允许修改 `agent_evolution.enabled` 和+`resource_acl.auto_protect_new_content`。```httpGET /api/v1/admin/accounts/{account_id}/settingsPATCH /api/v1/admin/accounts/{account_id}/settingsContent-Type: application/json-{"agent_evolution": {"enabled": true}}+{+ "agent_evolution": {"enabled": true},+ "resource_acl": {"auto_protect_new_content": true}+}+```++`resource_acl.auto_protect_new_content` 默认为 `false`。开启后,账号内新建的共享+文件、目录和 `add-resource` 根节点会给创建者直接 `manage`,同时继承父目录+ACL;已有内容不会迁移或改权。重新关闭只影响后续创建,已有 ACL 继续生效。++```bash+ov --sudo admin set-account-settings acme --auto-protect-new-content true```覆盖已有配置前,内核会先备份到diff --git a/docs/zh/api/11-snapshot.md b/docs/zh/api/11-snapshot.mdindex 9e02ccfd1..fa625e5b5 100644--- a/docs/zh/api/11-snapshot.md+++ b/docs/zh/api/11-snapshot.md@@ -23,6 +23,23 @@ OpenViking 在 VikingFS 之上提供了一套基于 Git 的多版本管理能力- **正向恢复(forward-commit restore)**:`restore` **不会**回退或改写历史。它会读取 `source_commit` 的内容,把差异写回工作区,并在当前 HEAD 之上**生成一个新的提交**。因此新提交的父提交是恢复操作发生前的 HEAD,而**不是** `source_commit`。HEAD 始终单调向前推进,历史永远不会丢失。- **作用范围**:`commit` 可以通过 `paths` 限定只快照部分 URI;`restore` 可以通过 `project_dir` 限定只恢复某个子目录,目录之外的文件保持不变。+## ACL 权限++快照使用操作发生时的当前 ACL,不保存、回滚或读取历史 ACL。未开启 ACL 的公共资源保持原有的全部可见行为;开启 ACL 后,权限要求如下:++| 操作 | 权限要求 |+|------|----------|+| `show(path=...)` / `diff` / `log` | `read` |+| `commit` | `write`;目录会递归检查当前全部子节点,任一子节点无权则整次失败 |+| `restore` 覆盖已有文件 | 文件的 `write` |+| `restore` 新建文件 | 父目录的 `write` |+| `restore` 删除文件 | 文件的 `write` |+| `.ovgitignore` 读写删除 | ADMIN |++USER 和 ADMIN 调用 `commit`、`log`、`restore` 时必须显式传入 `paths` 或 `project_dir`;`show` 必须传入 `path`,不带 `path` 的全局提交元数据查询只保留给本地 ROOT 模式。用户可以操作自己有权访问的公共资源和自己的 `viking://user/{user_id}/...`,不能访问其他用户空间。目录操作会先完整鉴权,不会静默跳过无权子节点;`restore` 会先鉴权全部写入和删除项,再开始修改。++恢复后的既有节点保留当前 ACL。被恢复的新节点继承当前父目录 ACL,不会给执行 `restore` 的用户额外授予 `manage`。后台向量重建属于已授权操作的系统工作,不会再次受父目录 ACL 阻断。+## API 实现介绍- HTTP 路由:[snapshot.py](https://github.com/volcengine/OpenViking/blob/main/openviking/server/routers/snapshot.py),前缀 `/api/v1/snapshot`。@@ -41,7 +58,7 @@ OpenViking 在 VikingFS 之上提供了一套基于 Git 的多版本管理能力| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|| message | str | 是 | - | 提交说明 |-| paths | List[str] | 否 | null | 限定本次快照的 `viking://` URI 列表,条目可以是文件或目录;目录会按照快照的剪枝规则递归展开。`null` 表示对整棵账号树做快照。传入空列表 `[]` 表示显式的空路径集(不会产生改动)。如果某个路径在 VFS 和前一次快照中都不存在,会输出一条 warn,并按"对该名称下任何子树执行删除"处理 |+| paths | List[str] | 否 | null | 限定本次快照的 `viking://` URI 列表,条目可以是文件或目录;目录会按照快照的剪枝规则递归展开。USER/ADMIN 必须显式传入;`null` 只保留给本地 ROOT 模式的整棵账号树快照。传入空列表 `[]` 表示显式的空路径集(不会产生改动)。如果某个路径在 VFS 和前一次快照中都不存在,会输出一条 warn,并按"对该名称下任何子树执行删除"处理 || branch | str | 否 | `main` | 要推进的分支 || author_name | str | 否 | null | 覆盖默认的提交者名字(默认 `viking-bot`) || author_email | str | 否 | null | 覆盖默认的提交者邮箱 |@@ -125,7 +142,7 @@ ov snapshot commit -m "v1 initial import" --paths viking://resources/my_md.md -o|------|------|------|--------|------|| branch | str | 否 | `main` | 要回溯的分支 || limit | int | 否 | 20 | 最多返回的提交数量。HTTP 接口限制范围为 1–500 |-| paths | List[str] | 否 | null | 只返回修改了任一指定 `viking://` URI 的提交;支持文件和目录。最多接受 32 条路径,每条 account-relative 路径最多包含 64 个层级。HTTP 接口通过重复 `paths` 查询参数传入多个 URI |+| paths | List[str] | 否 | null | 只返回修改了任一指定 `viking://` URI 的提交;USER/ADMIN 必须显式传入。本地 ROOT 模式可省略以查询全局历史。最多接受 32 条路径,每条 account-relative 路径最多包含 64 个层级。HTTP 接口通过重复 `paths` 查询参数传入多个 URI |过滤发生在限制返回数量之前,因此 `limit=10` 和 `paths=[X]` 表示最多返回 10 条与 X 有关的提交,而不是先取最近 10 条提交再过滤。@@ -219,12 +236,12 @@ ov snapshot log --limit 10 \| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|| target_ref | str | 是 | - | 提交 OID(支持缩写前缀)、分支名或标签 |-| path | str | 否 | null | 某个文件的 `viking://` URI;省略时返回提交元数据 |+| path | str | 否 | null | 某个文件的 `viking://` URI;省略时返回提交元数据,但仅限本地 ROOT 模式 |**Python HTTP SDK**```python-# 查看提交元数据+# 查看提交元数据(仅本地 ROOT 模式)meta = client.snapshot.show("3f2a1b9c")print(meta["message"], meta["parents"])@@ -247,7 +264,7 @@ GET /api/v1/snapshot/show?target_ref={ref}[&path={uri}]``````bash-# 提交元数据(返回 JSON)+# 提交元数据(返回 JSON,仅本地 ROOT 模式)curl -X GET "http://localhost:1933/api/v1/snapshot/show?target_ref=3f2a1b9c" \-H "X-API-Key: your-key"@@ -264,7 +281,7 @@ curl -X GET "http://localhost:1933/api/v1/snapshot/show?target_ref=3f2a1b9c&path**CLI**```bash-# 提交元数据+# 提交元数据(仅本地 ROOT 模式)ov snapshot show 3f2a1b9c -o json# 读取文件内容(默认输出到 stdout,可用 --out-file 写入本地文件)@@ -377,7 +394,7 @@ ov snapshot diff viking://resources/my_project/guide.md \| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|| source_commit | str | 是 | - | 要恢复到的来源:提交 OID(支持缩写前缀)、分支名或标签 |-| project_dir | str | 否 | null | 要恢复的子目录 `viking://` URI;省略时恢复整棵账号树 |+| project_dir | str | 否 | null | 要恢复的子目录 `viking://` URI;USER/ADMIN 必须显式传入,省略时恢复整棵账号树仅用于本地 ROOT 模式 || branch | str | 否 | `main` | 要推进的分支 || dry_run | bool | 否 | false | 仅计算并返回差异,不做任何写入 || message | str | 否 | null | 新提交的说明;省略时自动生成 |@@ -506,7 +523,7 @@ ov snapshot restore 3f2a1b9c viking://resources/my_project --dry-run -o json语法为常见 glob 子集:空行被忽略、`#` 开头为注释、行首尾空白被裁剪;**不支持** `!` 取反与反斜杠转义;文件大小上限 64 KiB(写入时即校验)。匹配路径为账号相对 Git 树路径(`/` 分隔)。-提供三个方法:`get_gitignore`(读取,缺失返回空串)、`set_gitignore`(写入)、`delete_gitignore`(删除,缺失即成功、幂等)。三者都只需请求上下文中的账号,无路径参数。+提供三个方法:`get_gitignore`(读取,缺失返回空串)、`set_gitignore`(写入)、`delete_gitignore`(删除,缺失即成功、幂等)。三者都要求 ADMIN 权限,只需请求上下文中的账号,无路径参数。### get_gitignore()@@ -665,7 +682,7 @@ client.write(mode="create",wait=True,)-v1 = client.snapshot.commit(message="v1 initial import")+v1 = client.snapshot.commit(message="v1 initial import", paths=[root])# 2. 修改后再提交 v2client.write(@@ -674,10 +691,10 @@ client.write(mode="replace",wait=True,)-v2 = client.snapshot.commit(message="v2 update")+v2 = client.snapshot.commit(message="v2 update", paths=[root])# 3. 查看历史-for c in client.snapshot.log(limit=10):+for c in client.snapshot.log(limit=10, paths=[root]):print(c["oid"][:8], c["message"])# 4. 把工作区恢复到 v1(会在 v2 之上生成一个新提交)@@ -693,6 +710,7 @@ client.close()| 场景 | HTTP 状态码 | 错误码 ||------|-------------|--------|| 分支/提交不存在,或 `show` 的 `path` 在该提交中不存在 | 404 | `NOT_FOUND` |+| 未传入必要的操作范围,或当前身份缺少对应 ACL 权限 | 403 | `PERMISSION_DENIED` || 恢复期间分支被并发提交改写(CAS 冲突) | 409 | `CONFLICT` || `.ovgitignore` 过大、非 UTF-8,或包含不支持的 `!` 取反/反斜杠转义语法(`commit` 时校验) | 400 | `INVALID_ARGUMENT` || 请求体包含未知字段(请求模型为 `extra="forbid"`) | 400 | `INVALID_ARGUMENT` |diff --git a/docs/zh/api/12-acl.md b/docs/zh/api/12-acl.mdnew file mode 100644index 000000000..1b6377fe8--- /dev/null+++ b/docs/zh/api/12-acl.md@@ -0,0 +1,270 @@+# ACL API++ACL API 管理 `viking://resources/...` 共享资源的直接授权,并返回节点继承后的有效权限。个人资源不接受 ACL,需要分享时应移动到共享区。++权限模型和继承规则请先阅读 [资源访问控制(ACL)](../concepts/15-acl.md)。++## 接口总览++| 方法 | 路径 | 说明 |+|------|------|------|+| GET | `/api/v1/acl?uri={uri}` | 获取直接、继承和有效 ACL |+| PUT | `/api/v1/acl` | 替换当前节点的直接 ACL |+| DELETE | `/api/v1/acl?uri={uri}` | 清空当前节点的直接 ACL |+| POST | `/api/v1/acl/grant` | 设置一个 principal 的直接权限级别 |+| POST | `/api/v1/acl/revoke` | 删除一个 principal 的直接授权 |++所有接口都要求调用者对目标节点拥有 `manage`。共享资源由 account `ADMIN` 隐式管理。++`viking://resources` 是固定共享 scope,不能设置直接 ACL。账号配置+`resource_acl.auto_protect_new_content` 默认为 `false`:父目录没有 ACL 时,新建内容+继续使用原有公开规则;父目录已有 ACL 时,新建文件或目录会继承父权限,并给创建者+直接 `manage`。开启该配置后,即使父目录没有 ACL,新建共享文件、目录和+`add-resource` 根节点也会给创建者直接 `manage`;已有内容保持原样。+`add-resource` 的内部节点只继承,不重复写直接权限。++## 数据结构++### ACL entry++```json+{+ "principal": "user:bob",+ "level": "read"+}+```++| 字段 | 类型 | 说明 |+|------|------|------|+| `principal` | string | `user:{user_id}`、`group:{group_id}` 或 `user:*` |+| `level` | string | `read`、`write` 或 `manage` |++`group_id` 由调用者通过 [Admin API](./08-admin.md#用户组) 指定,是 account 内唯一且稳定的标识;用户组没有单独的展示名称。删除用户组后,旧 principal 不再匹配请求,除非重新创建同一个 `group_id`。++### ACL report++```json+{+ "uri": "viking://resources/project-a",+ "acl_enabled": true,+ "direct_entries": [+ {"principal": "user:bob", "level": "read"}+ ],+ "inherited_entries": [+ {"principal": "group:engineering", "level": "write"}+ ],+ "effective_entries": [+ {"principal": "group:engineering", "level": "write"},+ {"principal": "user:bob", "level": "read"}+ ]+}+```++| 字段 | 说明 |+|------|------|+| `direct_entries` | 只包含当前节点直接设置的条目 |+| `inherited_entries` | 所有祖先目录直接 ACL 的合并结果 |+| `effective_entries` | `direct_entries` 与 `inherited_entries` 的合并结果 |+| `acl_enabled` | 当前节点或任一祖先存在直接 ACL 时为 `true`;只读派生字段 |++account `ADMIN` 的隐式 `manage` 权限不出现在这些列表中。++## 获取 ACL++```+GET /api/v1/acl?uri={uri}+```++GET 可以在目标尚无 context 记录时返回结果:`direct_entries` 为空,继承权限从已有祖先 context 计算。修改 ACL 的接口要求目标已有 context 记录。++```bash+curl "http://localhost:1933/api/v1/acl?uri=viking%3A%2F%2Fresources%2Fproject-a" \+ -H "X-API-Key: your-key"+```++**Python SDK**++```python+report = client.acl_get("viking://resources/project-a")+```++**Go SDK**++```go+report, err := client.ACL(ctx, "viking://resources/project-a")+```++## 替换直接 ACL++```+PUT /api/v1/acl+```++请求体:++```json+{+ "uri": "viking://resources/project-a",+ "entries": [+ {"principal": "user:bob", "level": "read"},+ {"principal": "group:engineering", "level": "write"}+ ]+}+```++`entries` 会完整替换当前节点的直接 ACL,不影响祖先或后代节点自己的直接 ACL。重复 principal 会保留最高权限级别。传入空数组等价于删除当前节点的直接 ACL。++```bash+curl -X PUT http://localhost:1933/api/v1/acl \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "uri": "viking://resources/project-a",+ "entries": [+ {"principal": "user:bob", "level": "read"},+ {"principal": "group:engineering", "level": "write"}+ ]+ }'+```++**Python SDK**++```python+report = client.acl_set(+ "viking://resources/project-a",+ [+ {"principal": "user:bob", "level": "read"},+ {"principal": "group:engineering", "level": "write"},+ ],+)+```++异步客户端使用相同方法名:++```python+report = await client.acl_set(uri, entries)+```++**Go SDK**++```go+report, err := client.SetACL(ctx, "viking://resources/project-a", []openviking.ACLEntry{+ {Principal: "user:bob", Level: "read"},+ {Principal: "group:engineering", Level: "write"},+})+```++**CLI**++```bash+ov acl set viking://resources/project-a \+ --entry user:bob=read \+ --entry group:engineering=write+```++## 设置单个 principal 权限++```+POST /api/v1/acl/grant+```++```json+{+ "uri": "viking://resources/project-a",+ "principal": "user:bob",+ "level": "write"+}+```++该接口将 Bob 在当前节点上的直接 level 设置为 `write`。如果已有直接条目,则更新该条目;其他用户条目不变。++```bash+curl -X POST http://localhost:1933/api/v1/acl/grant \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "uri": "viking://resources/project-a",+ "principal": "user:bob",+ "level": "write"+ }'+```++```python+report = client.acl_grant(+ "viking://resources/project-a",+ principal="user:bob",+ level="write",+)+```++```bash+ov acl grant viking://resources/project-a --principal user:bob --level write+```++## 删除单个 principal 的直接授权++```+POST /api/v1/acl/revoke+```++```json+{+ "uri": "viking://resources/project-a",+ "principal": "user:bob"+}+```++`revoke` 只删除当前节点上 Bob 的直接条目。Bob 从祖先继承的权限仍然有效。++```python+report = client.acl_revoke("viking://resources/project-a", principal="user:bob")+```++```bash+ov acl revoke viking://resources/project-a --principal user:bob+```++## 清空当前节点的直接 ACL++```+DELETE /api/v1/acl?uri={uri}+```++该接口不删除后代节点的直接 ACL。清空后,当前节点从祖先 ACL 重新继承;每个后代继续由其祖先与自身的直接 ACL 计算有效权限。++```bash+curl -X DELETE \+ "http://localhost:1933/api/v1/acl?uri=viking%3A%2F%2Fresources%2Fproject-a" \+ -H "X-API-Key: your-key"+```++```python+report = client.acl_delete("viking://resources/project-a")+```++```bash+ov acl rm viking://resources/project-a+```++## 错误处理++接口先校验 manage,再向已授权调用者确认 URI 是否存在,避免通过错误类型探测资源。++| 场景 | 错误 |+|------|------|+| URI 不在 `viking://resources/...` | `INVALID_ARGUMENT` |+| 调用者没有 manage | `PERMISSION_DENIED` |+| 已授权调用者访问不存在的 URI | `NOT_FOUND` |+| 修改 ACL 时 URI 尚无 context 记录 | `INVALID_ARGUMENT`,需先完成索引 |+| `principal` 格式非法,或使用 `group:*` | `INVALID_ARGUMENT` |+| level 不是 `read/write/manage` | `INVALID_ARGUMENT` |+| 请求包含 `acl_enabled` 等未知字段 | `INVALID_ARGUMENT` |++ACL 的 direct 和 inherited 字段都保存在 context。更新会在同一子树批处理中修改目标 direct 并重算后代 inherited;写入失败时恢复原 context ACL 字段。++## 相关文档++- [资源访问控制(ACL)](../concepts/15-acl.md) - 权限、继承和检索语义+- [认证](../guides/04-authentication.md) - 请求身份与 account 角色+- [文件系统 API](./03-filesystem.md) - 受 ACL 控制的文件操作+- [检索 API](./06-retrieval.md) - `find/search` 接口diff --git a/docs/zh/api/12-content.md b/docs/zh/api/12-content.mdindex cb05fbc53..d834844e9 100644--- a/docs/zh/api/12-content.md+++ b/docs/zh/api/12-content.md@@ -577,7 +577,7 @@ ov set-tags viking://resources/project/ \**认证**-- HTTP 端点:在开启认证时要求 admin/root 角色。`api_key` 模式下,租户内容重建请使用 admin key;裸 root key 不能访问租户级数据。+- `api_key` 模式下,共享区 `viking://resources/...` 需要 admin key;普通 user key 只能重建自己的 `viking://user/<user_id>/...`,也可以使用等价的 `viking://~/...` 家目录别名。root key 不能访问租户级数据 API。- Python HTTP client / CLI:使用当前认证身份发起请求**参数**diff --git a/docs/zh/concepts/04-viking-uri.md b/docs/zh/concepts/04-viking-uri.mdindex d6fe8780d..2e1d0f031 100644--- a/docs/zh/concepts/04-viking-uri.md+++ b/docs/zh/concepts/04-viking-uri.md@@ -106,6 +106,8 @@ viking://~/resources/docs/ # 自己的私有资源目录viking://user/{user_id}/memories/ # 显式用户路径(可写自己的 id;访问他人需 admin/root)```+`viking://resources/...` 是当前 account 的共享区,可通过 [资源访问控制(ACL)](./15-acl.md) 细化目录或文件权限。`viking://user/{user}/resources/...` 是个人私有区;分享资源需要将其移动到共享区。+### 用户技能和 peer 内容```diff --git a/docs/zh/concepts/11-multi-tenant.md b/docs/zh/concepts/11-multi-tenant.mdindex d10a1bb10..78c77d4b6 100644--- a/docs/zh/concepts/11-multi-tenant.md+++ b/docs/zh/concepts/11-multi-tenant.md@@ -13,7 +13,7 @@ OpenViking 的多租户不是“为每个团队部署一套独立服务”,而- 用一个 OpenViking Server 服务多个团队、客户或应用- 用 `account` 隔离不同团队的数据-- 在同一个 `account` 内共享 `resources`+- 在同一个 `account` 内共享 `resources`,并用 ACL 对目录或文件细化授权- 用 `user` 隔离用户级记忆和会话- 用 ROOT / ADMIN / USER 角色分层管理权限- 支持 OpenClaw 插件、Vikingbot、CLI、HTTP SDK 等不同接入方式@@ -75,7 +75,7 @@ OpenViking Server 支持两种多租户相关认证模式:| 数据类型 | 是否跨 account 共享 | account 内是否共享 | 默认隔离边界 ||----------|---------------------|-------------------|--------------|-| 共享资源 (`viking://resources`) | 否 | 是 | account |+| 共享资源 (`viking://resources`) | 否 | 默认共享,可用 ACL 限制 | account / ACL || 用户资源 (`viking://user/{user_id}/resources`) | 否 | 否 | user || Peer 资源 (`viking://user/{user_id}/peers/{peer_id}/resources`) | 否 | 否 | user / peer || 记忆 | 否 | 否 | user / peer |@@ -109,8 +109,9 @@ viking://user/alice/peers/web-visitor-alice/resources/文件系统操作和语义检索都受租户约束:- 非 ROOT 请求会自动按 `account_id` 过滤-- `resources` 会允许检索 account 内共享资源-- `memory`、用户资源和 `skill` 会进一步按当前 `user space` 过滤+- `resources` 默认允许检索 account 内共享资源;设置 ACL 后按有效 ACL 过滤+- 用户资源始终按当前 `user space` 隔离;需要共享时移动到 `viking://resources`+- `memory` 和 `skill` 继续按当前 `user space` 过滤- Actor peer 会把 `viking://user/{user}/peers` 过滤到一个 peer,并作用于文件系统和检索操作这意味着“能搜到什么”与“能读到什么”保持一致,不会因为向量召回而越权。@@ -222,7 +223,7 @@ openclaw config set plugins.entries.openviking.config.peer_prefix "<peer-prefix>- 接入简单,插件不需要管理 account/user 生命周期- 最适合“一个 OpenClaw 实例对应一个 OpenViking 用户”的场景- `peer_prefix` 用于区分 OpenClaw 运行时身份,参与 peer/session 元数据-- 同一 account 内的 `resources` 可共享,memory 按 user scope 隔离+- 同一 account 内的 `resources` 默认共享,也可以通过 ACL 限制到指定用户;memory 按 user scope 隔离### OpenClaw 插件为何通常不配 `account` / `user`@@ -262,7 +263,7 @@ Vikingbot 当前的实践与 OpenClaw 插件不同,它更接近“平台代理这种模式的特点:- 适合一个 bot 服务承载多个聊天用户-- 同一 account 下所有用户共享 `resources`+- 同一 account 下的 `resources` 默认共享,ACL 可以对具体目录或文件细化权限- 用户记忆通过自动注册的 user 身份隔离- bot 侧需要承担更多租户生命周期管理逻辑@@ -317,6 +318,8 @@ peer 集合过滤选择当前用户内的 peer 内容子空间,例如- [配置](../guides/01-configuration.md) - `root_api_key` 和 `auth_mode`- [管理员(多租户)](../api/08-admin.md) - Admin API 参考- [API 概览](../api/01-overview.md) - CLI / HTTP 连接方式+- [资源访问控制(ACL)](./15-acl.md) - account 内资源授权、继承和检索过滤+- [ACL API](../api/12-acl.md) - HTTP、SDK 和 CLI 接口- [数据加密](./10-encryption.md) - 多租户下的静态数据加密- [多租户示例](https://github.com/volcengine/OpenViking/blob/main/examples/multi_tenant/README.md) - 完整管理流程示例- [OpenClaw 插件](https://github.com/volcengine/OpenViking/blob/main/examples/openclaw-plugin/README_CN.md) - OpenClaw 的接入方式diff --git a/docs/zh/concepts/15-acl.md b/docs/zh/concepts/15-acl.mdnew file mode 100644index 000000000..66c614ffd--- /dev/null+++ b/docs/zh/concepts/15-acl.md@@ -0,0 +1,160 @@+# 资源访问控制(ACL)++OpenViking ACL 用于在同一个 account 内,把共享资源目录或文件授权给用户或用户组。ACL 不改变 account 隔离:任何授权都只在当前 account 内生效。++ACL 采用协作文档式的继承模型。目录授权持续作用于所有后代,子目录和文件可以继续增加直接授权;祖先授权不会被子节点覆盖。++## 适用 URI++ACL 只作用于共享资源:++```text+viking://resources/...+```++- `viking://resources/...` 的 account `ADMIN` 隐式拥有 `manage`。+- `viking://resources` 是固定共享 scope,本身不能设置直接 ACL;ACL 从它下面的文件和目录开始。+- `viking://user/{user_id}/resources/...` 是个人私有区,不接受 ACL。需要分享时,将资源移动到有权写入的共享目录,并继承该目录的 ACL。++隐式管理权不会写入 ACL 条目,也不能被 ACL 删除。它保证共享资源始终有人能够首次设置或恢复权限。++## Principal 与权限级别++ACL 条目使用带类型的 principal:++- `user:{user_id}`:当前 account 内的用户。+- `group:{group_id}`:由调用者指定、在当前 account 内唯一的用户组 ID。+- `user:*`:当前 account 内任意用户。++不支持 `group:*`。用户组是平铺结构;修改成员关系不会重写资源 ACL 或 context 记录,而是在下一次请求构造 `RequestContext.group_ids` 时生效。+请求创建的异步解析和语义任务会携带同一份 group 身份。`add-resource` 写入目标通过鉴权后,自动语义维护会保留原调用者身份,并显式使用内部 ACL bypass,不会把调用者角色改成 `ADMIN`。++| Level | 允许的操作 |+|-------|------------|+| `read` | 读取、列目录、`find/search/grep` |+| `write` | `read` 的能力,以及写入、创建、删除或移动文件、修改 tags |+| `manage` | `write` 的能力,以及删除或移动目录、管理 ACL |++高等级包含低等级能力。授予 `manage`,等价于同时授予 `read` 和 `write`。++## 继承规则++节点的有效 ACL 是所有祖先直接 ACL 与节点自身直接 ACL 的并集:++```text+effective(node) = UNION(direct_acl(each ancestor), direct_acl(node))+```++例如:++```text+read user:bob on viking://resources/A+write group:engineering on viking://resources/A/B+read user:carol on viking://resources/A/B/C/report.md+```++`report.md` 的有效权限为:++- Bob:`read`+- `engineering` 的成员:`write`+- Carol:`read`++删除 `A/B` 上用户组的直接 ACL 不会删除 `A` 或 `report.md` 上的条目。子节点只会失去由该条目提供的权限。++## 默认行为与 `acl_enabled`++账号级 `resource_acl.auto_protect_new_content` 默认关闭。关闭时,如果父目录没有+ACL,新建文件或目录不会自动开启 ACL,继续使用原有 URI namespace 可见性和写入+规则;父目录已有 ACL 时,创建者获得直接 `manage`,并继承父目录权限。++开启后,新建共享文件或目录即使位于无 ACL 的父目录下,创建者也会在首条 context+记录上获得直接 `manage`;父目录权限仍作为继承 ACL 合并。已有内容不会迁移或+改权,重新关闭也只影响后续创建。`add-resource` 只把本次生成的根目录(`no_split`+时为根文件)作为创建节点:根节点获得创建者直接 `manage`,内部节点只继承,+不重复写直接授权。重新向量化或覆盖已有 context 不会改变直接 ACL。++只要节点或任一祖先存在直接 ACL,该节点就进入 ACL 控制域:++```text+acl_enabled = true+```++`acl_enabled` 是系统派生字段,不能由 API 调用者设置。删除最后一个相关直接 ACL 后,它会自动恢复为 `false`。++## 文件操作++所有文件接口使用同一套权限判断:++| 操作 | 所需能力 |+|------|----------|+| read、stat、list、tree、find、search、grep、glob、relations | read |+| write、create、mkdir、set tags | write |+| 删除或移动文件 | write |+| 删除或移动目录 | 目录及完整子树的 manage |+| 管理 ACL | manage |+| move 目标父目录 | write |++服务端会先 canonicalize URI,再在同一个鉴权入口中依次执行 account/owner/actor peer 等硬边界、有效 ACL 或 legacy fallback,以及写入和删除的 namespace 防护。++父目录已有 ACL,或账号开启 `auto_protect_new_content` 时,新建共享节点由创建者的+直接 `manage` 完成权限 bootstrap。其他情况下,首次设置 ACL 只能由共享区隐式+管理者完成;启用后,后续 ACL 修改要求有效 `manage` 能力。++目录上的 ACL 授权会被所有后代继承。`list`、`tree` 和批量结果仍逐个检查有效 ACL,因为未设置 ACL 的目录可能按原有 URI 规则可见,而某个后代已经通过自己的 ACL 进入控制域。++共享区内部移动时,节点自己的直接 ACL 随节点移动,继承权限按新祖先重新计算。个人资源移入共享区时不携带 ACL,只继承目标目录权限;共享资源移回个人区时清空 ACL。++递归修改 tags、删除或移动目录会先校验完整目标子树。任一节点缺少所需能力,或子树扫描不完整,操作都会整体中止。++目录 `stat` 的 `count` 使用相同的路径和 ACL 标量过滤,表示当前用户可见的 context 数量。++## 检索过滤++ACL 只保存在 context collection。每条 context 记录维护当前节点和继承权限两组原生标量字段:++```text+acl_enabled+acl_direct_grants+acl_inherited_grants+```++`acl_direct_grants` 是当前节点直接 ACL,`acl_inherited_grants` 是所有祖先直接 ACL 的并集。每个 principal 只保存最高 level,编码为 `{mask}:{principal}`:`1` 表示 `read`、`3` 表示 `write`、`7` 表示 `manage`。例如 `3:group:dev` 表示 `group:dev` 拥有 `write`,同时也具备 `read`。有效权限是两组列表的并集,不维护独立 ACL collection。++请求的可用 principal 为 `user:{ctx.user_id}`、`user:*`,以及 `ctx.group_ids` 中每个 ID 对应的 `group:{group_id}`。`find/search` 读取时为每个 principal 匹配 `1`、`3`、`7` 三种 token,并在 `viking://resources` scope 内对 direct 和 inherited 两个原生 `list<string>` 字段做过滤;个人资源始终按 URI owner 隔离。旧记录缺少 ACL 字段时按 `acl_enabled=false` 处理,无需全量回填。++检索 target URI 只是搜索范围,不要求调用者能够读取 target 节点本身。用户即使不能读取中间目录,也可以检索到深层单独授权给自己的文件。++共享区 context 写入会保留同 URI 已有 direct ACL。父目录已开启 ACL,或账号开启+`auto_protect_new_content` 时,新创建节点为创建者生成直接 `manage`,并从父节点+生成 inherited ACL;否则保持 `acl_enabled=false`。`add-resource` 的内部节点只继承+导入根节点。重新向量化和普通覆盖写不会把受控记录恢复为默认可见,也不能通过+普通 context 字段直接改 ACL。++## 示例++将目录授权给 Bob 只读:++```bash+ov acl grant viking://resources/project-a --principal user:bob --level read+```++Bob 可以读取和检索该目录的后代,但不能写入或删除。升级为 `write`:++```bash+ov acl grant viking://resources/project-a --principal user:bob --level write+```++删除 Bob 在当前节点上的直接授权:++```bash+ov acl revoke viking://resources/project-a --principal user:bob+```++如果 Bob 仍被祖先目录授权,该继承权限继续有效。++## 相关文档++- [ACL API](../api/12-acl.md) - HTTP、SDK 和 CLI 接口+- [多租户](./11-multi-tenant.md) - account、user 和角色边界+- [Viking URI](./04-viking-uri.md) - URI namespace+- [检索](./07-retrieval.md) - 分层检索流程diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.mdindex 071ea58e5..6a2a23ad4 100644--- a/docs/zh/guides/01-configuration.md+++ b/docs/zh/guides/01-configuration.md@@ -1515,6 +1515,56 @@ Redis Sentinel 分别配置数据节点和 Sentinel 的 ACL:```</details>+##### ACL schema++ACL 只维护在 context collection。除 `acl_enabled: bool` 外,需要以下 `list<string>` 标量索引字段:++```text+acl_direct_grants+acl_inherited_grants+```++每个元素使用 `{mask}:{principal}` 格式,其中 `1` 表示 `read`、`3` 表示 `write`、`7` 表示 `manage`。++本地 backend 会在启动时为存量 collection 增加字段并重建标量索引。旧记录不做全量回填;缺失 ACL 字段按 `acl_enabled=false` 和空列表读取。++火山向量库等远端 backend 的存量 collection 需要由部署方预先添加这些字段和 scalar index,OpenViking 只校验 schema。`volcengine` API key 数据面模式还要求 context collection 和配置的 index 已存在。权限模型详见 [资源访问控制(ACL)](../concepts/15-acl.md)。++<details>+<summary><b>openGauss</b></summary>++需要 openGauss 服务端支持原生 `vector` 类型,并使用允许远程连接的数据库用户。+可通过 `pip install "openviking[opengauss]"` 安装可选驱动。+官方容器中的初始 `omm` 用户可能限制远程登录,必要时请为 OpenViking 创建普通数据库用户。++```json+{+ "storage": {+ "vectordb": {+ "name": "context",+ "backend": "opengauss",+ "project": "default",+ "distance_metric": "cosine",+ "dimension": 1024,+ "opengauss": {+ "host": "127.0.0.1",+ "port": 5432,+ "user": "openviking",+ "password": "your-password",+ "db_name": "postgres",+ "schema": "public",+ "mode": "standalone"+ }+ }+ }+}+```++分布式 openGauss 部署可将 `mode` 设为 `"distributed"`;OpenViking 会尝试把元数据表标记为 reference table,并按 `id` 分布集合表。+</details>+++## 配置文件OpenViking 使用两个配置文件:diff --git a/docs/zh/guides/04-authentication.md b/docs/zh/guides/04-authentication.mdindex 13ce09833..1d866d593 100644--- a/docs/zh/guides/04-authentication.md+++ b/docs/zh/guides/04-authentication.md@@ -451,6 +451,160 @@ Role.register("operator", rank=1) # 权限介于 USER (0) 与 ADMIN (1) 之间### Trusted 模式+```bash+# 创建工作区 + 首个 admin+curl -X POST http://localhost:1933/api/v1/admin/accounts \+ -H "X-API-Key: your-secret-root-key" \+ -H "Content-Type: application/json" \+ -d '{"account_id": "acme", "admin_user_id": "alice"}'+# 返回: {"result": {"account_id": "acme", "admin_user_id": "alice", "user_key": "..."}}++# 注册普通用户(ROOT 或 ADMIN 均可)+curl -X POST http://localhost:1933/api/v1/admin/accounts/acme/users \+ -H "X-API-Key: your-secret-root-key" \+ -H "Content-Type: application/json" \+ -d '{"user_id": "bob", "role": "user"}'+# 返回: {"result": {"account_id": "acme", "user_id": "bob", "user_key": "..."}}+```++ACL 用户组是例外:组和成员通过 [Admin API](../api/08-admin.md#用户组) 维护,成员必须是当前 account 已注册的用户。客户端不能通过 header 或 token claim 声明组;服务端认证用户后查询组注册表,并把结果写入本次请求的 `RequestContext.group_ids`。++受信部署也可以通过受信网关调用 Admin API,目前支持两种方式:++- 携带受信部署自身的 `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 模式下执行一次)+curl -X POST http://localhost:1933/api/v1/admin/accounts \+ -H "X-API-Key: your-secret-root-key" \+ -H "Content-Type: application/json" \+ -d '{"account_id": "platform", "admin_user_id": "gateway-admin"}'++# 如果它需要跨 account 的管理权限,再提升为 root+curl -X PUT http://localhost:1933/api/v1/admin/accounts/platform/users/gateway-admin/role \+ -H "X-API-Key: your-secret-root-key" \+ -H "Content-Type: application/json" \+ -d '{"role": "root"}'++# 然后,在 trusted 模式下使用该身份调用 Admin API+curl -X POST http://localhost:1933/api/v1/admin/accounts \+ -H "X-API-Key: your-secret-root-key" \+ -H "X-OpenViking-Account: platform" \+ -H "X-OpenViking-User: gateway-admin" \+ -H "Content-Type: application/json" \+ -d '{+ "account_id": "acme",+ "admin_user_id": "alice"+ }'+```++## 客户端使用++OpenViking 支持两种方式传递 API Key:++**X-API-Key 请求头**++```bash+curl http://localhost:1933/api/v1/fs/ls?uri=viking:// \+ -H "X-API-Key: <user-key>"+```++**Authorization: Bearer 请求头**++```bash+curl http://localhost:1933/api/v1/fs/ls?uri=viking:// \+ -H "Authorization: Bearer <user-key>"+```++**Python SDK(HTTP)**++```python+import openviking as ov++client = ov.SyncHTTPClient(+ url="http://localhost:1933",+ api_key="<user-key>",+)+```++**CLI(通过 ovcli.conf)**++```json+{+ "url": "http://localhost:1933",+ "api_key": "<user-key>"+}+```++如果使用普通 `user key` 或 `admin key`,`account` 和 `user` 可以省略,因为服务端可以从 key 反查出来;如果使用 `trusted` 模式,则建议明确配置。++**CLI 覆盖参数**++```bash+openviking --account acme --user alice ls viking://+```++### 使用 --sudo 和 Root API Key++CLI 支持在 `ovcli.conf` 中同时配置 `api_key`(用于普通用户操作)和 `root_api_key`(用于管理员操作):++```json+{+ "url": "http://localhost:1933",+ "api_key": "<user-key>",+ "root_api_key": "<root-key>"+}+```++当需要执行管理员命令(`admin`、`system`、`reindex`)时,使用 `--sudo` 标志提升权限:++```bash+# 列出所有账户(需要 root 权限)+ov --sudo admin list-accounts++# 重新索引内容+ov --sudo reindex viking://++# 系统命令+ov --sudo system status+```++`--sudo` 标志:+- 仅适用于管理员命令:`admin`、`system`、`reindex`+- 用于非管理员命令时会报错+- `ovcli.conf` 中未配置 `root_api_key` 时会报错+- 请求时使用 `root_api_key` 替代 `api_key`++### 租户数据访问++租户级数据 API(如 `ls`、`find`、resources、sessions 等)在 `api_key`+模式下必须使用绑定了 account/user 的 key。这个 key 可以是 `USER` key,也可以是+`ADMIN` key;`ADMIN` key 会以它自己的 user 身份访问数据,不能通过+`X-OpenViking-Account` / `X-OpenViking-User` 切换身份。++ACL 检查还会使用服务端解析的 account 内用户组。成员变更从下一次请求生效,不需要签发新 API Key,也不会修改资源 ACL。++`ROOT` key 没有绑定租户 user,因此在 `api_key` 模式下不能访问租户级数据 API。+如果部署需要由上游网关断言 `account` / `user`,请使用 `trusted` 模式,而不是在+root key 请求上携带身份 header。++**ovcli.conf**++```json+{+ "url": "http://localhost:1933",+ "auth_mode": "trusted",+ "api_key": "your-trusted-server-key",+ "account": "acme",+ "user": "alice"+}+```++## Trusted 模式+Trusted 模式不会查询 user key,而是直接信任每个请求显式携带的身份请求头:```json@@ -578,6 +732,7 @@ ov doctor## 相关文档- [多租户](../concepts/11-multi-tenant.md) - 多租户能力、共享边界与接入实践+- [资源访问控制(ACL)](../concepts/15-acl.md) - account 内资源权限- [配置](01-configuration.md) - 配置文件说明- [服务部署](03-deployment.md) - 服务部署- [API 概览](../api/01-overview.md) - API 参考diff --git a/openviking/core/namespace.py b/openviking/core/namespace.pyindex 391ec7495..65fed4b18 100644--- a/openviking/core/namespace.py+++ b/openviking/core/namespace.py@@ -401,9 +401,11 @@ def content_owner_context_for_uri(uri: str, ctx: RequestContext) -> RequestContereturn RequestContext(user=UserIdentifier(ctx.account_id, owner_user_id),role=ctx.role,+ group_ids=ctx.group_ids,actor_peer_id=ctx.actor_peer_id,from_oauth=ctx.from_oauth,api_key=ctx.api_key,+ bypass_acl=ctx.bypass_acl,)diff --git a/openviking/parse/tree_builder.py b/openviking/parse/tree_builder.pyindex 7ada17124..b7e7f3abf 100644--- a/openviking/parse/tree_builder.py+++ b/openviking/parse/tree_builder.py@@ -114,24 +114,19 @@ class TreeBuilder:effective_parent_uri,kind="resource",)- try:- parent_exists = await viking_fs.exists(effective_parent_uri, ctx=ctx)- if not parent_exists:- if create_parent or parent_is_content_root:- logger.info(- f"[TreeBuilder] Parent URI does not exist, creating: {effective_parent_uri}"- )- await viking_fs.mkdir(effective_parent_uri, exist_ok=True, ctx=ctx)- else:- raise FileNotFoundError(- f"Parent URI does not exist: {effective_parent_uri}. "- f"Use --parent-auto-create/-p to automatically create it."- )- stat_result = await viking_fs.stat(effective_parent_uri, ctx=ctx)- except FileNotFoundError:- raise- except Exception as e:- raise FileNotFoundError(f"Parent URI does not exist: {effective_parent_uri}") from e+ parent_exists = await viking_fs.exists(effective_parent_uri, ctx=ctx)+ if not parent_exists:+ if create_parent or parent_is_content_root:+ logger.info(+ f"[TreeBuilder] Parent URI does not exist, creating: {effective_parent_uri}"+ )+ await viking_fs.mkdir(effective_parent_uri, exist_ok=True, ctx=ctx)+ else:+ raise FileNotFoundError(+ f"Parent URI does not exist: {effective_parent_uri}. "+ f"Use --parent-auto-create/-p to automatically create it."+ )+ stat_result = await viking_fs.stat(effective_parent_uri, ctx=ctx)if not stat_result.get("isDir"):raise ValueError(f"Parent URI is not a directory: {effective_parent_uri}")base_uri = effective_parent_uridiff --git a/openviking/resource/watch_scheduler.py b/openviking/resource/watch_scheduler.pyindex aea690a37..75b129494 100644--- a/openviking/resource/watch_scheduler.py+++ b/openviking/resource/watch_scheduler.py@@ -293,6 +293,7 @@ class WatchScheduler:ctx = RequestContext(user=user,role=role,+ bypass_acl=True,)if task.to_uri:diff --git a/openviking/retrieve/hierarchical_retriever.py b/openviking/retrieve/hierarchical_retriever.pyindex e175d276d..890527085 100644--- a/openviking/retrieve/hierarchical_retriever.py+++ b/openviking/retrieve/hierarchical_retriever.py@@ -231,6 +231,31 @@ class HierarchicalRetriever:telemetry.count("vector.scored", len(global_results))telemetry.count("vector.scanned", len(global_results))+ leaf_results: List[Dict[str, Any]] = []+ if self.vector_store.acl_manager is not None and (level is None or 2 in level):+ leaf_results = await vector_proxy.search_in_tenant(+ query_vector=query_vector,+ sparse_query_vector=sparse_query_vector,+ context_type=context_type,+ target_directories=target_dirs,+ extra_filter=scope_dsl,+ level=[2],+ limit=max(limit, self.GLOBAL_SEARCH_TOPK),+ )+ telemetry.count("vector.searches", 1)+ telemetry.count("vector.scored", len(leaf_results))+ telemetry.count("vector.scanned", len(leaf_results))+ if self._rerank_client and mode == RetrieverMode.THINKING and leaf_results:+ leaf_scores = await self._rerank_scores(+ query.query,+ [str(result.get("abstract", "")) for result in leaf_results],+ [self._finite_score(result.get("_score", 0.0)) for result in leaf_results],+ )+ leaf_results = [+ {**result, "_score": score}+ for result, score in zip(leaf_results, leaf_scores, strict=True)+ ]+# Debug: Print all URIs in global_resultsif logger.isEnabledFor(logging.DEBUG):logger.debug(f"[retrieve] target_dirs: {target_dirs}")@@ -272,7 +297,7 @@ class HierarchicalRetriever:seen_starting_uris.add(uri)# Add directory hits to the result pool only when explicitly requested.- initial_candidates = []+ initial_candidates = list(leaf_results)if level is not None:for result, score in zip(global_results, directory_scores, strict=True):if result.get("level", 2) not in level:diff --git a/openviking/server/account_settings.py b/openviking/server/account_settings.pyindex a85803780..e6b79fc03 100644--- a/openviking/server/account_settings.py+++ b/openviking/server/account_settings.py@@ -31,6 +31,14 @@ class AccountAgentEvolutionSettings(BaseModel):model_config = {"extra": "forbid"}+class AccountResourceAclSettings(BaseModel):+ """Account-scoped defaults for newly created shared content."""++ auto_protect_new_content: bool = False++ model_config = {"extra": "forbid"}++class AccountSettings(BaseModel):"""Persisted account overrides.@@ -38,6 +46,7 @@ class AccountSettings(BaseModel):"""agent_evolution: Optional[AccountAgentEvolutionSettings] = None+ resource_acl: Optional[AccountResourceAclSettings] = Nonemodel_config = {"extra": "forbid"}@@ -46,6 +55,7 @@ class AccountSettingsPatch(BaseModel):"""Allowlisted account settings accepted by the update API."""agent_evolution: Optional[AccountAgentEvolutionSettings] = None+ resource_acl: Optional[AccountResourceAclSettings] = Nonemodel_config = {"extra": "forbid"}@@ -116,6 +126,12 @@ def effective_agent_evolution_enabled(return settings.agent_evolution.enabled+def effective_auto_protect_new_content(settings: AccountSettings) -> bool:+ if settings.resource_acl is None:+ return False+ return settings.resource_acl.auto_protect_new_content++async def update_account_settings(viking_fs: VikingFS,account_id: str,@@ -147,6 +163,8 @@ async def update_account_settings(updated = current.model_copy(deep=True)if patch.agent_evolution is not None:updated.agent_evolution = patch.agent_evolution.model_copy(deep=True)+ if patch.resource_acl is not None:+ updated.resource_acl = patch.resource_acl.model_copy(deep=True)if updated == current:return currentdiff --git a/openviking/server/api_keys/legacy.py b/openviking/server/api_keys/legacy.pyindex 0879ba8f2..2a8345f0f 100644--- a/openviking/server/api_keys/legacy.py+++ b/openviking/server/api_keys/legacy.py@@ -3,6 +3,7 @@"""Legacy API Key management (original implementation)."""import asyncio+import copyimport fnmatchimport hashlibimport hmac@@ -31,13 +32,18 @@ from openviking_cli.exceptions import (NotFoundError,UnauthenticatedError,)-from openviking_cli.session.user_id import validate_account_id, validate_user_id+from openviking_cli.session.user_id import (+ validate_account_id,+ validate_identifier_part,+ validate_user_id,+)from openviking_cli.utils import get_loggerlogger = get_logger(__name__)ACCOUNTS_PATH = "/local/_system/accounts.json"USERS_PATH_TEMPLATE = "/local/{account_id}/_system/users.json"+GROUPS_PATH_TEMPLATE = "/local/{account_id}/_system/groups.json"# Argon2id parameters - export with LEGACY_ prefix for reuse in new.py@@ -97,6 +103,7 @@ class LegacyAPIKeyManager:self._accounts: Dict[str, AccountInfo] = {}# Prefix index: key_prefix -> list[UserKeyEntry]self._prefix_index: Dict[str, list[UserKeyEntry]] = {}+ self._user_group_ids: Dict[tuple[str, str], tuple[str, ...]] = {}# Serializes reload() so overlapping refreshes can't interleave.self._reload_lock = asyncio.Lock()self._user_deletion_lock = asyncio.Lock()@@ -104,6 +111,7 @@ class LegacyAPIKeyManager:def _discard_account_state(self, account_id: str) -> None:"""Remove an account and its key index entries from in-memory state."""account = self._accounts.pop(account_id, None)+ self._discard_account_group_index(account_id)if account is None:return@@ -144,9 +152,12 @@ class LegacyAPIKeyManager:accounts_data = {"accounts": {"default": {"created_at": now}}}await self._write_json(ACCOUNTS_PATH, accounts_data)- accounts, prefix_index = await self._build_state(accounts_data, allow_migration=True)+ accounts, prefix_index, user_group_ids = await self._build_state(+ accounts_data, allow_migration=True+ )self._accounts = accountsself._prefix_index = prefix_index+ self._user_group_ids = user_group_idslogger.info("LegacyAPIKeyManager loaded: %d accounts, %d user keys",@@ -162,10 +173,13 @@ class LegacyAPIKeyManager:# Store not initialized yet (reader started before writer): keep state.return- accounts, prefix_index = await self._build_state(accounts_data, allow_migration=False)+ accounts, prefix_index, user_group_ids = await self._build_state(+ accounts_data, allow_migration=False+ )# Atomic swap: rebind so readers never observe a half-built index.self._accounts = accountsself._prefix_index = prefix_index+ self._user_group_ids = user_group_idslogger.debug("LegacyAPIKeyManager reloaded: %d accounts, %d user keys",@@ -175,20 +189,33 @@ class LegacyAPIKeyManager:async def _build_state(self, accounts_data: dict, *, allow_migration: bool- ) -> tuple[Dict[str, AccountInfo], Dict[str, list[UserKeyEntry]]]:+ ) -> tuple[+ Dict[str, AccountInfo],+ Dict[str, list[UserKeyEntry]],+ Dict[tuple[str, str], tuple[str, ...]],+ ]:"""Build fresh (accounts, prefix_index) state; migrate plaintext only if allow_migration."""accounts: Dict[str, AccountInfo] = {}prefix_index: Dict[str, list[UserKeyEntry]] = {}+ user_group_ids: Dict[tuple[str, str], tuple[str, ...]] = {}for account_id, info in accounts_data.get("accounts", {}).items():users_path = USERS_PATH_TEMPLATE.format(account_id=account_id)users_data = await self._read_json(users_path)users = users_data.get("users", {}) if users_data else {}+ groups_path = GROUPS_PATH_TEMPLATE.format(account_id=account_id)+ groups_data = await self._read_json(groups_path)+ groups = groups_data.get("groups", {}) if groups_data else {}accounts[account_id] = AccountInfo(created_at=info.get("created_at", ""),users=users,+ groups=groups,)+ user_group_ids.update({+ (account_id, user_id): group_ids+ for user_id, group_ids in self._group_memberships(users, groups).items()+ })for user_id, user_info in users.items():key_or_hash = user_info.get("key", "")@@ -229,7 +256,7 @@ class LegacyAPIKeyManager:prefix_index[key_prefix] = []prefix_index[key_prefix].append(entry)- return accounts, prefix_index+ return accounts, prefix_index, user_group_idsasync def compute_store_signature(self) -> tuple:"""Return a cheap (path, size, modTime) signature over accounts.json + all users.json."""@@ -242,6 +269,8 @@ class LegacyAPIKeyManager:for account_id in accounts_data.get("accounts", {}):users_path = USERS_PATH_TEMPLATE.format(account_id=account_id)signature.append(await self._stat_signature(users_path))+ groups_path = GROUPS_PATH_TEMPLATE.format(account_id=account_id)+ signature.append(await self._stat_signature(groups_path))return tuple(signature)@@ -343,6 +372,7 @@ class LegacyAPIKeyManager:self._accounts[account_id] = AccountInfo(created_at=now,users={admin_user_id: user_info},+ groups={},)entry = UserKeyEntry(@@ -362,6 +392,7 @@ class LegacyAPIKeyManager:try:await self._save_accounts_json()await self._save_users_json(account_id)+ await self._write_groups_json(account_id, {})except Exception:await self._rollback_create_account(account_id)raise@@ -532,12 +563,25 @@ class LegacyAPIKeyManager:if not isinstance(deletion, dict) or deletion.get("task_id") != task_id:return False+ old_groups = copy.deepcopy(account.groups)+ groups = copy.deepcopy(account.groups)+ for group in groups.values():+ members = group.get("members", [])+ if user_id in members:+ group["members"] = [member for member in members if member != user_id]account.users.pop(user_id)try:await self._save_users_json(account_id)+ if groups != old_groups:+ await self._write_groups_json(account_id, groups)except Exception:account.users[user_id] = user_info+ account.groups = old_groups+ self._rebuild_account_group_index(account_id)raise+ if groups != old_groups:+ account.groups = groups+ self._rebuild_account_group_index(account_id)return Truedef get_user_deletion(self, account_id: str, user_id: str) -> Optional[dict]:@@ -765,6 +809,71 @@ class LegacyAPIKeyManager:return Role.USERreturn Role(user.get("role", "user"))+ def get_user_group_ids(self, account_id: str, user_id: str) -> tuple[str, ...]:+ """Return the account-scoped groups currently containing the user."""+ return self._user_group_ids.get((account_id, user_id), ())++ async def create_group(self, account_id: str, group_id: str) -> dict:+ error = validate_identifier_part(group_id, "group_id")+ if error:+ raise InvalidArgumentError(error)+ async with self._reload_lock:+ account = self._require_account(account_id)+ if group_id in account.groups:+ raise AlreadyExistsError(group_id, "group")+ groups = copy.deepcopy(account.groups)+ groups[group_id] = {"members": []}+ await self._replace_groups(account_id, account, groups)+ return self._group_result(group_id, groups[group_id])++ def get_groups(self, account_id: str) -> list[dict]:+ account = self._require_account(account_id)+ return [+ self._group_result(group_id, group)+ for group_id, group in sorted(account.groups.items())+ ]++ def get_group_members(self, account_id: str, group_id: str) -> list[str]:+ group = self._require_group(account_id, group_id)+ return sorted(set(group.get("members", [])))++ async def add_group_member(self, account_id: str, group_id: str, user_id: str) -> bool:+ async with self._reload_lock:+ account = self._require_account(account_id)+ if user_id not in account.users:+ raise NotFoundError(user_id, "user")+ group = self._require_group(account_id, group_id)+ if user_id in group.get("members", []):+ return True+ groups = copy.deepcopy(account.groups)+ groups[group_id].setdefault("members", []).append(user_id)+ groups[group_id]["members"].sort()+ await self._replace_groups(account_id, account, groups)+ return True++ async def remove_group_member(self, account_id: str, group_id: str, user_id: str) -> bool:+ async with self._reload_lock:+ account = self._require_account(account_id)+ group = self._require_group(account_id, group_id)+ if user_id not in group.get("members", []):+ return False+ groups = copy.deepcopy(account.groups)+ groups[group_id]["members"] = [+ member for member in groups[group_id].get("members", []) if member != user_id+ ]+ await self._replace_groups(account_id, account, groups)+ return True++ async def delete_group(self, account_id: str, group_id: str) -> None:+ async with self._reload_lock:+ account = self._require_account(account_id)+ group = self._require_group(account_id, group_id)+ if group.get("members"):+ raise FailedPreconditionError("Group must be empty before deletion")+ groups = copy.deepcopy(account.groups)+ del groups[group_id]+ await self._replace_groups(account_id, account, groups)+def get_user_key_fingerprint(self, account_id: str, user_id: str) -> Optional[str]:"""Return SHA-256 hex digest of the user's stored API key value, or None.@@ -796,6 +905,63 @@ class LegacyAPIKeyManager:# ---- internal helpers ----+ def _require_account(self, account_id: str) -> AccountInfo:+ account = self._accounts.get(account_id)+ if account is None:+ raise NotFoundError(account_id, "account")+ return account++ def _require_group(self, account_id: str, group_id: str) -> dict:+ account = self._require_account(account_id)+ group = account.groups.get(group_id)+ if group is None:+ raise NotFoundError(group_id, "group")+ return group++ @staticmethod+ def _group_result(group_id: str, group: dict) -> dict:+ return {+ "group_id": group_id,+ "member_count": len(set(group.get("members", []))),+ }++ def _discard_account_group_index(self, account_id: str) -> None:+ for key in [key for key in self._user_group_ids if key[0] == account_id]:+ del self._user_group_ids[key]++ def _rebuild_account_group_index(self, account_id: str) -> None:+ self._discard_account_group_index(account_id)+ account = self._accounts.get(account_id)+ if account is None:+ return+ self._user_group_ids.update({+ (account_id, user_id): group_ids+ for user_id, group_ids in self._group_memberships(+ account.users, account.groups+ ).items()+ })++ @staticmethod+ def _group_memberships(+ users: Dict[str, dict], groups: Dict[str, dict]+ ) -> Dict[str, tuple[str, ...]]:+ group_ids_by_user: Dict[str, list[str]] = {}+ for group_id, group in groups.items():+ for user_id in group.get("members", []):+ if user_id in users:+ group_ids_by_user.setdefault(user_id, []).append(group_id)+ return {+ user_id: tuple(sorted(set(group_ids)))+ for user_id, group_ids in group_ids_by_user.items()+ }++ async def _replace_groups(+ self, account_id: str, account: AccountInfo, groups: Dict[str, dict]+ ) -> None:+ await self._write_groups_json(account_id, groups)+ account.groups = groups+ self._rebuild_account_group_index(account_id)+def _remove_key_index_entry(self, account_id: str, user_id: str, user_info: dict) -> None:key_or_hash = user_info.get("key", "")if not key_or_hash:@@ -933,3 +1099,7 @@ class LegacyAPIKeyManager:await self._write_json(path, {"users": account.users}, lease_ref=lease)finally:await self._async_agfs.pathlock_release(lease)++ async def _write_groups_json(self, account_id: str, groups: dict) -> None:+ path = GROUPS_PATH_TEMPLATE.format(account_id=account_id)+ await self._write_json(path, {"groups": groups})diff --git a/openviking/server/api_keys/models.py b/openviking/server/api_keys/models.pyindex 76c4ac7e0..d8ccfed62 100644--- a/openviking/server/api_keys/models.py+++ b/openviking/server/api_keys/models.py@@ -38,3 +38,4 @@ class AccountInfo:created_at: strusers: Dict[str, dict] = field(default_factory=dict)+ groups: Dict[str, dict] = field(default_factory=dict)diff --git a/openviking/server/api_keys/new.py b/openviking/server/api_keys/new.pyindex 1f628b081..987738d2c 100644--- a/openviking/server/api_keys/new.py+++ b/openviking/server/api_keys/new.py@@ -233,6 +233,7 @@ class NewAPIKeyManager:self._legacy._accounts[account_id] = AccountInfo(created_at=now,users={admin_user_id: user_info},+ groups={},)entry = UserKeyEntry(@@ -251,6 +252,7 @@ class NewAPIKeyManager:try:await self._legacy._save_accounts_json()await self._legacy._save_users_json(account_id)+ await self._legacy._write_groups_json(account_id, {})except Exception:await self._legacy._rollback_create_account(account_id)raise@@ -490,6 +492,29 @@ class NewAPIKeyManager:"""return self._legacy.get_user_role(account_id, user_id)+ def get_user_group_ids(self, account_id: str, user_id: str) -> tuple[str, ...]:+ return self._legacy.get_user_group_ids(account_id, user_id)++ async def create_group(self, account_id: str, group_id: str) -> dict:+ return await self._legacy.create_group(account_id, group_id)++ def get_groups(self, account_id: str) -> list[dict]:+ return self._legacy.get_groups(account_id)++ def get_group_members(self, account_id: str, group_id: str) -> list[str]:+ return self._legacy.get_group_members(account_id, group_id)++ async def add_group_member(self, account_id: str, group_id: str, user_id: str) -> bool:+ return await self._legacy.add_group_member(account_id, group_id, user_id)++ async def remove_group_member(+ self, account_id: str, group_id: str, user_id: str+ ) -> bool:+ return await self._legacy.remove_group_member(account_id, group_id, user_id)++ async def delete_group(self, account_id: str, group_id: str) -> None:+ await self._legacy.delete_group(account_id, group_id)+def get_user_key_fingerprint(self, account_id: str, user_id: str) -> Optional[str]:"""SHA-256 hex digest of the user's stored API key value, or None.diff --git a/openviking/server/app.py b/openviking/server/app.pyindex 33355abcb..2c66db920 100644--- a/openviking/server/app.py+++ b/openviking/server/app.py@@ -31,6 +31,7 @@ from openviking.server.models import ERROR_CODE_TO_HTTP_STATUS, ErrorInfo, Respofrom openviking.server.profile_middleware import create_profile_http_middlewarefrom openviking.server.request_id import REQUEST_ID_HEADER, RequestIdMiddlewarefrom openviking.server.routers import (+ acl_router,admin_router,agent_evolution_router,bot_router,@@ -607,6 +608,7 @@ def create_app(# Register routersapp.include_router(system_router)+ app.include_router(acl_router)app.include_router(admin_router)app.include_router(agent_evolution_router)app.include_router(resources_router)diff --git a/openviking/server/auth/__init__.py b/openviking/server/auth/__init__.pyindex 9d0e74518..054c1d7d2 100644--- a/openviking/server/auth/__init__.py+++ b/openviking/server/auth/__init__.py@@ -98,6 +98,15 @@ def _get_plugin(request: Request):return plugin+def resolve_group_ids(request: Request, account_id: str, user_id: str) -> tuple[str, ...]:+ """Resolve server-managed account groups for a request identity."""+ manager = getattr(request.app.state, "api_key_manager", None)+ if manager is None:+ return ()+ resolver = getattr(manager, "get_user_group_ids", None)+ return tuple(resolver(account_id, user_id)) if resolver is not None else ()++def _build_request_context(request: Request,identity: ResolvedIdentity,@@ -107,12 +116,12 @@ def _build_request_context() -> RequestContext:plugin = _get_plugin(request)plugin.get_request_context_checks(request.url.path, identity)+ account_id = identity.account_id or "default"+ user_id = identity.user_id or "default"ctx = RequestContext(- user=UserIdentifier(- identity.account_id or "default",- identity.user_id or "default",- ),+ user=UserIdentifier(account_id, user_id),role=identity.role,+ group_ids=resolve_group_ids(request, account_id, user_id),actor_peer_id=actor_peer_id,from_oauth=identity.from_oauth,api_key=api_key,@@ -217,6 +226,7 @@ async def get_upload_request_context(ctx = RequestContext(user=UserIdentifier(consumed.account_id, consumed.user_id),role=Role.USER,+ group_ids=resolve_group_ids(request, consumed.account_id, consumed.user_id),# Actor peer comes from the token (bound at mint time from the trusted MCP# context), never from this upload request's headers, so server-side# auto-ingest keeps the caller's peer scope for reason-memory routing.diff --git a/openviking/server/identity.py b/openviking/server/identity.pyindex 6377d6fbb..5b42515de 100644--- a/openviking/server/identity.py+++ b/openviking/server/identity.py@@ -94,6 +94,9 @@ class RequestContext:user: UserIdentifierrole: Role+ # Account-scoped groups resolved by the server for this request. Callers do+ # not supply these values through headers or ACL payloads.+ group_ids: tuple[str, ...] = ()# 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@@ -105,6 +108,9 @@ class RequestContext:# Raw API key from the request — used by Connector to call back into OV# on behalf of the original userapi_key: Optional[str] = field(default=None, repr=False)+ # Trusted background workers may maintain derived content without replaying+ # the triggering user's resource ACL. Tenant and namespace checks still apply.+ bypass_acl: bool = False@propertydef account_id(self) -> str:diff --git a/openviking/server/routers/__init__.py b/openviking/server/routers/__init__.pyindex dd280a3f3..e6e80d296 100644--- a/openviking/server/routers/__init__.py+++ b/openviking/server/routers/__init__.py@@ -2,6 +2,7 @@# SPDX-License-Identifier: AGPL-3.0"""OpenViking HTTP Server routers."""+from openviking.server.routers.acl import router as acl_routerfrom openviking.server.routers.admin import router as admin_routerfrom openviking.server.routers.agent_evolution import router as agent_evolution_routerfrom openviking.server.routers.bot import router as bot_router@@ -27,6 +28,7 @@ from openviking.server.routers.watches import router as watches_routerfrom openviking.server.routers.webdav import router as webdav_router__all__ = [+ "acl_router","admin_router","agent_evolution_router","bot_router",diff --git a/openviking/server/routers/acl.py b/openviking/server/routers/acl.pynew file mode 100644index 000000000..e2001d780--- /dev/null+++ b/openviking/server/routers/acl.py@@ -0,0 +1,98 @@+"""ACL endpoints."""++from fastapi import APIRouter, Body, Depends, Query+from pydantic import BaseModel, ConfigDict++from openviking.core.path_variables import resolve_path_variables+from openviking.core.uri_validation import validate_request_viking_uri+from openviking.server.auth import get_request_context+from openviking.server.dependencies import get_service+from openviking.server.identity import RequestContext+from openviking.server.models import Response+from openviking.storage.acl import AclLevel++router = APIRouter(prefix="/api/v1/acl", tags=["acl"])+++class _AclRequest(BaseModel):+ model_config = ConfigDict(extra="forbid")+++class AclEntryRequest(_AclRequest):+ principal: str+ level: AclLevel+++class SetAclRequest(_AclRequest):+ uri: str+ entries: list[AclEntryRequest]+++class GrantAclRequest(_AclRequest):+ uri: str+ principal: str+ level: AclLevel+++class RevokeAclRequest(_AclRequest):+ uri: str+ principal: str+++async def get_acl(+ uri: str = Query(..., description="Viking URI"),+ _ctx: RequestContext = Depends(get_request_context),+):+ uri = validate_request_viking_uri(resolve_path_variables(uri), _ctx)+ result = await get_service().fs.get_acl(uri, ctx=_ctx)+ return Response(status="ok", result=result)+++async def set_acl(+ request: SetAclRequest = Body(...),+ _ctx: RequestContext = Depends(get_request_context),+):+ uri = validate_request_viking_uri(resolve_path_variables(request.uri), _ctx)+ result = await get_service().fs.set_acl(+ uri,+ [entry.model_dump() for entry in request.entries],+ ctx=_ctx,+ )+ return Response(status="ok", result=result)+++async def delete_acl(+ uri: str = Query(..., description="Viking URI"),+ _ctx: RequestContext = Depends(get_request_context),+):+ uri = validate_request_viking_uri(resolve_path_variables(uri), _ctx)+ result = await get_service().fs.delete_acl(uri, ctx=_ctx)+ return Response(status="ok", result=result)++[email protected]("/grant")+async def grant_acl(+ request: GrantAclRequest = Body(...),+ _ctx: RequestContext = Depends(get_request_context),+):+ uri = validate_request_viking_uri(resolve_path_variables(request.uri), _ctx)+ result = await get_service().fs.grant_acl(+ uri,+ request.principal,+ request.level,+ ctx=_ctx,+ )+ return Response(status="ok", result=result)++[email protected]("/revoke")+async def revoke_acl(+ request: RevokeAclRequest = Body(...),+ _ctx: RequestContext = Depends(get_request_context),+):+ uri = validate_request_viking_uri(resolve_path_variables(request.uri), _ctx)+ result = await get_service().fs.revoke_acl(uri, request.principal, ctx=_ctx)+ return Response(status="ok", result=result)diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.pyindex ae50b852a..09b8371bb 100644--- a/openviking/server/routers/admin.py+++ b/openviking/server/routers/admin.py@@ -12,6 +12,7 @@ from openviking.server.account_settings import (AccountAgentEvolutionSettings,AccountSettings,AccountSettingsPatch,+ effective_auto_protect_new_content,read_account_settings,update_account_settings,)@@ -81,6 +82,12 @@ class RegenerateKeyRequest(BaseModel):seed: str | None = None+class CreateGroupRequest(BaseModel):+ model_config = {"extra": "forbid"}++ group_id: str++class MigrateLegacyDataRequest(BaseModel):action: str = "migrate"@@ -179,7 +186,10 @@ async def _account_settings_result("settings": {"agent_evolution": {"enabled": enabled,- }+ },+ "resource_acl": {+ "auto_protect_new_content": effective_auto_protect_new_content(settings),+ },},"overrides": settings.model_dump(exclude_none=True),}@@ -195,7 +205,7 @@ def _has_initial_user_config(user_config: UserConfig | None) -> bool:return bool(_has_add_targets(user_config) or (user_config and user_config.memory_policy))-def _validate_initial_user_config(+async def _validate_initial_user_config(service,user_ctx: RequestContext,user_config: UserConfig | None,@@ -205,7 +215,7 @@ def _validate_initial_user_config(if service.viking_fs is None:raise FailedPreconditionError("OpenViking service is not initialized.")if _has_add_targets(user_config):- validate_add_targets(+ await validate_add_targets(user_config.add_targets,ctx=user_ctx,viking_fs=service.viking_fs,@@ -292,7 +302,7 @@ async def create_account(user=UserIdentifier(body.account_id, body.admin_user_id),role=Role.ADMIN,)- _validate_initial_user_config(service, account_ctx, body.user_config)+ await _validate_initial_user_config(service, account_ctx, body.user_config)manager = _get_api_key_manager(request)user_key = await manager.create_account(body.account_id,@@ -399,7 +409,7 @@ async def delete_account(try:storage = viking_fs._get_vector_store()if storage:- deleted = await storage.delete_account_data(account_id)+ deleted = await storage.delete_account_data(account_id, ctx=ctx)logger.info(f"VectorDB cascade delete for account {account_id}: {deleted} records")except Exception as e:logger.warning(f"VectorDB cleanup for account {account_id}: {e}")@@ -469,7 +479,7 @@ async def register_user(user=UserIdentifier(account_id, body.user_id),role=resolved_role,)- _validate_initial_user_config(service, user_ctx, body.user_config)+ await _validate_initial_user_config(service, user_ctx, body.user_config)manager = _get_api_key_manager(request)user_key = await manager.register_user(account_id,@@ -638,3 +648,89 @@ async def regenerate_key(seed=body.seed if body is not None else None,)return Response(status="ok", result={"user_key": new_key})+++# ---- Group endpoints ----++[email protected]("/accounts/{account_id}/groups")+@require_auth_root_or_admin+async def create_group(+ body: CreateGroupRequest,+ request: Request,+ account_id: str = Path(..., description="Account ID"),+ ctx: RequestContext = Depends(get_request_context),+):+ _check_account_access(ctx, account_id)+ result = await _get_api_key_manager(request).create_group(account_id, body.group_id)+ return Response(status="ok", result=result)++[email protected]("/accounts/{account_id}/groups")+@require_auth_root_or_admin+async def list_groups(+ request: Request,+ account_id: str = Path(..., description="Account ID"),+ ctx: RequestContext = Depends(get_request_context),+):+ _check_account_access(ctx, account_id)+ result = _get_api_key_manager(request).get_groups(account_id)+ return Response(status="ok", result=result)++[email protected]("/accounts/{account_id}/groups/{group_id}")+@require_auth_root_or_admin+async def delete_group(+ request: Request,+ account_id: str = Path(..., description="Account ID"),+ group_id: str = Path(..., description="Group ID"),+ ctx: RequestContext = Depends(get_request_context),+):+ _check_account_access(ctx, account_id)+ await _get_api_key_manager(request).delete_group(account_id, group_id)+ return Response(status="ok", result={"deleted": True})++[email protected]("/accounts/{account_id}/groups/{group_id}/members")+@require_auth_root_or_admin+async def list_group_members(+ request: Request,+ account_id: str = Path(..., description="Account ID"),+ group_id: str = Path(..., description="Group ID"),+ ctx: RequestContext = Depends(get_request_context),+):+ _check_account_access(ctx, account_id)+ members = _get_api_key_manager(request).get_group_members(account_id, group_id)+ return Response(status="ok", result={"group_id": group_id, "members": members})++[email protected]("/accounts/{account_id}/groups/{group_id}/members/{user_id}")+@require_auth_root_or_admin+async def add_group_member(+ request: Request,+ account_id: str = Path(..., description="Account ID"),+ group_id: str = Path(..., description="Group ID"),+ user_id: str = Path(..., description="User ID"),+ ctx: RequestContext = Depends(get_request_context),+):+ _check_account_access(ctx, account_id)+ added = await _get_api_key_manager(request).add_group_member(+ account_id, group_id, user_id+ )+ return Response(status="ok", result={"added": added})++[email protected]("/accounts/{account_id}/groups/{group_id}/members/{user_id}")+@require_auth_root_or_admin+async def remove_group_member(+ request: Request,+ account_id: str = Path(..., description="Account ID"),+ group_id: str = Path(..., description="Group ID"),+ user_id: str = Path(..., description="User ID"),+ ctx: RequestContext = Depends(get_request_context),+):+ _check_account_access(ctx, account_id)+ removed = await _get_api_key_manager(request).remove_group_member(+ account_id, group_id, user_id+ )+ return Response(status="ok", result={"removed": removed})diff --git a/openviking/server/routers/skills.py b/openviking/server/routers/skills.pyindex 81fad7d26..1daff2283 100644--- a/openviking/server/routers/skills.py+++ b/openviking/server/routers/skills.py@@ -444,7 +444,7 @@ async def _skill_snapshot_lock() -> AsyncIterator[None]:"""Hold the storage tree lock while one content-addressed Skill view is read."""viking_fs = service.fs._ensure_initialized() # noqa: SLF001- viking_fs._ensure_access(root_uri, ctx) # noqa: SLF001+ await viking_fs._ensure_access(root_uri, ctx) # noqa: SLF001path = viking_fs._uri_to_path(root_uri, ctx=ctx) # noqa: SLF001fs_ctx = {"account_id": ctx.account_id}lease = await viking_fs._async_agfs.pathlock_acquire_tree( # noqa: SLF001diff --git a/openviking/server/user_config.py b/openviking/server/user_config.pyindex 9eed21dbd..8f9244765 100644--- a/openviking/server/user_config.py+++ b/openviking/server/user_config.py@@ -12,6 +12,7 @@ from typing import TYPE_CHECKING, Any, AsyncIterator, Callable, Optional, TypeVafrom openviking.core.namespace import canonical_user_rootfrom openviking.core.uri_validation import validate_content_target_urifrom openviking.server.config import AddTargetsConfig, UserConfig+from openviking.storage.acl import AclActionfrom openviking_cli.exceptions import InvalidArgumentError, NotFoundErrorif TYPE_CHECKING:@@ -67,12 +68,6 @@ def _user_config_from_payload(payload: Any) -> UserConfig:raise InvalidArgumentError(str(exc)) from exc-def _ensure_mutable(viking_fs: VikingFS, uri: str, ctx: RequestContext) -> None:- ensure = getattr(viking_fs, "_ensure_mutable_access", None)- if callable(ensure):- ensure(uri, ctx)--def validate_user_memory_policy(memory_policy: Optional[dict[str, Any]]) -> None:if memory_policy is None:return@@ -84,7 +79,7 @@ def validate_user_memory_policy(memory_policy: Optional[dict[str, Any]]) -> None)-def validate_resource_add_target(+async def validate_resource_add_target(uri: str,*,ctx: RequestContext,@@ -96,11 +91,11 @@ def validate_resource_add_target(kind="resource",field_name="resource_uri",)- _ensure_mutable(viking_fs, resolved, ctx)+ await viking_fs._ensure_access(resolved, ctx, action=AclAction.WRITE)return resolved-def validate_skill_add_target(+async def validate_skill_add_target(uri: str,*,ctx: RequestContext,@@ -112,27 +107,29 @@ def validate_skill_add_target(kind="skill",field_name="skill_uri",)- _ensure_mutable(viking_fs, resolved, ctx)+ await viking_fs._ensure_access(resolved, ctx, action=AclAction.WRITE)return resolved-def validate_add_targets(+async def validate_add_targets(settings: AddTargetsConfig,*,ctx: RequestContext,viking_fs: VikingFS,) -> ResolvedAddTargets:+ resource_uri = (+ await validate_resource_add_target(settings.resource_uri, ctx=ctx, viking_fs=viking_fs)+ if settings.resource_uri+ else None+ )+ skill_uri = (+ await validate_skill_add_target(settings.skill_uri, ctx=ctx, viking_fs=viking_fs)+ if settings.skill_uri+ else None+ )return ResolvedAddTargets(- resource_uri=(- validate_resource_add_target(settings.resource_uri, ctx=ctx, viking_fs=viking_fs)- if settings.resource_uri- else None- ),- skill_uri=(- validate_skill_add_target(settings.skill_uri, ctx=ctx, viking_fs=viking_fs)- if settings.skill_uri- else None- ),+ resource_uri=resource_uri,+ skill_uri=skill_uri,)@@ -166,7 +163,7 @@ async def update_user_config(current = await read_user_config(viking_fs, ctx)before = current.model_dump()result = updater(current)- runtime = validate_add_targets(current.add_targets, ctx=ctx, viking_fs=viking_fs)+ runtime = await validate_add_targets(current.add_targets, ctx=ctx, viking_fs=viking_fs)current.add_targets.resource_uri = runtime.resource_uricurrent.add_targets.skill_uri = runtime.skill_urivalidate_user_memory_policy(current.memory_policy)@@ -204,7 +201,7 @@ async def write_user_config(ctx: RequestContext,user_config: UserConfig,) -> ResolvedAddTargets:- runtime = validate_add_targets(user_config.add_targets, ctx=ctx, viking_fs=viking_fs)+ runtime = await validate_add_targets(user_config.add_targets, ctx=ctx, viking_fs=viking_fs)user_config.add_targets.resource_uri = runtime.resource_uriuser_config.add_targets.skill_uri = runtime.skill_urivalidate_user_memory_policy(user_config.memory_policy)@@ -242,7 +239,7 @@ async def write_user_add_targets(ctx: RequestContext,settings: AddTargetsConfig,) -> ResolvedAddTargets:- runtime = validate_add_targets(settings, ctx=ctx, viking_fs=viking_fs)+ runtime = await validate_add_targets(settings, ctx=ctx, viking_fs=viking_fs)def _set(user_config: UserConfig) -> None:user_config.add_targets = settings@@ -288,7 +285,7 @@ async def effective_resource_add_target() -> Optional[str]:user_settings = await read_user_add_targets(viking_fs, ctx)if user_settings.resource_uri:- return validate_resource_add_target(+ return await validate_resource_add_target(user_settings.resource_uri, ctx=ctx, viking_fs=viking_fs)configured = getattr(@@ -297,7 +294,7 @@ async def effective_resource_add_target(None,)if configured:- return validate_resource_add_target(configured, ctx=ctx, viking_fs=viking_fs)+ return await validate_resource_add_target(configured, ctx=ctx, viking_fs=viking_fs)return None@@ -309,14 +306,16 @@ async def effective_skill_add_target() -> Optional[str]:user_settings = await read_user_add_targets(viking_fs, ctx)if user_settings.skill_uri:- return validate_skill_add_target(user_settings.skill_uri, ctx=ctx, viking_fs=viking_fs)+ return await validate_skill_add_target(+ user_settings.skill_uri, ctx=ctx, viking_fs=viking_fs+ )configured = getattr(getattr(getattr(server_config, "user_config_defaults", None), "add_targets", None),"skill_uri",None,)if configured:- return validate_skill_add_target(configured, ctx=ctx, viking_fs=viking_fs)+ return await validate_skill_add_target(configured, ctx=ctx, viking_fs=viking_fs)return Nonediff --git a/openviking/service/core.py b/openviking/service/core.pyindex baa7ce676..b84a2363b 100644--- a/openviking/service/core.py+++ b/openviking/service/core.py@@ -14,6 +14,10 @@ from openviking.core.directories import DirectoryInitializerfrom openviking.privacy import UserPrivacyConfigServicefrom openviking.resource.uri_mutation_coordinator import UriMutationCoordinatorfrom openviking.resource.watch_scheduler import WatchScheduler+from openviking.server.account_settings import (+ effective_auto_protect_new_content,+ read_account_settings,+)from openviking.server.identity import RequestContext, Rolefrom openviking.service.agent_evolution_service import AgentEvolutionServicefrom openviking.service.debug_service import DebugService@@ -27,6 +31,7 @@ from openviking.service.session_auto_commit import SessionAutoCommitSchedulerfrom openviking.service.session_service import SessionServicefrom openviking.service.task_tracker import get_task_tracker, set_task_trackerfrom openviking.session import create_session_compressor+from openviking.storage.acl import AclManagerfrom openviking.storage.collection_schemas import init_context_collectionfrom openviking.storage.index_consistency import check_index_consistencyfrom openviking.storage.queuefs.add_resource_processor import AddResourceProcessor@@ -180,6 +185,10 @@ class OpenVikingService:self._vikingdb_manager = VikingDBManager(vectordb_config=config.vectordb, queue_manager=self._queue_manager)+ self._vikingdb_manager.acl_manager = AclManager(+ self._vikingdb_manager,+ auto_protect_new_content=self._auto_protect_new_content,+ )# Configure queues if QueueManager is available.# Workers are NOT started here — start() is called after VikingFS is initialized@@ -195,6 +204,12 @@ class OpenVikingService:binding_config, self._encryptor = build_runtime_ragfs_binding_config(self._config)return binding_config+ async def _auto_protect_new_content(self, account_id: str) -> bool:+ if self._viking_fs is None:+ raise NotInitializedError("VikingFS")+ settings = await read_account_settings(self._viking_fs, account_id)+ return effective_auto_protect_new_content(settings)+def _ensure_data_dir_lock_acquired(self) -> None:"""Acquire the process-level data directory lock once for this service instance."""if self._data_dir_lock_acquired:@@ -346,6 +361,7 @@ class OpenVikingService:query_embedder=self._embedder,rerank_config=config.rerank,vector_store=self._vikingdb_manager,+ acl_manager=self._vikingdb_manager.acl_manager,retrieval_config=config.retrieval,grep_config=config.grep,enable_recorder=enable_recorder,diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.pyindex 444d22cce..c1dac36a7 100644--- a/openviking/service/fs_service.py+++ b/openviking/service/fs_service.py@@ -25,6 +25,7 @@ from openviking.storage.abstract_overview import (plan_abstract_overview_refresh,render_abstract_overview,)+from openviking.storage.acl import CreatorAclGrantfrom openviking.storage.content_write import ContentWriteCoordinatorfrom openviking.storage.queuefs import SemanticMsg, get_queue_managerfrom openviking.storage.queuefs.semantic_msg import build_semantic_coalesce_key@@ -193,9 +194,10 @@ class FSService:) -> None:"""Create directory."""viking_fs = self._ensure_initialized()+ directory_uri, abstract_uri = self._resolve_directory_uris(uri)+ directory_preexisting = await viking_fs.exists(directory_uri, ctx=ctx)await viking_fs.mkdir(uri, ctx=ctx)- directory_uri, abstract_uri = self._resolve_directory_uris(uri)abstract = self._normalize_directory_description(description)if not abstract:if await viking_fs.exists(abstract_uri, ctx=ctx):@@ -229,6 +231,9 @@ class FSService:overview="",context_type=context_type_for_uri(directory_uri),ctx=ctx,+ creator_acl_grant=(+ CreatorAclGrant.DIRECT if not directory_preexisting else None+ ),include_overview=False,)@@ -417,6 +422,7 @@ class FSService:recursive=False,account_id=ctx.account_id,user_id=ctx.user.user_id,+ group_ids=ctx.group_ids,peer_id=ctx.user.user_id,role=str(ctx.role),skip_vectorization=False,@@ -734,6 +740,27 @@ class FSService:ctx=ctx,)+ async def get_acl(self, uri: str, ctx: RequestContext) -> Dict[str, Any]:+ return await self._ensure_initialized().get_acl(uri, ctx=ctx)++ async def set_acl(+ self, uri: str, entries: List[Dict[str, str]], ctx: RequestContext+ ) -> Dict[str, Any]:+ return await self._ensure_initialized().set_acl(uri, entries, ctx=ctx)++ async def grant_acl(+ self, uri: str, principal: str, level: str, ctx: RequestContext+ ) -> Dict[str, Any]:+ return await self._ensure_initialized().grant_acl(uri, principal, level, ctx=ctx)++ async def revoke_acl(+ self, uri: str, principal: str, ctx: RequestContext+ ) -> Dict[str, Any]:+ return await self._ensure_initialized().revoke_acl(uri, principal, ctx=ctx)++ async def delete_acl(self, uri: str, ctx: RequestContext) -> Dict[str, Any]:+ return await self._ensure_initialized().delete_acl(uri, ctx=ctx)+async def commit(self,*,diff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.pyindex 1ab5dd24f..6775049ae 100644--- a/openviking/service/resource_service.py+++ b/openviking/service/resource_service.py@@ -54,6 +54,7 @@ from openviking.server.user_config import (effective_resource_add_target,effective_skill_add_target,)+from openviking.storage.acl import AclActionfrom openviking.storage.queuefs import QueueManager, get_queue_managerfrom openviking.storage.queuefs.add_resource_msg import AddResourcePhasefrom openviking.storage.viking_fs import VikingFS@@ -1026,8 +1027,10 @@ class ResourceService:telemetry_id=get_current_telemetry().telemetry_id or None,account_id=ctx.account_id,user_id=ctx.user.user_id,+ group_ids=list(ctx.group_ids),role=str(ctx.role),actor_peer_id=ctx.actor_peer_id,+ bypass_acl=ctx.bypass_acl,lock_handoff=lock_handoff,reason=reason,instruction=instruction,@@ -1120,6 +1123,10 @@ class ResourceService:create_parent=create_parent,)if candidate_uri and defer_candidate_resolution:+ await self._resource_processor.ensure_candidate_parent_write_access(+ candidate_uri=candidate_uri,+ ctx=ctx,+ )return root_uri, None, Trueif candidate_uri:root_uri, resource_lock = await self._resource_processor.reserve_unique_candidate(@@ -1128,11 +1135,17 @@ class ResourceService:)return root_uri, resource_lock, False+ await self._viking_fs._ensure_access(root_uri, ctx, action=AclAction.WRITE)dst_path = self._viking_fs._uri_to_path(root_uri, ctx=ctx)resource_lock = await self._viking_fs._async_agfs.pathlock_acquire_tree(dst_path,timeout_secs=0.0,)+ try:+ await self._viking_fs._ensure_access(root_uri, ctx, action=AclAction.WRITE)+ except BaseException:+ await self._release_lock_ref(resource_lock)+ raisereturn root_uri, resource_lock, False@staticmethod@@ -1771,8 +1784,10 @@ class ResourceService:telemetry_id=telemetry_id or None,account_id=ctx.account_id,user_id=ctx.user.user_id,+ group_ids=list(ctx.group_ids),role=str(ctx.role),actor_peer_id=ctx.actor_peer_id,+ bypass_acl=ctx.bypass_acl,lock_handoff=lock_handoff,reason=reason,instruction=instruction,diff --git a/openviking/storage/acl.py b/openviking/storage/acl.pynew file mode 100644index 000000000..0f012813f--- /dev/null+++ b/openviking/storage/acl.py@@ -0,0 +1,515 @@+"""Context-backed ACL storage and permission resolution."""++from __future__ import annotations++from dataclasses import dataclass+from enum import Enum+from typing import TYPE_CHECKING, Any, Awaitable, Callable, Iterable, Mapping, Sequence++from openviking.core.identifiers import validate_identifier_part, validate_user_id+from openviking.core.namespace import uri_parts+from openviking.server.identity import RequestContext, Role+from openviking.storage.expr import FilterExpr, Or, PathScope+from openviking_cli.exceptions import InvalidArgumentError++if TYPE_CHECKING:+ from openviking.storage.viking_vector_index_backend import VikingVectorIndexBackend+++class AclLevel(str, Enum):+ READ = "read"+ WRITE = "write"+ MANAGE = "manage"+++class AclAction(str, Enum):+ READ = "read"+ WRITE = "write"+ MANAGE = "manage"+++class CreatorAclGrant(str, Enum):+ DIRECT = "direct"+ INHERITED = "inherited"+++_LEVEL_MASK = {+ AclLevel.READ: 1,+ AclLevel.WRITE: 3,+ AclLevel.MANAGE: 7,+}+_MASK_LEVEL = {mask: level for level, mask in _LEVEL_MASK.items()}+ACL_GRANT_FIELDS = ("acl_direct_grants", "acl_inherited_grants")+ACL_CONTEXT_FIELDS = frozenset(("acl_enabled", *ACL_GRANT_FIELDS))+ACL_CREATOR_GRANT_FIELD = "_acl_creator_grant"+_ACL_OUTPUT_FIELDS = ["uri", *sorted(ACL_CONTEXT_FIELDS)]+++@dataclass(frozen=True)+class AclEntry:+ principal: str+ level: AclLevel++ def to_dict(self) -> dict[str, str]:+ return {"principal": self.principal, "level": self.level.value}+++@dataclass(frozen=True)+class DirectAcl:+ entries: tuple[AclEntry, ...] = ()++ @classmethod+ def from_entries(+ cls, entries: Iterable[AclEntry | Mapping[str, Any]]+ ) -> "DirectAcl":+ return cls(tuple(_normalize_entries(entries)))++ @property+ def empty(self) -> bool:+ return not self.entries++ def union(self, other: "DirectAcl") -> "DirectAcl":+ return DirectAcl.from_entries((*self.entries, *other.entries))++ def principals_for(self, action: AclAction) -> frozenset[str]:+ required_mask = _LEVEL_MASK[AclLevel(action.value)]+ return frozenset(+ entry.principal+ for entry in self.entries+ if _LEVEL_MASK[entry.level] & required_mask == required_mask+ )++ def context_fields(self, prefix: str) -> dict[str, Any]:+ return {f"{prefix}_grants": [_encode_grant(entry) for entry in self.entries]}++ @classmethod+ def from_context_fields(cls, record: Mapping[str, Any], prefix: str) -> "DirectAcl":+ raw_grants = record.get(f"{prefix}_grants") or []+ if not isinstance(raw_grants, (list, tuple)):+ raise RuntimeError(f"Invalid ACL grants for {prefix}: expected a list")+ return cls.from_entries(_decode_grant(grant) for grant in raw_grants)+++@dataclass(frozen=True)+class EffectiveAcl:+ enabled: bool+ direct: DirectAcl+ inherited: DirectAcl++ @property+ def permissions(self) -> DirectAcl:+ return self.inherited.union(self.direct)++ def context_fields(self) -> dict[str, Any]:+ return {+ "acl_enabled": self.enabled,+ **self.direct.context_fields("acl_direct"),+ **self.inherited.context_fields("acl_inherited"),+ }+++def normalize_acl_principal(principal: Any) -> str:+ if not isinstance(principal, str):+ raise InvalidArgumentError("principal must be a string")+ normalized = principal.strip()+ kind, separator, identifier = normalized.partition(":")+ if not separator or kind not in {"user", "group"}:+ raise InvalidArgumentError("principal must use user:<id> or group:<id>")+ if kind == "user":+ if identifier != "*":+ error = validate_user_id(identifier)+ if error:+ raise InvalidArgumentError(error)+ else:+ if identifier == "*":+ raise InvalidArgumentError("group:* is not supported")+ error = validate_identifier_part(identifier, "group_id")+ if error:+ raise InvalidArgumentError(error)+ return normalized+++def acl_principals(ctx: RequestContext) -> frozenset[str]:+ return frozenset(+ [+ f"user:{ctx.user.user_id}",+ "user:*",+ *(f"group:{value}" for value in ctx.group_ids),+ ]+ )+++def normalize_acl_level(value: Any) -> AclLevel:+ if isinstance(value, AclLevel):+ return value+ try:+ return AclLevel(str(value).strip())+ except ValueError as exc:+ raise InvalidArgumentError("ACL level must be read, write, or manage") from exc+++def _encode_grant(entry: AclEntry) -> str:+ return f"{_LEVEL_MASK[entry.level]}:{entry.principal}"+++def _decode_grant(raw: Any) -> AclEntry:+ if not isinstance(raw, str):+ raise RuntimeError("Invalid ACL grant token: expected a string")+ raw_mask, separator, raw_principal = raw.partition(":")+ try:+ level = _MASK_LEVEL[int(raw_mask)] if separator else None+ principal = normalize_acl_principal(raw_principal)+ except (InvalidArgumentError, KeyError, ValueError) as exc:+ raise RuntimeError(f"Invalid ACL grant token: {raw!r}") from exc+ if level is None or raw != _encode_grant(AclEntry(principal, level)):+ raise RuntimeError(f"Invalid ACL grant token: {raw!r}")+ return AclEntry(principal, level)+++def acl_grant_tokens(principals: Iterable[str], action: AclAction) -> list[str]:+ """Return exact scalar-index tokens that satisfy *action* for the principals."""+ required_mask = _LEVEL_MASK[AclLevel(action.value)]+ return [+ _encode_grant(AclEntry(principal, level))+ for principal in sorted(set(principals))+ for level, mask in _LEVEL_MASK.items()+ if mask & required_mask == required_mask+ ]+++def _normalize_entries(entries: Iterable[AclEntry | Mapping[str, Any]]) -> list[AclEntry]:+ highest: dict[str, AclLevel] = {}+ for raw in entries:+ if isinstance(raw, AclEntry):+ principal, raw_level = raw.principal, raw.level+ else:+ principal = raw.get("principal")+ raw_level = raw.get("level", "")+ principal = normalize_acl_principal(principal)+ level = normalize_acl_level(raw_level)+ current = highest.get(principal)+ if current is None or _LEVEL_MASK[level] > _LEVEL_MASK[current]:+ highest[principal] = level+ return [AclEntry(principal, highest[principal]) for principal in sorted(highest)]+++def is_acl_uri(uri: str) -> bool:+ return uri_parts(uri)[:1] == ["resources"]+++def acl_ancestors(uri: str) -> list[str]:+ """Return ACL-bearing ancestors from the resource root through *uri*."""+ parts = uri_parts(uri)+ if parts[:1] != ["resources"]:+ raise InvalidArgumentError("ACL is only supported for viking://resources")+ return [f"viking://{'/'.join(parts[:depth])}" for depth in range(1, len(parts) + 1)]+++def has_implicit_manage(ctx: RequestContext, uri: str) -> bool:+ return is_acl_uri(uri) and ctx.role == Role.ADMIN+++def acl_allows(acl: EffectiveAcl, ctx: RequestContext, action: AclAction) -> bool:+ principals = acl.permissions.principals_for(action)+ return not principals.isdisjoint(acl_principals(ctx))+++class AclManager:+ """Stores direct and inherited ACL fields in the context collection."""++ def __init__(+ self,+ context_store: "VikingVectorIndexBackend",+ auto_protect_new_content: Callable[[str], Awaitable[bool]] | None = None,+ ) -> None:+ self._context_store = context_store+ self._auto_protect_new_content = auto_protect_new_content++ @staticmethod+ def _effective_from_record(record: Mapping[str, Any]) -> EffectiveAcl:+ direct = DirectAcl.from_context_fields(record, "acl_direct")+ inherited = DirectAcl.from_context_fields(record, "acl_inherited")+ return EffectiveAcl(+ enabled=bool(record.get("acl_enabled", False))+ or not direct.empty+ or not inherited.empty,+ direct=direct,+ inherited=inherited,+ )++ @classmethod+ def _effective_from_records(cls, records: Sequence[Mapping[str, Any]]) -> EffectiveAcl:+ if not records:+ return EffectiveAcl(False, DirectAcl(), DirectAcl())+ values = {cls._effective_from_record(record) for record in records}+ if len(values) != 1:+ uri = records[0].get("uri", "<unknown>")+ raise RuntimeError(f"Inconsistent ACL fields for context URI: {uri}")+ return values.pop()++ @staticmethod+ def _group_by_uri(records: Sequence[Mapping[str, Any]]) -> dict[str, list[Mapping[str, Any]]]:+ grouped: dict[str, list[Mapping[str, Any]]] = {}+ for record in records:+ uri = record.get("uri")+ if uri:+ grouped.setdefault(str(uri), []).append(record)+ return grouped++ async def _records_for_uris(+ self,+ uris: Iterable[str],+ ctx: RequestContext,+ ) -> list[dict[str, Any]]:+ unique = sorted(set(uris))+ records: list[dict[str, Any]] = []+ for offset in range(0, len(unique), 100):+ conditions = [PathScope("uri", uri, depth=0) for uri in unique[offset : offset + 100]]+ records.extend(+ await self._scroll_all(Or(conditions), _ACL_OUTPUT_FIELDS, ctx)+ )+ return records++ async def _scroll_all(+ self,+ filter_expr: FilterExpr,+ output_fields: list[str],+ ctx: RequestContext,+ ) -> list[dict[str, Any]]:+ records: list[dict[str, Any]] = []+ cursor: str | None = None+ while True:+ page, cursor = await self._context_store.scroll(+ filter=filter_expr,+ limit=500,+ cursor=cursor,+ output_fields=output_fields,+ ctx=ctx,+ )+ records.extend(page)+ if cursor is None:+ return records++ async def _subtree_records(self, uri: str, ctx: RequestContext) -> list[dict[str, Any]]:+ refs = await self._scroll_all(PathScope("uri", uri, depth=-1), ["id"], ctx)+ ids = [str(record["id"]) for record in refs if record.get("id")]+ records: list[dict[str, Any]] = []+ for offset in range(0, len(ids), 500):+ records.extend(+ await self._context_store.get_strict(ids[offset : offset + 500], ctx=ctx)+ )+ return records++ async def get_direct(self, uri: str, ctx: RequestContext) -> DirectAcl:+ acl_ancestors(uri)+ records = await self._records_for_uris([uri], ctx)+ return self._effective_from_records(records).direct++ async def resolve_many(+ self, uris: Iterable[str], ctx: RequestContext+ ) -> dict[str, EffectiveAcl]:+ unique_uris = list(dict.fromkeys(uris))+ paths = {uri: acl_ancestors(uri) for uri in unique_uris}+ exact_records = await self._records_for_uris(unique_uris, ctx)+ exact_groups = self._group_by_uri(exact_records)+ result = {+ uri: self._effective_from_records(exact_groups[uri])+ for uri in unique_uris+ if uri in exact_groups+ }++ missing = [uri for uri in unique_uris if uri not in result]+ if missing:+ ancestor_records = await self._records_for_uris(+ (ancestor for uri in missing for ancestor in paths[uri]), ctx+ )+ ancestor_groups = self._group_by_uri(ancestor_records)+ direct_map = {+ uri: self._effective_from_records(records).direct+ for uri, records in ancestor_groups.items()+ }+ for uri in missing:+ inherited = DirectAcl()+ for ancestor in paths[uri][:-1]:+ inherited = inherited.union(direct_map.get(ancestor, DirectAcl()))+ direct = direct_map.get(uri, DirectAcl())+ result[uri] = EffectiveAcl(+ enabled=not inherited.empty or not direct.empty,+ direct=direct,+ inherited=inherited,+ )+ return result++ async def resolve(self, uri: str, ctx: RequestContext) -> EffectiveAcl:+ return (await self.resolve_many([uri], ctx))[uri]++ async def materialize_context_records(+ self, records: Sequence[dict[str, Any]], ctx: RequestContext+ ) -> list[dict[str, Any]]:+ resource_uris: set[str] = set()+ for record in records:+ uri = record.get("uri")+ if not uri:+ continue+ resource_uri = str(uri)+ if not is_acl_uri(resource_uri):+ continue+ resource_uris.add(resource_uri)+ if not resource_uris:+ return list(records)++ existing = await self._records_for_uris(resource_uris, ctx)+ existing_groups = self._group_by_uri(existing)+ existing_acl = {+ uri: self._effective_from_records(items) for uri, items in existing_groups.items()+ }+ new_uris = resource_uris.difference(existing_acl)+ parents: dict[str, str | None] = {}+ for uri in new_uris:+ ancestors = acl_ancestors(uri)+ parents[uri] = ancestors[-2] if len(ancestors) > 1 else None++ parent_acl = await self.resolve_many([parent for parent in parents.values() if parent], ctx)+ auto_protect_new_content: bool | None = None++ materialized: list[dict[str, Any]] = []+ for record in records:+ record = dict(record)+ raw_creator_grant = record.pop(ACL_CREATOR_GRANT_FIELD, None)+ creator_grant = (+ CreatorAclGrant(raw_creator_grant) if raw_creator_grant is not None else None+ )+ source_uri = str(record.get("uri") or "")+ if source_uri not in resource_uris:+ materialized.append(record)+ continue+ effective = existing_acl.get(source_uri)+ if effective is None:+ parent = parents[source_uri]+ inherited = parent_acl[parent].permissions if parent else DirectAcl()+ direct = DirectAcl()+ creator = (record.get("user") or {}).get("user_id")+ protect_created = bool(parent and parent_acl[parent].enabled)+ if (+ creator+ and creator_grant is not None+ and parent+ and not protect_created+ and self._auto_protect_new_content is not None+ ):+ if auto_protect_new_content is None:+ auto_protect_new_content = await self._auto_protect_new_content(+ ctx.account_id+ )+ protect_created = auto_protect_new_content+ if creator and creator_grant is not None and protect_created:+ creator_acl = DirectAcl.from_entries(+ [AclEntry(f"user:{creator}", AclLevel.MANAGE)]+ )+ if creator_grant == CreatorAclGrant.DIRECT:+ direct = creator_acl+ else:+ inherited = inherited.union(creator_acl)+ effective = EffectiveAcl(not direct.empty or not inherited.empty, direct, inherited)+ materialized.append({**record, **effective.context_fields()})+ return materialized++ async def materialize_moved_record(+ self, record: Mapping[str, Any], new_uri: str, ctx: RequestContext+ ) -> dict[str, Any]:+ if not is_acl_uri(new_uri):+ return EffectiveAcl(False, DirectAcl(), DirectAcl()).context_fields()+ ancestors = acl_ancestors(new_uri)+ parent = ancestors[-2] if len(ancestors) > 1 else None+ inherited = (await self.resolve(parent, ctx)).permissions if parent else DirectAcl()+ source_uri = str(record.get("uri") or "")+ direct = (+ DirectAcl.from_context_fields(record, "acl_direct")+ if is_acl_uri(source_uri)+ else DirectAcl()+ )+ return EffectiveAcl(+ enabled=not direct.empty or not inherited.empty,+ direct=direct,+ inherited=inherited,+ ).context_fields()++ async def _apply_subtree(+ self,+ root_uri: str,+ records: Sequence[dict[str, Any]],+ ctx: RequestContext,+ *,+ root_direct: DirectAcl | None = None,+ ) -> EffectiveAcl:+ grouped = self._group_by_uri(records)+ if root_uri not in grouped:+ raise InvalidArgumentError("ACL target has no context record; index it first")++ direct_map = {+ uri: self._effective_from_records(items).direct for uri, items in grouped.items()+ }+ if root_direct is not None:+ direct_map[root_uri] = root_direct++ root_ancestors = acl_ancestors(root_uri)+ parent = root_ancestors[-2] if len(root_ancestors) > 1 else None+ base = (await self.resolve(parent, ctx)).permissions if parent else DirectAcl()+ effective_by_uri: dict[str, EffectiveAcl] = {}+ root_depth = len(root_ancestors)+ for uri in grouped:+ ancestors = acl_ancestors(uri)+ inherited = base+ for ancestor in ancestors[root_depth - 1 : -1]:+ inherited = inherited.union(direct_map.get(ancestor, DirectAcl()))+ direct = direct_map.get(uri, DirectAcl())+ effective_by_uri[uri] = EffectiveAcl(+ enabled=not direct.empty or not inherited.empty,+ direct=direct,+ inherited=inherited,+ )++ updated = [+ {**record, **effective_by_uri[str(record["uri"])].context_fields()}+ for record in records+ if str(record.get("uri") or "") in effective_by_uri+ ]+ ids = await self._context_store._upsert_many_raw(updated, ctx=ctx)+ if len(ids) != len(updated):+ raise RuntimeError(f"Failed to update {len(updated) - len(ids)} context ACL record(s)")+ return effective_by_uri[root_uri]++ async def refresh_context_subtree(self, uri: str, ctx: RequestContext) -> None:+ records = await self._subtree_records(uri, ctx)+ if records:+ await self._apply_subtree(uri, records, ctx)++ async def set_direct(+ self,+ uri: str,+ entries: Sequence[AclEntry | Mapping[str, Any]],+ ctx: RequestContext,+ ) -> EffectiveAcl:+ if uri_parts(uri) == ["resources"]:+ raise InvalidArgumentError("ACL cannot be set on viking://resources")+ proposed = DirectAcl.from_entries(entries)+ old_records = await self._subtree_records(uri, ctx)+ try:+ effective = await self._apply_subtree(+ uri, old_records, ctx, root_direct=proposed+ )+ except Exception:+ if old_records:+ await self._context_store._upsert_many_raw(old_records, ctx=ctx)+ raise+ return effective++ @staticmethod+ def to_report(uri: str, effective: EffectiveAcl) -> dict[str, Any]:+ return {+ "uri": uri,+ "acl_enabled": effective.enabled,+ "direct_entries": [entry.to_dict() for entry in effective.direct.entries],+ "inherited_entries": [entry.to_dict() for entry in effective.inherited.entries],+ "effective_entries": [entry.to_dict() for entry in effective.permissions.entries],+ }diff --git a/openviking/storage/collection_schemas.py b/openviking/storage/collection_schemas.pyindex 879f40589..33499acff 100644--- a/openviking/storage/collection_schemas.py+++ b/openviking/storage/collection_schemas.py@@ -19,6 +19,7 @@ from typing import Any, Dict, List, Optionalfrom openviking.core.context import ContextType, ResourceContentTypefrom openviking.models.embedder.base import embed_compatfrom openviking.server.identity import RequestContext, Role+from openviking.storage.acl import ACL_CONTEXT_FIELDS, ACL_GRANT_FIELDSfrom openviking.storage.errors import (CollectionNotFoundError,EmbeddingConfigurationError,@@ -118,6 +119,15 @@ class CollectionSchemas:{"FieldName": "content", "FieldType": "text"},{"FieldName": "account_id", "FieldType": "string"},{"FieldName": "owner_user_id", "FieldType": "string"},+ {"FieldName": "acl_enabled", "FieldType": "bool", "DefaultValue": False},+ *[+ {+ "FieldName": field,+ "FieldType": "list<string>",+ "DefaultValue": [],+ }+ for field in ACL_GRANT_FIELDS+ ],])scalar_index = [@@ -136,6 +146,8 @@ class CollectionSchemas:"search_tags","account_id","owner_user_id",+ "acl_enabled",+ *ACL_GRANT_FIELDS,])return {@@ -306,6 +318,26 @@ async def init_context_collection(storage) -> bool:"Existing collection metadata is unavailable; cannot validate embedding compatibility")+ existing_fields = {field.get("FieldName") for field in existing_meta.get("Fields", [])}+ missing_acl_fields = sorted(ACL_CONTEXT_FIELDS - existing_fields)+ existing_scalar_indexes = set(existing_meta.get("ScalarIndex", []))+ missing_acl_indexes = sorted(ACL_CONTEXT_FIELDS - existing_scalar_indexes)++ async def _migrate_acl_schema() -> None:+ if not missing_acl_fields and not missing_acl_indexes:+ return+ if vectordb_cfg.backend not in {"local", "cuvs"}:+ raise EmbeddingConfigurationError(+ "Context collection is missing ACL schema: "+ f"fields={missing_acl_fields}, scalar_indexes={missing_acl_indexes}. "+ "Add them to the remote collection before starting OpenViking."+ )+ if not hasattr(storage, "update_collection_schema"):+ raise EmbeddingConfigurationError(+ "Local context collection does not support automatic schema migration"+ )+ await storage.update_collection_schema(schema["Fields"], schema["ScalarIndex"])+base_description, existing_embedding_meta = _decode_collection_description(existing_meta.get("Description"))@@ -324,10 +356,12 @@ async def init_context_collection(storage) -> bool:)if _embedding_metadata_compatible(existing_embedding_meta, embedding_meta):+ await _migrate_acl_schema()return Falseexisting_count = await storage.count() if hasattr(storage, "count") else 0if existing_embedding_meta is None and existing_count == 0:+ await _migrate_acl_schema()if hasattr(storage, "update_collection_description"):await storage.update_collection_description(_encode_collection_description(@@ -338,6 +372,7 @@ async def init_context_collection(storage) -> bool:return Falseif existing_embedding_meta is None:+ await _migrate_acl_schema()logger.warning("Existing collection has %d vector(s) but no embedding metadata ""(created by an older version). Backfilling with current config and continuing.",@@ -353,6 +388,7 @@ async def init_context_collection(storage) -> bool:return Falseif existing_count == 0 and hasattr(storage, "update_collection_description"):+ await _migrate_acl_schema()await storage.update_collection_description(_encode_collection_description(base_description or "Unified context collection",@@ -380,6 +416,7 @@ async def init_context_collection(storage) -> bool:and not dimension_changedand hasattr(storage, "update_collection_description")):+ await _migrate_acl_schema()logger.warning("Embedding metadata changed (provider/model) but dimension is ""unchanged; embedding.allow_metadata_override=true, so the existing "@@ -586,8 +623,14 @@ class TextEmbeddingHandler(DequeueHandlerBase):embedding_msg = EmbeddingMsg.from_json(data["data"])inserted_data = embedding_msg.context_dataaccount_id = inserted_data.get("account_id", "default")- user = UserIdentifier(account_id=account_id, user_id="default")- ctx = RequestContext(user=user, role=Role.ROOT)+ context_user = inserted_data.get("user") or {}+ user_id = (+ context_user.get("user_id")+ or inserted_data.get("owner_user_id")+ or "default"+ )+ user = UserIdentifier(account_id=account_id, user_id=user_id)+ ctx = RequestContext(user=user, role=Role.USER, bypass_acl=True)collector = resolve_telemetry(embedding_msg.telemetry_id)telemetry_ctx = bind_telemetry(collector) if collector is not None else nullcontext()diff --git a/openviking/storage/content_write.py b/openviking/storage/content_write.pyindex 2c8838dbb..f446e74be 100644--- a/openviking/storage/content_write.py+++ b/openviking/storage/content_write.py@@ -37,6 +37,7 @@ from openviking.storage.abstract_overview import (plan_abstract_overview_refresh,prepare_abstract_overview_write,)+from openviking.storage.acl import AclAction, CreatorAclGrantfrom openviking.storage.errors import LockAcquisitionError, ResourceBusyErrorfrom openviking.storage.queuefs import SemanticMsg, get_queue_managerfrom openviking.storage.queuefs.semantic_msg import build_semantic_coalesce_key@@ -129,7 +130,7 @@ class ContentWriteCoordinator:processing_mode = normalize_processing_mode(processing_mode)normalized_uri = self._validate_uri_path(uri, field_name="uri")self._ensure_content_write_policy(normalized_uri)- self._viking_fs._ensure_mutable_access(normalized_uri, ctx)+ await self._viking_fs._ensure_access(normalized_uri, ctx, action=AclAction.WRITE)if mode == "create":return await self._create_and_write(@@ -213,7 +214,7 @@ class ContentWriteCoordinator:"""normalized_root = self._validate_uri_path(root_uri, field_name="root_uri")await self._validate_batch_root(normalized_root, ctx=ctx)- normalized_operations = self._normalize_batch_operations(+ normalized_operations = await self._normalize_batch_operations(normalized_root, operations, ctx=ctx)@@ -399,14 +400,14 @@ class ContentWriteCoordinator:and len(parts) <= classification.content_index + 1):raise InvalidArgumentError("batch-write root must be inside a resource directory")- self._viking_fs._ensure_mutable_access(root_uri, ctx)+ await self._viking_fs._ensure_access(root_uri, ctx, action=AclAction.WRITE)stat = await self._safe_stat(root_uri, ctx=ctx)if not stat.get("isDir"):raise InvalidArgumentError(f"batch-write root must be an existing directory: {root_uri}")- def _normalize_batch_operations(+ async def _normalize_batch_operations(self,root_uri: str,operations: list[dict[str, Any]],@@ -438,7 +439,7 @@ class ContentWriteCoordinator:f"batch-write target has a different context type: {uri}")self._ensure_content_write_policy(uri)- self._viking_fs._ensure_mutable_access(uri, ctx)+ await self._viking_fs._ensure_access(uri, ctx, action=AclAction.WRITE)has_content = "content" in rawhas_content_base64 = "content_base64" in raw@@ -601,6 +602,7 @@ class ContentWriteCoordinator:recursive=recursive,account_id=ctx.account_id,user_id=ctx.user.user_id,+ group_ids=ctx.group_ids,role=str(ctx.role),skip_vectorization=False,telemetry_id=telemetry.telemetry_id,@@ -655,18 +657,20 @@ class ContentWriteCoordinator:ctx: RequestContext,) -> Dict[str, Any]:self._validate_tag_mode(mode)+ normalized_uri = self._validate_uri_path(uri, field_name="uri")normalized_tags = normalize_search_tags(tags, discard_invalid=True)- stat = await self._safe_stat(uri, ctx=ctx)+ await self._viking_fs._ensure_access(normalized_uri, ctx, action=AclAction.WRITE)+ stat = await self._safe_stat(normalized_uri, ctx=ctx)if stat.get("isDir"):return await self._set_directory_tags(- uri=uri,+ uri=normalized_uri,tags=normalized_tags,mode=mode,recursive=recursive,ctx=ctx,)return await self._set_single_uri_tags(- uri=uri,+ uri=normalized_uri,tags=normalized_tags,mode=mode,recursive=recursive,@@ -813,6 +817,7 @@ class ContentWriteCoordinator:uri=uri,context_type=context_type,ctx=ctx,+ creator_acl_grant=(CreatorAclGrant.DIRECT if mode == "create" else None),)post_process_started = Trueelse:@@ -920,6 +925,7 @@ class ContentWriteCoordinator:uri: str,context_type: str,ctx: RequestContext,+ creator_acl_grant: CreatorAclGrant | None = None,) -> bool:parent = VikingURI(uri).parentif parent is None:@@ -931,6 +937,7 @@ class ContentWriteCoordinator:parent_uri=parent.uri,context_type=context_type,ctx=ctx,+ creator_acl_grant=creator_acl_grant,)async def _vectorize_abstract_overview(self, *, uri: str, ctx: RequestContext) -> bool:@@ -1355,6 +1362,12 @@ class ContentWriteCoordinator:if not updated_targets:raise NotFoundError(uri, "semantic file")+ await self._viking_fs._ensure_access_many(+ [str(target["uri"]) for target in updated_targets],+ ctx,+ action=AclAction.WRITE,+ )+applied_uris: list[str] = []skipped_count = 0for target in updated_targets:diff --git a/openviking/storage/queuefs/add_resource_msg.py b/openviking/storage/queuefs/add_resource_msg.pyindex f4b44b80f..189bfc3b1 100644--- a/openviking/storage/queuefs/add_resource_msg.py+++ b/openviking/storage/queuefs/add_resource_msg.py@@ -20,6 +20,7 @@ class AddResourceMsg:root_uri: straccount_id: struser_id: str+ group_ids: list[str] = field(default_factory=list)role: strpath: str = ""source_path: str = ""@@ -29,6 +30,7 @@ class AddResourceMsg:job_phase: AddResourcePhase | str | None = Nonelock_handoff: Optional[Dict[str, Any]] = Noneactor_peer_id: Optional[str] = None+ bypass_acl: bool = Falsereason: str = ""instruction: str = ""timeout: Optional[float] = None@@ -139,8 +141,14 @@ class AddResourceMsg:root_uri=str(root_uri),account_id=str(data.get("account_id", "default")),user_id=str(data.get("user_id", "default")),+ group_ids=(+ [str(group_id) for group_id in data["group_ids"]]+ if isinstance(data.get("group_ids"), list)+ else []+ ),role=str(data.get("role", "root")),actor_peer_id=data.get("actor_peer_id"),+ bypass_acl=bool(data.get("bypass_acl", False)),telemetry_id=str(data.get("telemetry_id"))if isinstance(data.get("telemetry_id"), str)else None,diff --git a/openviking/storage/queuefs/add_resource_processor.py b/openviking/storage/queuefs/add_resource_processor.pyindex d7fda1189..c2a2ea4aa 100644--- a/openviking/storage/queuefs/add_resource_processor.py+++ b/openviking/storage/queuefs/add_resource_processor.py@@ -105,7 +105,9 @@ class AddResourceProcessor(DequeueHandlerBase):ctx = RequestContext(user=UserIdentifier(msg.account_id, msg.user_id),role=Role(msg.role),+ group_ids=tuple(msg.group_ids),actor_peer_id=msg.actor_peer_id,+ bypass_acl=msg.bypass_acl,)tracker = get_task_tracker()task = await tracker.create(@@ -295,6 +297,7 @@ class AddResourceProcessor(DequeueHandlerBase):user=UserIdentifier(msg.account_id, msg.user_id),role=Role(msg.role),actor_peer_id=msg.actor_peer_id,+ bypass_acl=msg.bypass_acl,),),self._service_loop,diff --git a/openviking/storage/queuefs/embedding_msg_converter.py b/openviking/storage/queuefs/embedding_msg_converter.pyindex 43fa33e2c..495085622 100644--- a/openviking/storage/queuefs/embedding_msg_converter.py+++ b/openviking/storage/queuefs/embedding_msg_converter.py@@ -9,6 +9,7 @@ to EmbeddingMsg objects for asynchronous vector processing.from openviking.core.context import Context, ContextLevelfrom openviking.core.namespace import owner_fields_for_uri+from openviking.storage.acl import ACL_CREATOR_GRANT_FIELD, CreatorAclGrantfrom openviking.storage.queuefs.embedding_msg import EmbeddingMsgfrom openviking.telemetry import get_current_telemetryfrom openviking_cli.utils import get_logger@@ -20,7 +21,9 @@ class EmbeddingMsgConverter:"""Converter for Context objects to EmbeddingMsg."""@staticmethod- def from_context(context: Context) -> EmbeddingMsg | None:+ def from_context(+ context: Context, creator_acl_grant: CreatorAclGrant | None = None+ ) -> EmbeddingMsg | None:"""Convert a Context object to EmbeddingMsg."""@@ -77,6 +80,8 @@ class EmbeddingMsgConverter:else:message = vectorization_text+ if creator_acl_grant is not None:+ context_data[ACL_CREATOR_GRANT_FIELD] = creator_acl_grantembedding_msg = EmbeddingMsg(message=message,context_data=context_data,diff --git a/openviking/storage/queuefs/semantic_dag.py b/openviking/storage/queuefs/semantic_dag.pyindex 655143acc..9b51a1abc 100644--- a/openviking/storage/queuefs/semantic_dag.py+++ b/openviking/storage/queuefs/semantic_dag.py@@ -22,6 +22,7 @@ from openviking.storage.abstract_overview import (read_abstract_overview_pending_snapshot,write_abstract_overview,)+from openviking.storage.acl import CreatorAclGrantfrom openviking.storage.viking_fs import LS_ALL_NODES, get_viking_fsfrom openviking.telemetry import bind_telemetry, get_current_telemetryfrom openviking.utils.ingest_options import IngestOptions@@ -162,6 +163,7 @@ class SemanticDagExecutor:ctx: RequestContext,incremental_update: bool = False,target_uri: Optional[str] = None,+ target_preexisting: Optional[bool] = None,recursive: bool = True,lock: Optional[Dict[str, Any]] = None,is_code_repo: bool = False,@@ -179,6 +181,7 @@ class SemanticDagExecutor:self._ctx = ctxself._incremental_update = incremental_updateself._target_uri = target_uri+ self._target_preexisting = target_preexistingself._recursive = recursiveself._lock = lockself._is_code_repo = is_code_repo@@ -196,6 +199,7 @@ class SemanticDagExecutor:self._changed_paths = {path for key in ("added", "modified", "deleted") for path in self._changes.get(key, [])}+ self._added_paths = {path.rstrip("/") for path in self._changes.get("added", [])}self._node_concurrency = max(1, max_concurrent_llm)self._llm_sem = asyncio.Semaphore(max_concurrent_llm)self._viking_fs = get_viking_fs()@@ -216,6 +220,16 @@ class SemanticDagExecutor:self._overview_cache_lock = asyncio.Lock()self._root_write_result = AbstractOverviewWriteResult(wrote=False)+ def _creator_acl_grant(self, uri: str) -> CreatorAclGrant | None:+ normalized = uri.rstrip("/")+ if self._generation_trigger == "resource_ingest" and self._target_preexisting is False:+ root = self._root_uri.rstrip("/")+ if normalized == root:+ return CreatorAclGrant.DIRECT+ if normalized.startswith(f"{root}/"):+ return CreatorAclGrant.INHERITED+ return CreatorAclGrant.DIRECT if normalized in self._added_paths else None+async def run(self, root_uri: str) -> None:"""Run DAG execution starting from root_uri."""self._root_uri = root_uri@@ -699,6 +713,7 @@ class SemanticDagExecutor:ctx=self._ctx,use_summary=use_summary,ingest_options=self._ingest_options,+ creator_acl_grant=self._creator_acl_grant(file_path),)except Exception as e:logger.error(@@ -954,6 +969,7 @@ class SemanticDagExecutor:overview=overview,ctx=self._ctx,ingest_options=self._ingest_options,+ creator_acl_grant=self._creator_acl_grant(dir_uri),)except Exception as e:logger.error(diff --git a/openviking/storage/queuefs/semantic_msg.py b/openviking/storage/queuefs/semantic_msg.pyindex 1199d6596..02d6fb8d4 100644--- a/openviking/storage/queuefs/semantic_msg.py+++ b/openviking/storage/queuefs/semantic_msg.py@@ -5,7 +5,7 @@import jsonfrom dataclasses import asdict, dataclass, fieldfrom datetime import datetime-from typing import Any, Dict, List, Optional+from typing import Any, Dict, List, Optional, Sequencefrom uuid import uuid4from openviking.utils.ingest_options import IngestOptions@@ -51,6 +51,7 @@ class SemanticMsg:recursive: bool = True # Whether to recursively process subdirectoriesaccount_id: str = "default"user_id: str = "default"+ group_ids: List[str] = field(default_factory=list)peer_id: str = "default"role: str = "root"# Additional flags@@ -79,6 +80,7 @@ class SemanticMsg:recursive: bool = True,account_id: str = "default",user_id: str = "default",+ group_ids: Optional[Sequence[str]] = None,peer_id: str = "default",role: str = "root",skip_vectorization: bool = False,@@ -103,6 +105,7 @@ class SemanticMsg:self.recursive = recursiveself.account_id = account_idself.user_id = user_id+ self.group_ids = list(group_ids or [])self.peer_id = peer_idself.role = roleself.skip_vectorization = skip_vectorization@@ -154,6 +157,7 @@ class SemanticMsg:recursive=data.get("recursive", True),account_id=data.get("account_id", "default"),user_id=data.get("user_id", "default"),+ group_ids=data.get("group_ids") if isinstance(data.get("group_ids"), list) else None,peer_id=data.get("peer_id", "default"),role=data.get("role", "root"),skip_vectorization=data.get("skip_vectorization", False),diff --git a/openviking/storage/queuefs/semantic_processor.py b/openviking/storage/queuefs/semantic_processor.pyindex 5d4126c53..05163b646 100644--- a/openviking/storage/queuefs/semantic_processor.py+++ b/openviking/storage/queuefs/semantic_processor.py@@ -43,6 +43,7 @@ from openviking.storage.abstract_overview import (plan_abstract_overview_refresh,write_abstract_overview,)+from openviking.storage.acl import CreatorAclGrantfrom openviking.storage.errors import LockAcquisitionErrorfrom openviking.storage.queuefs.named_queue import DequeueHandlerBasefrom openviking.storage.queuefs.semantic_dag import DagStats, SemanticDagExecutor@@ -164,10 +165,11 @@ class SemanticProcessor(DequeueHandlerBase):@staticmethoddef _ctx_from_semantic_msg(msg: SemanticMsg) -> RequestContext:- role = Role(msg.role or Role.ROOT)return RequestContext(user=UserIdentifier(msg.account_id, msg.user_id),- role=role,+ role=Role(msg.role),+ group_ids=tuple(msg.group_ids),+ bypass_acl=True,)def _detect_file_type(self, file_name: str) -> str:@@ -260,12 +262,13 @@ class SemanticProcessor(DequeueHandlerBase):or parent_uri == uri.rstrip("/")):return+ parent_ctx = self._ctx_from_semantic_msg(msg)semantic_config = get_openviking_config().semanticdecision = await plan_abstract_overview_refresh(viking_fs=get_viking_fs(),dir_uri=parent_uri,changed_entries=1,- ctx=self._ctx_from_semantic_msg(msg),+ ctx=parent_ctx,l0_body_changed=l0_body_changed,# This helper handles automatic upward propagation only. Manual# refresh/ingest bypasses the threshold for its requested root,@@ -296,6 +299,7 @@ class SemanticProcessor(DequeueHandlerBase):recursive=False,account_id=msg.account_id,user_id=msg.user_id,+ group_ids=msg.group_ids,peer_id=msg.peer_id,role=msg.role,skip_vectorization=msg.skip_vectorization,@@ -470,6 +474,7 @@ class SemanticProcessor(DequeueHandlerBase):ctx=current_ctx,incremental_update=is_incremental,target_uri=target_uri,+ target_preexisting=msg.target_preexisting,recursive=msg.recursive,lock=semantic_lock.lock,is_code_repo=msg.is_code_repo,@@ -1544,6 +1549,7 @@ class SemanticProcessor(DequeueHandlerBase):overview: str,ctx: Optional[RequestContext] = None,ingest_options: IngestOptions | None = None,+ creator_acl_grant: CreatorAclGrant | None = None,) -> None:"""Create directory Context and enqueue to EmbeddingQueue."""@@ -1557,6 +1563,7 @@ class SemanticProcessor(DequeueHandlerBase):context_type=context_type,ctx=active_ctx,ingest_options=ingest_options,+ creator_acl_grant=creator_acl_grant,)async def _vectorize_single_file(@@ -1569,6 +1576,7 @@ class SemanticProcessor(DequeueHandlerBase):use_summary: bool = False,preserve_existing_created_at: bool = False,ingest_options: IngestOptions | None = None,+ creator_acl_grant: CreatorAclGrant | None = None,) -> None:"""Vectorize a single file using its content or summary."""from openviking.utils.embedding_utils import vectorize_file@@ -1583,4 +1591,5 @@ class SemanticProcessor(DequeueHandlerBase):use_summary=use_summary,preserve_existing_created_at=preserve_existing_created_at,ingest_options=ingest_options,+ creator_acl_grant=creator_acl_grant,)diff --git a/openviking/storage/viking_fs/__init__.py b/openviking/storage/viking_fs/__init__.pyindex dae95911c..ad958ce8f 100644--- a/openviking/storage/viking_fs/__init__.py+++ b/openviking/storage/viking_fs/__init__.py@@ -99,6 +99,7 @@ from openviking_cli.utils.logger import get_loggerfrom openviking_cli.utils.uri import VikingURIif TYPE_CHECKING:+ from openviking.storage.acl import AclManagerfrom openviking.storage.viking_vector_index_backend import VikingVectorIndexBackendfrom openviking_cli.utils.config import GrepConfig, RerankConfig, RetrievalConfig@@ -130,6 +131,7 @@ class VikingFS(query_embedder: Optional[Any] = None,rerank_config: Optional["RerankConfig"] = None,vector_store: Optional["VikingVectorIndexBackend"] = None,+ acl_manager: Optional["AclManager"] = None,retrieval_config: Optional["RetrievalConfig"] = None,grep_config: Optional["GrepConfig"] = None,timeout: int = 10,@@ -140,6 +142,7 @@ class VikingFS(self.query_embedder = query_embedderself.rerank_config = rerank_configself.vector_store = vector_store+ self.acl_manager = acl_managerself.retrieval_config = retrieval_configself.grep_config = grep_configself._encryptor = encryptordiff --git a/openviking/storage/viking_fs/_access.py b/openviking/storage/viking_fs/_access.pyindex 05b0f130e..12e249ad6 100644--- a/openviking/storage/viking_fs/_access.py+++ b/openviking/storage/viking_fs/_access.py@@ -6,7 +6,7 @@ import hashlibimport jsonimport refrom contextlib import contextmanager-from typing import Any, Callable, Dict, List, Optional, Union+from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Unionfrom openviking.core.context import ContextLevelfrom openviking.core.namespace import (@@ -19,6 +19,17 @@ from openviking.core.namespace import (from openviking.resource.watch_storage import is_watch_task_control_urifrom openviking.server.error_mapping import is_not_found_errorfrom openviking.server.identity import RequestContext, Role+from openviking.storage.acl import (+ AclAction,+ AclEntry,+ AclLevel,+ acl_allows,+ acl_ancestors,+ has_implicit_manage,+ is_acl_uri,+ normalize_acl_level,+ normalize_acl_principal,+)from openviking.storage.internal_names import STORAGE_INTERNAL_ENTRY_NAMESfrom openviking_cli.exceptions import (FailedPreconditionError,@@ -145,46 +156,208 @@ class _AccessMixin:digest = hashlib.sha256(relative_path.encode("utf-8")).hexdigest()return f"{mount_prefix}{temp_root}/{digest}.encrypt"- def _ensure_access(self, uri: str, ctx: Optional[RequestContext]) -> None:+ async def _can_access_many(+ self,+ uris: Sequence[str],+ ctx: Optional[RequestContext],+ *,+ action: AclAction = AclAction.READ,+ ) -> Dict[str, bool]:+ if not isinstance(action, AclAction):+ raise TypeError(f"action must be AclAction, got {type(action).__name__}")real_ctx = self._ctx_or_default(ctx)- if not self._is_accessible(uri, real_ctx):- raise PermissionDeniedError(f"Access denied for {uri}", resource=uri)+ result: Dict[str, bool] = {}+ valid: List[str] = []+ for uri in dict.fromkeys(uris):+ try:+ self._safe_uri_parts(uri)+ except ValueError:+ result[uri] = False+ else:+ valid.append(uri)++ acl_manager = self.acl_manager+ if acl_manager is None:+ result.update({uri: self._is_accessible(uri, real_ctx) for uri in valid})+ return result++ pending: List[str] = []+ for uri in valid:+ if is_watch_task_control_uri(uri):+ result[uri] = self._is_accessible(uri, real_ctx)+ continue+ if not is_acl_uri(uri):+ result[uri] = self._is_accessible(uri, real_ctx)+ continue+ if real_ctx.bypass_acl or has_implicit_manage(real_ctx, uri):+ result[uri] = True+ else:+ pending.append(uri)++ effective = await acl_manager.resolve_many(pending, real_ctx) if pending else {}+ for uri in pending:+ acl = effective[uri]+ if not acl.enabled:+ result[uri] = self._is_accessible(uri, real_ctx)+ else:+ result[uri] = acl_allows(acl, real_ctx, action)+ return result++ async def _ensure_access(+ self,+ uri: str,+ ctx: Optional[RequestContext],+ *,+ action: AclAction = AclAction.READ,+ ) -> None:+ await self._ensure_access_many([uri], ctx, action=action)- def _ensure_mutable_access(self, uri: str, ctx: Optional[RequestContext]) -> None:- self._ensure_access(uri, ctx)+ async def _ensure_access_many(+ self,+ uris: Sequence[str],+ ctx: Optional[RequestContext],+ *,+ action: AclAction,+ ) -> None:real_ctx = self._ctx_or_default(ctx)+ access = await self._can_access_many(uris, real_ctx, action=action)+ denied = next((uri for uri in uris if not access.get(uri, False)), None)+ if denied is not None:+ raise PermissionDeniedError(f"Access denied for {denied}", resource=denied)++ if action is AclAction.READ:+ return+self._ensure_user_not_deleting(real_ctx)- if is_hidden_by_actor_peer_view(uri, real_ctx) or may_include_hidden_actor_peers(uri, real_ctx):- raise PermissionDeniedError(f"Access denied for {uri}", resource=uri)- self._ensure_supported_write_namespace(uri)- if real_ctx.role != Role.ROOT and uri.rstrip("/") == "viking://temp":- raise PermissionDeniedError(- "Temp root is read-only for non-root users",- resource=uri,- )+ for uri in uris:+ self._safe_uri_parts(uri)+ if uri == "viking://" and real_ctx.role == Role.USER:+ raise PermissionDeniedError(+ "Writing the account root requires an administrator",+ resource=uri,+ )+ if is_hidden_by_actor_peer_view(uri, real_ctx) or may_include_hidden_actor_peers(+ uri, real_ctx+ ):+ raise PermissionDeniedError(f"Access denied for {uri}", resource=uri)+ if action is AclAction.MANAGE:+ self._ensure_supported_delete_namespace(uri)+ canonical_parts = self._safe_uri_parts(uri)+ if real_ctx.role != Role.ROOT and (+ canonical_parts == ["resources"]+ or (canonical_parts[:1] == ["user"] and len(canonical_parts) == 2)+ ):+ raise PermissionDeniedError(+ "Deleting a namespace root requires root access; use a concrete content "+ "path instead.",+ resource=uri,+ )+ self._ensure_supported_write_namespace(uri)+ if real_ctx.role != Role.ROOT and uri.rstrip("/") == "viking://temp":+ raise PermissionDeniedError(+ "Temp root is read-only for non-root users",+ resource=uri,+ )++ async def _ensure_retrieval_scope(+ self, uri: str, ctx: Optional[RequestContext]+ ) -> None:+ self._safe_uri_parts(uri)+ if self.acl_manager is not None and is_acl_uri(uri):+ return+ await self._ensure_access(uri, ctx)- def _ensure_delete_access(self, uri: str, ctx: Optional[RequestContext]) -> None:- self._ensure_access(uri, ctx)+ async def _ensure_acl_manage(+ self, uri: str, ctx: Optional[RequestContext]+ ) -> RequestContext:+ if self.acl_manager is None:+ raise RuntimeError("ACL is not initialized")real_ctx = self._ctx_or_default(ctx)- self._ensure_user_not_deleting(real_ctx)- if is_hidden_by_actor_peer_view(uri, real_ctx) or may_include_hidden_actor_peers(uri, real_ctx):- raise PermissionDeniedError(f"Access denied for {uri}", resource=uri)- self._ensure_supported_delete_namespace(uri)- canonical_parts = self._safe_uri_parts(uri)- if real_ctx.role != Role.ROOT and (- canonical_parts == ["resources"]- or (canonical_parts[:1] == ["user"] and len(canonical_parts) == 2)- ):- raise PermissionDeniedError(- "Deleting a namespace root requires root access; use a concrete content "- "path instead.",- resource=uri,- )- if real_ctx.role != Role.ROOT and uri.rstrip("/") == "viking://temp":- raise PermissionDeniedError(- "Temp root is read-only for non-root users",- resource=uri,- )+ self._safe_uri_parts(uri)+ acl_ancestors(uri)+ if has_implicit_manage(real_ctx, uri):+ return real_ctx+ effective = await self.acl_manager.resolve(uri, real_ctx)+ if effective.enabled and acl_allows(effective, real_ctx, AclAction.MANAGE):+ return real_ctx+ raise PermissionDeniedError(f"ACL management denied for {uri}", resource=uri)++ async def _ensure_acl_target_exists(self, uri: str, ctx: RequestContext) -> None:+ try:+ await self._async_agfs.stat(self._uri_to_path(uri, ctx=ctx))+ except Exception as exc:+ if is_not_found_error(exc):+ raise NotFoundError(uri, "resource") from exc+ raise++ async def get_acl(self, uri: str, ctx: Optional[RequestContext] = None) -> Dict[str, Any]:+ real_ctx = await self._ensure_acl_manage(uri, ctx)+ await self._ensure_acl_target_exists(uri, real_ctx)+ effective = await self.acl_manager.resolve(uri, real_ctx)+ return self.acl_manager.to_report(uri, effective)++ async def set_acl(+ self,+ uri: str,+ entries: Sequence[AclEntry | Mapping[str, Any]],+ ctx: Optional[RequestContext] = None,+ ) -> Dict[str, Any]:+ real_ctx = await self._ensure_acl_manage(uri, ctx)+ path = self._uri_to_path(uri, ctx=real_ctx)+ lease = await self._async_agfs.pathlock_acquire_tree(path)+ try:+ await self._ensure_acl_manage(uri, real_ctx)+ await self._ensure_acl_target_exists(uri, real_ctx)+ effective = await self.acl_manager.set_direct(uri, entries, real_ctx)+ return self.acl_manager.to_report(uri, effective)+ finally:+ await self._async_agfs.pathlock_release(lease)++ async def grant_acl(+ self,+ uri: str,+ principal: str,+ level: AclLevel | str,+ ctx: Optional[RequestContext] = None,+ ) -> Dict[str, Any]:+ return await self._update_acl_entry(uri, principal, level, ctx)++ async def revoke_acl(+ self,+ uri: str,+ principal: str,+ ctx: Optional[RequestContext] = None,+ ) -> Dict[str, Any]:+ return await self._update_acl_entry(uri, principal, None, ctx)++ async def _update_acl_entry(+ self,+ uri: str,+ principal: str,+ level: Optional[AclLevel | str],+ ctx: Optional[RequestContext],+ ) -> Dict[str, Any]:+ principal = normalize_acl_principal(principal)+ normalized_level = normalize_acl_level(level) if level is not None else None+ real_ctx = await self._ensure_acl_manage(uri, ctx)+ path = self._uri_to_path(uri, ctx=real_ctx)+ lease = await self._async_agfs.pathlock_acquire_tree(path)+ try:+ await self._ensure_acl_manage(uri, real_ctx)+ await self._ensure_acl_target_exists(uri, real_ctx)+ direct = await self.acl_manager.get_direct(uri, real_ctx)+ entries = {entry.principal: entry for entry in direct.entries}+ if normalized_level is None:+ entries.pop(principal, None)+ else:+ entries[principal] = AclEntry(principal, normalized_level)+ effective = await self.acl_manager.set_direct(uri, list(entries.values()), real_ctx)+ return self.acl_manager.to_report(uri, effective)+ finally:+ await self._async_agfs.pathlock_release(lease)++ async def delete_acl(self, uri: str, ctx: Optional[RequestContext] = None) -> Dict[str, Any]:+ return await self.set_acl(uri, [], ctx=ctx)def _ensure_user_not_deleting(self, ctx: RequestContext) -> None:guard = getattr(self, "_user_deletion_guard", None)@@ -306,9 +479,10 @@ class _AccessMixin:if not self._is_name_visible_at_path(name, parent_path):return False- uri = self._path_to_uri(entry_path, ctx=ctx)- if not self._is_accessible(uri, ctx):- return False+ if self.acl_manager is None:+ uri = self._path_to_uri(entry_path, ctx=ctx)+ if not self._is_accessible(uri, ctx):+ return Falsereturn True@@ -337,9 +511,9 @@ class _AccessMixin:):"""Shared generator: fetch raw TreeEntry list from Rust, yield (entry, uri) tuples.- node_limit counts ACL-visible entries (see design §6.5), so the user's- node_limit cannot be pushed directly to Rust — doing so would truncate- before filtering and drop entries that should be visible.+ node_limit counts ACL-visible entries, so the user's node_limit cannot+ be pushed directly to Rust — doing so would truncate before filtering+ and drop entries that should be visible.To keep memory bounded without changing that semantic, we push down an*amplified* raw-node limit (node_limit * _TREE_OVERFETCH_FACTOR). If ACL@@ -379,10 +553,8 @@ class _AccessMixin:level_limit=level_limit,)- visible: List[tuple] = []+ candidates: List[tuple] = []for entry in raw_entries:- if node_limit is not None and len(visible) >= node_limit:- breakif not self._is_tree_entry_visible(entry, path, real_ctx):continueif not await self._read_path_visible(uri, entry["path"], primary_path, real_ctx):@@ -393,7 +565,52 @@ class _AccessMixin:entry_path=entry["path"],ctx=ctx,)- visible.append((entry, entry_uri))+ candidates.append((entry, entry_uri))+ if (+ self.acl_manager is None+ and node_limit is not None+ and len(candidates) >= node_limit+ ):+ break++ expose_resource_names = bool(+ self.acl_manager is not None and is_acl_uri(uri)+ )+ if self.acl_manager is None:+ visible = candidates+ else:+ access = await self._can_access_many(+ [entry_uri for _, entry_uri in candidates], real_ctx+ )+ if expose_resource_names:+ denied_directories = {+ entry["path"].rstrip("/")+ for entry, entry_uri in candidates+ if entry.get("info", {}).get("isDir", False)+ and not access.get(entry_uri, False)+ }+ visible = []+ base = path.rstrip("/")+ for entry, entry_uri in candidates:+ parent = entry["path"].rstrip("/").rsplit("/", 1)[0]+ blocked = False+ while parent.startswith(f"{base}/"):+ if parent in denied_directories:+ blocked = True+ break+ parent = parent.rsplit("/", 1)[0]+ if blocked:+ continue+ if access.get(entry_uri, False):+ visible.append((entry, entry_uri))+ else:+ denied_entry = dict(entry)+ denied_entry["access"] = "denied"+ visible.append((denied_entry, entry_uri))+ else:+ visible = [item for item in candidates if access.get(item[1], False)]+ if node_limit is not None:+ visible = visible[:node_limit]# If we still lack enough visible entries but Rust returned a full# page (raw_limit reached), more raw nodes may exist — re-fetch withdiff --git a/openviking/storage/viking_fs/_base.py b/openviking/storage/viking_fs/_base.pyindex 084f4b0bd..47b2f1071 100644--- a/openviking/storage/viking_fs/_base.py+++ b/openviking/storage/viking_fs/_base.py@@ -12,6 +12,7 @@ from openviking_cli.exceptions import (from openviking_cli.utils.logger import get_loggerif TYPE_CHECKING:+ from openviking.storage.acl import AclManagerfrom openviking.storage.viking_vector_index_backend import VikingVectorIndexBackendfrom openviking_cli.utils.config import GrepConfig, RerankConfig, RetrievalConfig@@ -146,6 +147,7 @@ def init_viking_fs(query_embedder: Optional[Any] = None,rerank_config: Optional["RerankConfig"] = None,vector_store: Optional["VikingVectorIndexBackend"] = None,+ acl_manager: Optional["AclManager"] = None,retrieval_config: Optional["RetrievalConfig"] = None,grep_config: Optional["GrepConfig"] = None,timeout: int = 10,@@ -173,6 +175,7 @@ def init_viking_fs(query_embedder=query_embedder,rerank_config=rerank_config,vector_store=vector_store,+ acl_manager=acl_manager,retrieval_config=retrieval_config,grep_config=grep_config,encryptor=encryptor,diff --git a/openviking/storage/viking_fs/_grep.py b/openviking/storage/viking_fs/_grep.pyindex 41212fc8b..8451249f1 100644--- a/openviking/storage/viking_fs/_grep.py+++ b/openviking/storage/viking_fs/_grep.py@@ -57,7 +57,7 @@ class _GrepMixin:Returns:Dict with matches, count, match_count, files_scanned"""- self._ensure_access(uri, ctx)+ await self._ensure_access(uri, ctx)# Skip vector_store.count() — the count field is not needed for grep,# and avoiding it saves one VikingDB API call.await self.stat(uri, ctx=ctx, skip_count=True)@@ -248,7 +248,7 @@ class _GrepMixin:excluded_prefix = Noneif exclude_uri:excluded_prefix = exclude_uri.rstrip("/")- self._ensure_access(excluded_prefix, ctx)+ await self._ensure_access(excluded_prefix, ctx)filter_expr = And([filter_expr,RawDSL({@@ -390,7 +390,7 @@ class _GrepMixin:excluded_path = Noneif exclude_uri:normalized_excluded_uri = exclude_uri.rstrip("/")- self._ensure_access(normalized_excluded_uri, ctx)+ await self._ensure_access(normalized_excluded_uri, ctx)excluded_path = self._uri_to_path(normalized_excluded_uri, ctx=ctx)try:@@ -486,7 +486,7 @@ class _GrepMixin:excluded_prefix = Noneif exclude_uri:excluded_prefix = exclude_uri.rstrip("/")- self._ensure_access(excluded_prefix, ctx)+ await self._ensure_access(excluded_prefix, ctx)file_uris = await self._collect_grep_files(uri,excluded_prefix=excluded_prefix,diff --git a/openviking/storage/viking_fs/_ops.py b/openviking/storage/viking_fs/_ops.pyindex fcc29f6ea..42a1d9cbc 100644--- a/openviking/storage/viking_fs/_ops.py+++ b/openviking/storage/viking_fs/_ops.py@@ -3,6 +3,7 @@"""Core filesystem operations mixin for VikingFS."""import asyncio+from dataclasses import replacefrom datetime import datetime, timezonefrom typing import Any, Dict, List, Optional, Union@@ -16,6 +17,7 @@ from openviking.pyagfs.exceptions import ()from openviking.server.error_mapping import is_not_found_error, map_exceptionfrom openviking.server.identity import RequestContext+from openviking.storage.acl import AclAction, is_acl_urifrom openviking.storage.expr import PathScopefrom openviking.storage.internal_names import STORAGE_INTERNAL_ENTRY_NAMESfrom openviking.storage.viking_fs._base import (@@ -47,7 +49,7 @@ class _OpsMixin:ctx: Optional[RequestContext] = None,) -> bytes:"""Read file"""- self._ensure_access(uri, ctx)+ await self._ensure_access(uri, ctx)real_ctx = self._ctx_or_default(ctx)primary_path = self._uri_to_path(uri, ctx=ctx)@@ -84,7 +86,7 @@ class _OpsMixin:ctx: Optional[RequestContext] = None,) -> str:"""Write file"""- self._ensure_mutable_access(uri, ctx)+ await self._ensure_access(uri, ctx, action=AclAction.WRITE)path = self._uri_to_path(uri, ctx=ctx)if isinstance(data, str):data = data.encode("utf-8")@@ -101,7 +103,7 @@ class _OpsMixin:lease_ref: Dict[str, Any] | None = None,) -> None:"""Create directory."""- self._ensure_mutable_access(uri, ctx)+ await self._ensure_access(uri, ctx, action=AclAction.WRITE)path = self._uri_to_path(uri, ctx=ctx)# Always ensure parent directories exist before creating this directoryawait self._ensure_parent_dirs(path, ctx=ctx, lease_ref=lease_ref)@@ -136,7 +138,9 @@ class _OpsMixin:"""from openviking.storage.errors import LockAcquisitionError, ResourceBusyError- self._ensure_delete_access(uri, ctx)+ guard_ctx = replace(self._ctx_or_default(ctx), bypass_acl=True)+ await self._ensure_access(uri, guard_ctx, action=AclAction.MANAGE)+ await self._ensure_access(uri, ctx, action=AclAction.WRITE)path = self._uri_to_path(uri, ctx=ctx)target_uri = self._path_to_uri(path, ctx=ctx)@@ -163,6 +167,8 @@ class _OpsMixin:if mapped is not None:raise mapped from excraise+ if recursive:+ await self._ensure_access(target_uri, ctx, action=AclAction.MANAGE)# Path does not exist: clean up any orphan index records and returnuris_to_delete = await self._collect_uris(path, recursive, ctx=ctx)uris_to_delete.append(target_uri)@@ -173,6 +179,7 @@ class _OpsMixin:return {"estimated_deleted_count": estimated_count}if is_dir:+ await self._ensure_access(target_uri, ctx, action=AclAction.MANAGE)if not recursive:raise FailedPreconditionError(f"Cannot remove directory without --recursive: {uri}",@@ -191,8 +198,19 @@ class _OpsMixin:raise ResourceBusyError(f"Resource is being processed: {uri}", uri=uri)try:- uris_to_delete = await self._collect_uris(path, recursive, ctx=ctx) if is_dir else []+ uris_to_delete = (+ await self._collect_uris(+ path,+ recursive,+ ctx=ctx,+ strict=is_dir and self.acl_manager is not None,+ )+ if is_dir+ else []+ )uris_to_delete.append(target_uri)+ if is_dir:+ await self._ensure_access_many(uris_to_delete, ctx, action=AclAction.MANAGE)real_ctx = self._ctx_or_default(ctx)estimated_count = await _estimate_deleted_count(path, real_ctx)await self._delete_from_vector_store(uris_to_delete, ctx=ctx)@@ -236,17 +254,15 @@ class _OpsMixin:On VectorDB update failure the copy is cleaned up so the source stays intact."""- self._ensure_mutable_access(old_uri, ctx)- # mv is implemented as copy + recursive rm of the source (see the- # ``rm(old_path, recursive=is_dir)`` below), so the source must also clear- # the delete guard. Without this, a protected account root such as- # ``viking://`` — which rm() rejects up front (#2873) — could still be- # destroyed via mv, since the write guard alone permits the bare root.- self._ensure_delete_access(old_uri, ctx)- self._ensure_mutable_access(new_uri, ctx)+ acl_manager = self.acl_manager+ guard_ctx = replace(self._ctx_or_default(ctx), bypass_acl=True)+ await self._ensure_access(old_uri, guard_ctx, action=AclAction.MANAGE)+ await self._ensure_access(old_uri, ctx, action=AclAction.WRITE)+ await self._ensure_access(new_uri, ctx, action=AclAction.WRITE)old_path = self._uri_to_path(old_uri, ctx=ctx)new_path = self._uri_to_path(new_uri, ctx=ctx)target_uri = self._path_to_uri(old_path, ctx=ctx)+ new_acl_scope = acl_manager is not None and is_acl_uri(new_uri)# Verify source exists and determine type before locking.try:@@ -260,6 +276,9 @@ class _OpsMixin:raiseraise FileNotFoundError(f"mv source not found: {old_uri}") from exc+ if is_dir:+ await self._ensure_access(old_uri, ctx, action=AclAction.MANAGE)+if not is_dir:if new_uri.rstrip("/") != new_uri:raise InvalidArgumentError(@@ -300,9 +319,18 @@ class _OpsMixin:try:uris_to_move = (- await self._collect_uris(old_path, recursive=True, ctx=ctx) if is_dir else []+ await self._collect_uris(+ old_path,+ recursive=True,+ ctx=ctx,+ strict=is_dir and acl_manager is not None,+ )+ if is_dir+ else [])uris_to_move.append(target_uri)+ if is_dir:+ await self._ensure_access_many(uris_to_move, ctx, action=AclAction.MANAGE)# Check if it's temp directory (files already encrypted)is_temp = old_uri.startswith("viking://temp/")@@ -333,9 +361,19 @@ class _OpsMixin:raise# Update VectorDB URIs (on failure, clean up the copy)+ vector_mappings: List[tuple[str, str]] = []try:- await self._update_vector_store_uris(uris_to_move, old_uri, new_uri, ctx=ctx)+ vector_mappings = await self._update_vector_store_uris(+ uris_to_move, old_uri, new_uri, ctx=ctx+ )+ if acl_manager and new_acl_scope:+ await acl_manager.refresh_context_subtree(+ new_uri,+ self._ctx_or_default(ctx),+ )except Exception:+ if vector_mappings:+ await self._restore_vector_store_uris(vector_mappings, ctx=ctx)try:if is_dir:cleanup_lease = await self._async_agfs.pathlock_acquire_tree(@@ -533,7 +571,7 @@ class _OpsMixin:Use this when the count field is not needed (e.g. in grep) to avoidan extra VikingDB API call."""- self._ensure_access(uri, ctx)+ await self._ensure_access(uri, ctx)real_ctx = self._ctx_or_default(ctx)primary_path = self._uri_to_path(uri, ctx=ctx)path = primary_path@@ -580,21 +618,26 @@ class _OpsMixin:return resultasync def exists(self, uri: str, ctx: Optional[RequestContext] = None) -> bool:- """Check if a URI exists.-- Args:- uri: Viking URI- ctx: Request context+ """Check whether a URI is physically present in the caller's namespace.- Returns:- bool: True if the URI exists, False otherwise+ Resource ACLs control access to content, not namespace occupancy. In+ particular, auto-naming must not treat an occupied but unreadable URI+ as available. Namespace isolation still applies to private user,+ actor-peer, upload, and internal paths."""- try:- await self.stat(uri, ctx=ctx)- return True- except Exception:+ real_ctx = self._ctx_or_default(ctx)+ self._safe_uri_parts(uri)+ if not self._is_accessible(uri, real_ctx):return False+ primary_path = self._uri_to_path(uri, ctx=ctx)+ for candidate_path in self._read_paths(uri, ctx=ctx):+ if not await self._read_path_visible(uri, candidate_path, primary_path, real_ctx):+ continue+ if await self._agfs_path_exists(candidate_path):+ return True+ return self._is_session_root_uri(uri)+async def glob(self,pattern: str,@@ -604,7 +647,7 @@ class _OpsMixin:) -> Dict:"""File pattern matching, supports **/*.md recursive."""_ensure_non_empty_search_query(pattern)- self._ensure_access(uri, ctx)+ await self._ensure_access(uri, ctx)real_ctx = self._ctx_or_default(ctx)primary_path = self._uri_to_path(uri, ctx=ctx)path: Optional[str] = None@@ -632,9 +675,8 @@ class _OpsMixin:continuation_token=continuation_token,)+ page_matches: List[str] = []for entry in page.get("entries", []):- if node_limit is not None and node_limit > 0 and len(matches) >= node_limit:- return {"matches": matches, "count": len(matches)}if not self._is_path_entry_visible(entry["path"],entry.get("name") or entry["path"].rsplit("/", 1)[-1],@@ -650,7 +692,22 @@ class _OpsMixin:entry_path=entry["path"],ctx=ctx,)- matches.append(entry_uri)+ if self.acl_manager is None:+ matches.append(entry_uri)+ if node_limit is not None and node_limit > 0 and len(matches) >= node_limit:+ return {"matches": matches, "count": len(matches)}+ continue++ page_matches.append(entry_uri)++ if self.acl_manager is not None:+ access = await self._can_access_many(page_matches, real_ctx)+ for entry_uri in page_matches:+ if not access.get(entry_uri, False):+ continue+ matches.append(entry_uri)+ if node_limit is not None and node_limit > 0 and len(matches) >= node_limit:+ return {"matches": matches, "count": len(matches)}if node_limit is not None and node_limit > 0 and len(matches) >= node_limit:return {"matches": matches, "count": len(matches)}@@ -741,7 +798,7 @@ class _OpsMixin:output="agent"[{'uri': 'viking://resources...', 'size': 100, 'isDir': False, 'modTime': '2026-02-11T08:52:16.256Z', 'rel_path': '.abstract.md', 'abstract': "..."}]"""- self._ensure_access(uri, ctx)+ await self._ensure_access(uri, ctx)if output == "original":return await self._tree_original(uri, show_all_hidden, node_limit, level_limit, ctx=ctx)elif output == "agent":@@ -769,6 +826,17 @@ class _OpsMixin:ctx=ctx,):info = entry["info"]+ if entry.get("access") == "denied":+ result.append(+ {+ "name": info["name"],+ "isDir": info["isDir"],+ "rel_path": entry["rel_path"],+ "uri": entry_uri,+ "access": "denied",+ }+ )+ continuenew_entry = dict(entry.get("extra", {}))new_entry.update({"name": info["name"],@@ -803,6 +871,16 @@ class _OpsMixin:):info = entry["info"]is_dir = info["isDir"]+ if entry.get("access") == "denied":+ result.append(+ {+ "uri": entry_uri,+ "isDir": is_dir,+ "rel_path": entry["rel_path"],+ "access": "denied",+ }+ )+ continueresult.append({"uri": entry_uri,"size": 0 if is_dir else info["size"],@@ -811,14 +889,23 @@ class _OpsMixin:"rel_path": entry["rel_path"],})- await self._batch_fetch_abstracts(result, abs_limit, ctx=ctx)+ await self._batch_fetch_abstracts(+ [entry for entry in result if entry.get("access") != "denied"],+ abs_limit,+ ctx=ctx,+ )return result# ========== Vector Sync Helper Methods ==========async def _collect_uris(- self, path: str, recursive: bool, ctx: Optional[RequestContext] = None+ self,+ path: str,+ recursive: bool,+ ctx: Optional[RequestContext] = None,+ *,+ strict: bool = False,) -> List[str]:"""Recursively collect all URIs (for rm/mv), including directories."""uris = []@@ -827,7 +914,7 @@ class _OpsMixin:try:entries = await self._ls_entries(p, ctx=ctx)except Exception as exc:- if is_not_found_error(exc):+ if is_not_found_error(exc) and not strict:returnraise@@ -916,7 +1003,7 @@ class _OpsMixin:lease_ref: Dict[str, Any] | None = None,) -> None:"""Write file directly. Encryption lock handled internally by EncryptionWrappedFS."""- self._ensure_mutable_access(uri, ctx)+ await self._ensure_access(uri, ctx, action=AclAction.WRITE)path = self._uri_to_path(uri, ctx=ctx)await self._ensure_parent_dirs(path, ctx=ctx, lease_ref=lease_ref)@@ -942,7 +1029,7 @@ class _OpsMixin:Raises:FileNotFoundError: If the file does not exist."""- self._ensure_access(uri, ctx)+ await self._ensure_access(uri, 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@@ -992,7 +1079,7 @@ class _OpsMixin:ctx: Optional[RequestContext] = None,) -> bytes:"""Read single binary file."""- self._ensure_access(uri, ctx)+ await self._ensure_access(uri, ctx)real_ctx = self._ctx_or_default(ctx)primary_path = self._uri_to_path(uri, ctx=ctx)last_not_found: Optional[Exception] = None@@ -1028,7 +1115,7 @@ class _OpsMixin:lease_ref: Dict[str, Any] | None = None,) -> None:"""Write single binary file. Encryption lock handled internally by EncryptionWrappedFS."""- self._ensure_mutable_access(uri, ctx)+ await self._ensure_access(uri, ctx, action=AclAction.WRITE)path = self._uri_to_path(uri, ctx=ctx)await self._ensure_parent_dirs(path, ctx=ctx, lease_ref=lease_ref)@@ -1042,7 +1129,7 @@ class _OpsMixin:lease_ref: Dict[str, Any] | None = None,) -> None:"""Append content to file while holding one exact pathlock lease."""- self._ensure_mutable_access(uri, ctx)+ await self._ensure_access(uri, ctx, action=AclAction.WRITE)path = self._uri_to_path(uri, ctx=ctx)owned_lease = None@@ -1112,7 +1199,7 @@ class _OpsMixin:output="agent"[{'name': '.abstract.md', 'size': 100, 'modTime': '2026-02-11T08:52:16.256Z', 'isDir': False, 'uri': 'viking://resources/.abstract.md', 'abstract': "..."}]"""- self._ensure_access(uri, ctx)+ await self._ensure_access(uri, ctx)if sort_by not in {None, "name", "mtime"}:raise ValueError("sort_by must be 'name' or 'mtime'")if sort_order not in {"asc", "desc"}:@@ -1209,16 +1296,24 @@ class _OpsMixin:ctx: Optional[RequestContext] = None,) -> List[Dict[str, Any]]:"""List directory contents (URI version)."""- real_ctx = self._ctx_or_default(ctx)- entry_items = await self._list_read_path_items(uri, ctx=ctx)+ entry_items = await self._ls_browsable_items(uri, ctx=ctx)entry_items = self._sort_ls_entry_items(entry_items, sort_by, sort_order)# basic infofallback_time = datetime.now(timezone.utc)all_entries = []for entry, entry_uri in entry_items:- if len(all_entries) >= node_limit:- breakname = entry.get("name", "")+ if entry.get("access") == "denied":+ if entry.get("isDir") or not name.startswith(".") or show_all_hidden:+ all_entries.append(+ {+ "name": name,+ "uri": entry_uri,+ "isDir": bool(entry.get("isDir", False)),+ "access": "denied",+ }+ )+ continueraw_time = entry.get("modTime", "")parsed_time = fallback_timeif isinstance(raw_time, (int, float)):@@ -1237,15 +1332,18 @@ class _OpsMixin:"isDir": is_dir,"modTime": format_iso8601(parsed_time),}- if not self._is_accessible(new_entry["uri"], real_ctx):- continueif is_dir:all_entries.append(new_entry)elif not name.startswith("."):all_entries.append(new_entry)elif show_all_hidden:all_entries.append(new_entry)- await self._batch_fetch_abstracts(all_entries, abs_limit, ctx=ctx)+ all_entries = all_entries[:node_limit]+ await self._batch_fetch_abstracts(+ [entry for entry in all_entries if entry.get("access") != "denied"],+ abs_limit,+ ctx=ctx,+ )return all_entriesasync def _ls_original(@@ -1258,29 +1356,58 @@ class _OpsMixin:ctx: Optional[RequestContext] = None,) -> List[Dict[str, Any]]:"""List directory contents (URI version)."""- real_ctx = self._ctx_or_default(ctx)- try:- entry_items = await self._list_read_path_items(uri, ctx=ctx)- entry_items = self._sort_ls_entry_items(entry_items, sort_by, sort_order)- # AGFS returns read-only structure, need to create new dict- all_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+ entry_items = await self._ls_browsable_items(uri, ctx=ctx)+ entry_items = self._sort_ls_entry_items(entry_items, sort_by, sort_order)+ # AGFS returns read-only structure, need to create new dict+ all_entries = []+ for entry, entry_uri in entry_items:+ name = entry.get("name", "")+ if entry.get("access") == "denied":+ new_entry = {+ "name": name,+ "isDir": bool(entry.get("isDir", False)),+ "uri": entry_uri,+ "access": "denied",+ }+ else:+ new_entry = dict(entry)new_entry["uri"] = entry_uri- if not self._is_accessible(new_entry["uri"], real_ctx):- continue- if entry.get("isDir"):- all_entries.append(new_entry)- elif not name.startswith("."):- all_entries.append(new_entry)- elif show_all_hidden:- all_entries.append(new_entry)- return all_entries- except Exception:- raise NotFoundError(uri, "directory")+ if entry.get("isDir"):+ all_entries.append(new_entry)+ elif not name.startswith("."):+ all_entries.append(new_entry)+ elif show_all_hidden:+ all_entries.append(new_entry)+ return all_entries[:node_limit]++ async def _ls_browsable_items(+ self,+ uri: str,+ ctx: Optional[RequestContext] = None,+ ) -> List[tuple[Dict[str, Any], str]]:+ """Return list entries according to namespace-enumeration semantics."""+ entry_items = await self._list_read_path_items(uri, ctx=ctx)+ access = await self._can_access_many([entry_uri for _, entry_uri in entry_items], ctx)+ expose_resource_names = bool(+ self.acl_manager is not None and is_acl_uri(uri)+ )++ browsable = []+ for entry, entry_uri in entry_items:+ if access.get(entry_uri, False):+ browsable.append((entry, entry_uri))+ elif expose_resource_names:+ browsable.append(+ (+ {+ "name": entry.get("name", ""),+ "isDir": bool(entry.get("isDir", False)),+ "access": "denied",+ },+ entry_uri,+ )+ )+ return browsableasync def move_file(self,@@ -1289,8 +1416,8 @@ class _OpsMixin:ctx: Optional[RequestContext] = None,) -> None:"""Move file."""- self._ensure_mutable_access(from_uri, ctx)- self._ensure_mutable_access(to_uri, ctx)+ await self._ensure_access(from_uri, ctx, action=AclAction.WRITE)+ await self._ensure_access(to_uri, ctx, action=AclAction.WRITE)from_path = self._uri_to_path(from_uri, ctx=ctx)await self._copy_file_through_vikingfs(from_uri, to_uri, ctx=ctx)@@ -1317,8 +1444,8 @@ class _OpsMixin:lease_ref: Dict[str, Any] | None = None,) -> None:"""Persist an already-encrypted temp tree without rewriting file bytes."""- self._ensure_access(temp_uri, ctx)- self._ensure_mutable_access(target_uri, ctx)+ await self._ensure_access(temp_uri, ctx)+ await self._ensure_access(target_uri, ctx, action=AclAction.WRITE)src_path = self._uri_to_path(temp_uri, ctx=ctx)dst_path = self._uri_to_path(target_uri, ctx=ctx)fs_ctx = self._pathlock_fs_ctx(ctx, lease_ref)@@ -1337,7 +1464,7 @@ class _OpsMixin:lease_ref: Dict[str, Any] | None = None,) -> None:"""Delete temp directory and its contents."""- self._ensure_mutable_access(temp_uri, ctx)+ await self._ensure_access(temp_uri, ctx, action=AclAction.MANAGE)path = self._uri_to_path(temp_uri, ctx=ctx)fs_ctx = self._pathlock_fs_ctx(ctx, lease_ref)try:diff --git a/openviking/storage/viking_fs/_semantic.py b/openviking/storage/viking_fs/_semantic.pyindex 4b7999696..a306fef0c 100644--- a/openviking/storage/viking_fs/_semantic.py+++ b/openviking/storage/viking_fs/_semantic.py@@ -10,6 +10,7 @@ from openviking.core.retrieval_targets import resolve_retrieval_targetsfrom openviking.server.error_mapping import is_not_found_error, map_exceptionfrom openviking.server.identity import RequestContextfrom openviking.storage.abstract_overview import body_for_preview, render_abstract_overview+from openviking.storage.acl import AclActionfrom openviking.storage.viking_fs._base import (_ensure_non_empty_search_query,logger,@@ -58,7 +59,7 @@ class _SemanticMixin:Bypasses stat() and isDir check. Caller (i.e. _batch_fetch_abstracts)must guarantee that the URI points to a directory."""- self._ensure_access(uri, ctx)+ await self._ensure_access(uri, ctx)real_ctx = self._ctx_or_default(ctx)primary_path = self._uri_to_path(uri, ctx=ctx)for path in self._read_paths(uri, ctx=ctx):@@ -84,7 +85,7 @@ class _SemanticMixin:If the caller points to a file, its parent directory is used instead sothe endpoint remains usable for both file and directory URIs."""- self._ensure_access(uri, ctx)+ await self._ensure_access(uri, ctx)real_ctx = self._ctx_or_default(ctx)primary_path = self._uri_to_path(uri, ctx=ctx)path = primary_path@@ -131,7 +132,7 @@ class _SemanticMixin:If the caller points to a file, its parent directory is used instead sothe endpoint remains usable for both file and directory URIs."""- self._ensure_access(uri, ctx)+ await self._ensure_access(uri, ctx)real_ctx = self._ctx_or_default(ctx)primary_path = self._uri_to_path(uri, ctx=ctx)path = primary_path@@ -216,7 +217,7 @@ class _SemanticMixin:retrieval_targets = resolve_retrieval_targets(target_uri, real_ctx)for target_dir in retrieval_targets.target_directories:- self._ensure_access(target_dir, ctx)+ await self._ensure_retrieval_scope(target_dir, ctx)storage = self._get_vector_store()if not storage:@@ -322,7 +323,7 @@ class _SemanticMixin:query_plan: Optional[QueryPlan] = Nonefor target_dir in retrieval_targets.target_directories:- self._ensure_access(target_dir, ctx)+ await self._ensure_retrieval_scope(target_dir, ctx)# When target_uri exists, read its abstract as optional query-planning context.target_abstract = ""@@ -435,7 +436,7 @@ class _SemanticMixin:) -> None:"""Write context to AGFS (L0/L1/L2)."""- self._ensure_mutable_access(uri, ctx)+ await self._ensure_access(uri, ctx, action=AclAction.WRITE)path = self._uri_to_path(uri, ctx=ctx)try:diff --git a/openviking/storage/viking_fs/_snapshot.py b/openviking/storage/viking_fs/_snapshot.pyindex 0f1de09d7..6cfb60273 100644--- a/openviking/storage/viking_fs/_snapshot.py+++ b/openviking/storage/viking_fs/_snapshot.py@@ -4,6 +4,7 @@import asyncioimport sys+from dataclasses import replacefrom typing import Any, Dict, List, Optional, Unionfrom openviking.pyagfs.exceptions import (@@ -13,7 +14,8 @@ from openviking.pyagfs.exceptions import (AGFSResourceExhaustedError,)from openviking.server.error_mapping import is_not_found_error, map_exception-from openviking.server.identity import RequestContext+from openviking.server.identity import RequestContext, Role+from openviking.storage.acl import AclActionfrom openviking.storage.viking_fs._base import (_prepare_snapshot_diff,logger,@@ -21,6 +23,7 @@ from openviking.storage.viking_fs._base import (from openviking_cli.exceptions import (InvalidArgumentError,NotFoundError,+ PermissionDeniedError,ResourceExhaustedError,)@@ -31,11 +34,92 @@ def _pkg():class _SnapshotMixin:"""Snapshot/git-like version control (commit/restore/show/diff/log)."""+ def _ensure_snapshot_admin(self, ctx: RequestContext) -> None:+ if ctx.role not in {Role.ROOT, Role.ADMIN}:+ raise PermissionDeniedError(+ "Managing snapshot ignore rules requires an administrator",+ resource=".ovgitignore",+ )++ async def _snapshot_scope_uris(+ self,+ uris: List[str],+ ctx: RequestContext,+ ) -> List[str]:+ """Return each requested snapshot scope and all current descendants."""+ result: List[str] = []+ for uri in uris:+ path = self._uri_to_path(uri, ctx=ctx)+ try:+ stat = await self._async_agfs.stat(path)+ except Exception as exc:+ if not is_not_found_error(exc):+ raise+ else:+ if isinstance(stat, dict) and stat.get("isDir", False):+ entries = await self._async_agfs.tree_directory(+ path,+ show_hidden=True,+ node_limit=None,+ level_limit=None,+ )+ result.extend(+ self._path_to_uri(entry["path"], ctx=ctx)+ for entry in entries+ if self._is_tree_entry_visible(entry, path, ctx)+ )+ result.append(uri)+ return list(dict.fromkeys(result))++ async def _ensure_restore_plan_access(+ self,+ plan: Dict[str, Any],+ *,+ tree_dir: str,+ ctx: RequestContext,+ ) -> None:+ """Authorize every VFS mutation reported by a restore dry-run."""+ diff = plan["diff"]+ write_targets: List[str] = []+ for item in diff["to_write"]:+ tree_path = f"{tree_dir}/{item['path']}".strip("/")+ uri = self._tree_path_to_uri(tree_path)+ try:+ await self._async_agfs.stat(self._uri_to_path(uri, ctx=ctx))+ except Exception as exc:+ if not is_not_found_error(exc):+ raise+ parent_tree_path = tree_path.rsplit("/", 1)[0]+ write_targets.append(self._tree_path_to_uri(parent_tree_path))+ else:+ write_targets.append(uri)++ delete_targets = [+ self._tree_path_to_uri(f"{tree_dir}/{path}".strip("/"))+ for path in diff["to_delete"]+ ]+ if write_targets:+ await self._ensure_access_many(+ list(dict.fromkeys(write_targets)),+ ctx,+ action=AclAction.WRITE,+ )+ if delete_targets:+ await self._ensure_access_many(+ list(dict.fromkeys(delete_targets)),+ ctx,+ action=AclAction.WRITE,+ )++ @staticmethod+ def _restore_reindex_context(ctx: RequestContext) -> RequestContext:+ return replace(ctx, bypass_acl=True)+async def system_sync_status(self, uri: str, ctx: Optional[RequestContext] = None) -> Dict[str, Any]:"""Return multi-write sync status for one Viking URI subtree."""- self._ensure_access(uri, ctx)+ await self._ensure_access(uri, ctx)real_ctx = self._ctx_or_default(ctx)path = self._uri_to_path(uri, ctx=ctx)return await self._async_agfs.system_sync_status(@@ -47,7 +131,7 @@ class _SnapshotMixin:self, uri: str, ctx: Optional[RequestContext] = None) -> Dict[str, Any]:"""Retry multi-write sync for one Viking URI subtree."""- self._ensure_mutable_access(uri, ctx)+ await self._ensure_access(uri, ctx, action=AclAction.WRITE)real_ctx = self._ctx_or_default(ctx)path = self._uri_to_path(uri, ctx=ctx)return await self._async_agfs.system_sync_retry(@@ -62,7 +146,9 @@ class _SnapshotMixin:UTF-8, mirroring the Rust layer's reject-non-UTF-8 behavior at committime rather than leaking a raw ``UnicodeDecodeError``."""- path = self._gitignore_agfs_path(ctx)+ real_ctx = self._ctx_or_default(ctx)+ self._ensure_snapshot_admin(real_ctx)+ path = self._gitignore_agfs_path(real_ctx)try:raw = await self._async_agfs.read(path, 0, -1)except Exception as exc:@@ -98,7 +184,9 @@ class _SnapshotMixin:"""if not isinstance(content, str):raise TypeError("content must be a string")- path = self._gitignore_agfs_path(ctx)+ real_ctx = self._ctx_or_default(ctx)+ self._ensure_snapshot_admin(real_ctx)+ path = self._gitignore_agfs_path(real_ctx)data = content.encode("utf-8")if len(data) > self._OVGITIGNORE_MAX_BYTES:raise AGFSInvalidOperationError(@@ -110,7 +198,9 @@ class _SnapshotMixin:async def delete_gitignore(self, ctx: Optional[RequestContext] = None) -> None:"""Delete the account-level .ovgitignore control file. Missing is success."""- path = self._gitignore_agfs_path(ctx)+ real_ctx = self._ctx_or_default(ctx)+ self._ensure_snapshot_admin(real_ctx)+ path = self._gitignore_agfs_path(real_ctx)try:await self._async_agfs.rm(path, recursive=False)except Exception as exc:@@ -155,19 +245,48 @@ class _SnapshotMixin:"""real_ctx = self._ctx_or_default(ctx)account = real_ctx.account_id+ if real_ctx.role != Role.ROOT and paths is None:+ raise PermissionDeniedError(+ "Snapshot commit requires explicit paths",+ resource="viking://",+ )if paths is None:tree_paths: Optional[List[str]] = Noneelse:tree_paths = [self._uri_to_tree_path(p, ctx=real_ctx) for p in paths]- return await self._async_agfs.run(- "git_commit",- account=account,- branch=branch,- message=message,- paths=tree_paths,- author_name=author_name or self._DEFAULT_GIT_AUTHOR_NAME,- author_email=author_email or self._DEFAULT_GIT_AUTHOR_EMAIL,- )+ kwargs = {+ "account": account,+ "branch": branch,+ "message": message,+ "paths": tree_paths,+ "author_name": author_name or self._DEFAULT_GIT_AUTHOR_NAME,+ "author_email": author_email or self._DEFAULT_GIT_AUTHOR_EMAIL,+ }+ if real_ctx.role == Role.ROOT or not paths:+ return await self._async_agfs.run("git_commit", **kwargs)++ from openviking.storage.errors import LockAcquisitionError, ResourceBusyError++ lock_paths: List[str] = []+ for path in sorted(+ {self._uri_to_path(uri, ctx=real_ctx) for uri in paths},+ key=lambda value: (value.count("/"), value),+ ):+ if not any(path == root or path.startswith(f"{root.rstrip('/')}/") for root in lock_paths):+ lock_paths.append(path)+ try:+ lease = await self._async_agfs.pathlock_acquire_tree_batch(lock_paths)+ except LockAcquisitionError as exc:+ raise ResourceBusyError(+ "A snapshot path is being processed",+ uri=paths[0],+ ) from exc+ try:+ scope_uris = await self._snapshot_scope_uris(paths, real_ctx)+ await self._ensure_access_many(scope_uris, real_ctx, action=AclAction.WRITE)+ return await self._async_agfs.run("git_commit", **kwargs)+ finally:+ await self._async_agfs.pathlock_release(lease)async def restore(self,@@ -220,6 +339,14 @@ class _SnapshotMixin:"""real_ctx = self._ctx_or_default(ctx)account = real_ctx.account_id+ acl_project_dir: Optional[str] = None+ if real_ctx.role != Role.ROOT:+ if project_dir is None:+ raise PermissionDeniedError(+ "Snapshot restore requires an explicit project_dir",+ resource="viking://",+ )+ acl_project_dir = project_dirtree_dir: Optional[str]if project_dir is None:tree_dir = None@@ -239,9 +366,9 @@ class _SnapshotMixin:}if tree_dir is not None:kwargs["project_dir"] = tree_dir- # dry_run only computes the diff; it never writes the VFS, so it needs- # no lock.- if dry_run:+ # ROOT is used by the local, unauthenticated deployment mode and by+ # trusted internal callers. Keep its existing dry-run path unchanged.+ if dry_run and real_ctx.role == Role.ROOT:return await self._async_agfs.run("git_restore", **kwargs)from openviking.pyagfs.exceptions import GitRestoreWritebackPartialError@@ -268,6 +395,19 @@ class _SnapshotMixin:)try:+ if acl_project_dir is not None:+ await self._ensure_access(acl_project_dir, real_ctx)+ plan = await self._async_agfs.run(+ "git_restore",+ **{**kwargs, "dry_run": True},+ )+ await self._ensure_restore_plan_access(+ plan,+ tree_dir=tree_dir or "",+ ctx=real_ctx,+ )+ if dry_run:+ return plantry:result = await self._async_agfs.run("git_restore", **kwargs)except GitRestoreWritebackPartialError as exc:@@ -319,7 +459,11 @@ class _SnapshotMixin:"[VikingFS] git restore reindex task creation failed; ""falling back to fire-and-forget rebuild")- self._schedule_vector_rebuild(written=written, deleted=deleted, ctx=real_ctx)+ self._schedule_vector_rebuild(+ written=written,+ deleted=deleted,+ ctx=self._restore_reindex_context(real_ctx),+ )return resultasync def _schedule_restore_reindex_for_paths(@@ -381,6 +525,13 @@ class _SnapshotMixin:directly, stripping the oid/size envelope returned by the binding."""real_ctx = self._ctx_or_default(ctx)+ if real_ctx.role != Role.ROOT and path is None:+ raise PermissionDeniedError(+ "Snapshot show requires an explicit path",+ resource="viking://",+ )+ if path is not None:+ await self._ensure_access(path, real_ctx)account = real_ctx.account_idtree_path = self._uri_to_tree_path(path, ctx=real_ctx) if path else Nonekwargs: Dict[str, Any] = {@@ -409,6 +560,7 @@ class _SnapshotMixin:``X-Snapshot-Oid`` / ``X-Snapshot-Size`` response headers."""real_ctx = self._ctx_or_default(ctx)+ await self._ensure_access(path, real_ctx)account = real_ctx.account_idtree_path = self._uri_to_tree_path(path, ctx=real_ctx)resp = await self._async_agfs.run(@@ -434,16 +586,28 @@ class _SnapshotMixin:) -> Dict[str, Any]:"""Return a unified text diff for one path between two snapshots."""real_ctx = self._ctx_or_default(ctx)- self._ensure_access(path, real_ctx)+ await self._ensure_access(path, real_ctx)+ account = real_ctx.account_id+ tree_path = self._uri_to_tree_path(path, ctx=real_ctx)from_meta: Optional[Dict[str, Any]] = Noneif from_ref:try:- from_meta = await self.show(from_ref, ctx=real_ctx)+ from_meta = await self._async_agfs.run(+ "git_show",+ account=account,+ target_ref=from_ref,+ path=None,+ )except AGFSNotFoundError as exc:raise NotFoundError(from_ref, "git_ref") from exctry:- to_meta = await self.show(to_ref, ctx=real_ctx)+ to_meta = await self._async_agfs.run(+ "git_show",+ account=account,+ target_ref=to_ref,+ path=None,+ )except AGFSNotFoundError as exc:raise NotFoundError(to_ref, "git_ref") from exc@@ -452,11 +616,12 @@ class _SnapshotMixin:async def read_optional(ref: str) -> Optional[bytes]:try:- value = await self.show(- ref,- path=path,+ response = await self._async_agfs.run(+ "git_show",+ account=account,+ target_ref=ref,+ path=tree_path,max_blob_bytes=_pkg().SNAPSHOT_DIFF_MAX_FILE_BYTES,- ctx=real_ctx,)except AGFSPathNotFoundError:return None@@ -466,9 +631,11 @@ class _SnapshotMixin:f"({_pkg().SNAPSHOT_DIFF_MAX_FILE_BYTES} bytes)",details={"limit_bytes": _pkg().SNAPSHOT_DIFF_MAX_FILE_BYTES, "path": path},) from exc- if not isinstance(value, bytes):- raise TypeError(f"git_show returned unexpected blob type: {type(value).__name__}")- return value+ if not isinstance(response, dict) or "bytes" not in response:+ raise TypeError(+ f"git_show returned unexpected blob response: {type(response).__name__}"+ )+ return response["bytes"]before_bytes = await read_optional(from_oid) if from_ref else Noneafter_bytes = await read_optional(to_oid)@@ -543,6 +710,14 @@ class _SnapshotMixin:if limit <= 0:return []real_ctx = self._ctx_or_default(ctx)+ if real_ctx.role != Role.ROOT:+ if not paths:+ raise PermissionDeniedError(+ "Snapshot log requires explicit paths",+ resource="viking://",+ )+ scope_uris = await self._snapshot_scope_uris(paths, real_ctx)+ await self._ensure_access_many(scope_uris, real_ctx, action=AclAction.READ)account = real_ctx.account_idtree_paths = (None if not paths else [self._uri_to_tree_path(path, ctx=real_ctx) for path in paths]@@ -654,10 +829,11 @@ class _SnapshotMixin:from openviking.service.reindex_executor import get_reindex_executorexecutor = get_reindex_executor()+ reindex_ctx = self._restore_reindex_context(ctx)with bind_task_context(task_id, ctx.account_id, ctx.user.user_id):await asyncio.gather(*[- self._run_vector_rebuild(executor, op, uri, level, ctx)+ self._run_vector_rebuild(executor, op, uri, level, reindex_ctx)for (op, uri, level) in tasks])diff --git a/openviking/storage/viking_fs/_vector.py b/openviking/storage/viking_fs/_vector.pyindex e4176da5f..79d77eed7 100644--- a/openviking/storage/viking_fs/_vector.py+++ b/openviking/storage/viking_fs/_vector.py@@ -2,7 +2,7 @@# SPDX-License-Identifier: AGPL-3.0"""Vector store integration mixin for VikingFS."""-from typing import TYPE_CHECKING, Any, List, Optional+from typing import TYPE_CHECKING, Any, List, Optional, Sequencefrom openviking.server.identity import RequestContextfrom openviking.storage.viking_fs._base import logger@@ -40,28 +40,62 @@ class _VectorMixin:old_base: str,new_base: str,ctx: Optional[RequestContext] = None,- ) -> None:+ ) -> List[tuple[str, str]]:"""Update URIs in vector store (when moving files).Preserves vector data and updates URI-derived identifiers without regenerating embeddings."""vector_store = self._get_vector_store()if not vector_store:- return+ return []real_ctx = self._ctx_or_default(ctx)+ mappings: List[tuple[str, str]] = []- for uri in uris:- try:+ try:+ for uri in uris:new_uri = new_base + uri[len(old_base) :]- if await vector_store.update_uri_mapping(+ updated = await vector_store.update_uri_mapping(ctx=real_ctx,uri=uri,new_uri=new_uri,- ):+ )+ if updated:+ mappings.append((uri, new_uri))logger.debug(f"[VikingFS] Updated URI: {uri} -> {new_uri}")- except Exception as e:- logger.warning(f"[VikingFS] Failed to update {uri} in vector store: {e}")+ except Exception:+ await self._restore_vector_store_uris(mappings, ctx=real_ctx)+ raise+ return mappings++ async def _restore_vector_store_uris(+ self,+ mappings: Sequence[tuple[str, str]],+ ctx: Optional[RequestContext] = None,+ ) -> None:+ vector_store = self._get_vector_store()+ if not vector_store:+ return+ real_ctx = self._ctx_or_default(ctx)+ for old_uri, new_uri in sorted(mappings, key=lambda item: item[0].count("/")):+ try:+ restored = await vector_store.update_uri_mapping(+ ctx=real_ctx,+ uri=new_uri,+ new_uri=old_uri,+ )+ if not restored:+ logger.warning(+ "[VikingFS] Vector URI rollback found no records: %s -> %s",+ new_uri,+ old_uri,+ )+ except Exception:+ logger.exception(+ "[VikingFS] Failed to roll back vector URI: %s -> %s",+ new_uri,+ old_uri,+ )def _get_vector_store(self) -> Optional["VikingVectorIndexBackend"]:"""Get vector store instance."""diff --git a/openviking/storage/viking_vector_index_backend.py b/openviking/storage/viking_vector_index_backend.pyindex 6e54bace7..2c3ae592a 100644--- a/openviking/storage/viking_vector_index_backend.py+++ b/openviking/storage/viking_vector_index_backend.py@@ -10,8 +10,15 @@ from contextlib import asynccontextmanagerfrom dataclasses import dataclassfrom typing import Any, AsyncIterator, Dict, List, Mapping, Optional-from openviking.core.namespace import uri_parts, visible_roots+from openviking.core.namespace import canonical_user_root, uri_parts, visible_rootsfrom openviking.server.identity import RequestContext, Role+from openviking.storage.acl import (+ ACL_CONTEXT_FIELDS,+ AclAction,+ AclManager,+ acl_grant_tokens,+ acl_principals,+)from openviking.storage.expr import And, Eq, FilterExpr, In, Or, PathScope, RawDSLfrom openviking.storage.vectordb.collection.collection import Collectionfrom openviking.storage.vectordb.collection.result import UpdateResult@@ -57,18 +64,6 @@ FETCH_BY_URI_OUTPUT_FIELDS = ["owner_user_id",]-URI_REWRITE_OUTPUT_FIELDS = [- "id",- "uri",- "level",- "name",- "description",- "tags",- "abstract",- "content",- "account_id",-]-VIKINGDB_CONTENT_MAX_SIZE = 1024 * 1024@@ -133,6 +128,22 @@ class _AsyncVectorAdapter:lambda: self._adapter.get_collection().update(description=description))+ async def update_collection_schema(+ self, fields: List[Dict[str, Any]], scalar_index: List[str], index_name: str+ ) -> None:+ def _update() -> None:+ collection = self._adapter.get_collection()+ collection.update(fields=fields)+ if self._adapter.mode in {"local", "cuvs"}:+ index_meta = collection.get_index_meta_data(index_name)+ index_meta["ScalarIndex"] = scalar_index+ collection.drop_index(index_name)+ collection.create_index(index_name, index_meta)+ else:+ collection.update_index(index_name, scalar_index=scalar_index)++ await asyncio.to_thread(_update)+class _SingleAccountBackend:"""绑定单个 account 的后端实现(内部类)"""@@ -327,6 +338,12 @@ class _SingleAccountBackend:await self._refresh_meta_data_async()return True+ async def update_collection_schema(+ self, fields: List[Dict[str, Any]], scalar_index: List[str]+ ) -> None:+ await self._async_adapter.update_collection_schema(fields, scalar_index, self._index_name)+ await self._refresh_meta_data_async()+# =========================================================================# Data Operations (with tenant enforcement)# =========================================================================@@ -474,6 +491,12 @@ class _SingleAccountBackend:logger.error("Error getting records: %s", e)return []+ async def get_strict(self, ids: List[str]) -> List[Dict[str, Any]]:+ records = await self._async_adapter.call("get", ids)+ if self._bound_account_id:+ records = [r for r in records if r.get("account_id") == self._bound_account_id]+ return records+async def delete(self, ids: List[str]) -> int:try:if self._bound_account_id:@@ -641,9 +664,17 @@ class _SingleAccountBackend:cursor: Optional[str] = None,output_fields: Optional[List[str]] = None,) -> tuple[List[Dict[str, Any]], Optional[str]]:+ """Scroll records without converting backend failures into an empty page."""+ if isinstance(filter, dict):+ filter = RawDSL(filter)+ if self._bound_account_id:+ account_filter = Eq("account_id", self._bound_account_id)+ filter = And([account_filter, filter]) if filter else account_filter+offset = int(cursor) if cursor else 0- records = await self.filter(- filter=filter or {},+ records = await self._async_adapter.call(+ "query",+ filter=filter,limit=limit,offset=offset,output_fields=output_fields,@@ -771,6 +802,7 @@ class VikingVectorIndexBackend:self.sparse_weight = config.sparse_weightself._collection_name = config.name or "context"self._index_name = config.index_name or DEFAULT_INDEX_NAME+ self.acl_manager: Optional[AclManager] = Noneself._account_backends: Dict[str, _SingleAccountBackend] = {}self._root_backend: Optional[_SingleAccountBackend] = None@@ -869,6 +901,15 @@ class VikingVectorIndexBackend:async def update_collection_description(self, description: str) -> bool:return await self._get_default_backend().update_collection_description(description)+ async def update_collection_schema(+ self, fields: List[Dict[str, Any]], scalar_index: List[str]+ ) -> None:+ default_backend = self._get_default_backend()+ await default_backend.update_collection_schema(fields, scalar_index)+ for backend in [*self._account_backends.values(), self._root_backend]:+ if backend is not None and backend is not default_backend:+ await backend._refresh_meta_data_async()+# =========================================================================# 公开数据操作 API(强制要求 ctx)# =========================================================================@@ -894,6 +935,8 @@ class VikingVectorIndexBackend:options.partial_update,options.search_tag_mode,)+ data = {key: value for key, value in data.items() if key not in ACL_CONTEXT_FIELDS}+ data = (await self._materialize_acl_fields([data], ctx))[0]backend = self._get_backend_for_context(ctx)logger.debug("[VikingVectorIndexBackend.upsert] Using backend for account_id=%s",@@ -929,8 +972,12 @@ class VikingVectorIndexBackend:ctx.account_id,len(data_list),)- backend = self._get_backend_for_context(ctx)- result = await backend.upsert_many(data_list)+ data_list = [+ {key: value for key, value in record.items() if key not in ACL_CONTEXT_FIELDS}+ for record in data_list+ ]+ data_list = await self._materialize_acl_fields(data_list, ctx)+ result = await self._upsert_many_raw(data_list, ctx=ctx)logger.debug("[VikingVectorIndexBackend.upsert_many] Completed with count=%s, result_count=%s",len(data_list),@@ -938,6 +985,34 @@ class VikingVectorIndexBackend:)return result+ async def _upsert_many_raw(+ self, data_list: List[Dict[str, Any]], *, ctx: RequestContext+ ) -> List[str]:+ """Write records whose ACL fields have already been materialized."""+ return await self._get_backend_for_context(ctx).upsert_many(data_list)++ async def _materialize_acl_fields(+ self, records: List[Dict[str, Any]], ctx: RequestContext+ ) -> List[Dict[str, Any]]:+ if not self.acl_manager or not records:+ return records+ return await self.acl_manager.materialize_context_records(records, ctx)++ async def update(self, data: Dict[str, Any], *, ctx: RequestContext) -> UpdateResult:+ """Strict update path. The target record must already exist."""+ data = {key: value for key, value in data.items() if key not in ACL_CONTEXT_FIELDS}+ logger.debug(+ "[VikingVectorIndexBackend.update] uri=%s",+ data.get("uri", ""),+ )+ backend = self._get_backend_for_context(ctx)+ logger.debug(+ f"[VikingVectorIndexBackend.update] Using backend for account_id={ctx.account_id}"+ )+ result = await backend.update(data)+ logger.debug(f"[VikingVectorIndexBackend.update] Completed, result={result}")+ return result+@asynccontextmanagerasync def bulk_ingest(self, *, ctx: RequestContext) -> AsyncIterator[None]:"""Coalesce optional derived-index rebuilds across many write calls.@@ -968,21 +1043,13 @@ class VikingVectorIndexBackend:if exit_cancellation is not None:raise exit_cancellation- async def update(self, data: Dict[str, Any], *, ctx: RequestContext) -> UpdateResult:- """Strict update path. The target record must already exist."""- logger.debug("[VikingVectorIndexBackend.update] uri=%s", data.get("uri", ""))- backend = self._get_backend_for_context(ctx)- logger.debug(- f"[VikingVectorIndexBackend.update] Using backend for account_id={ctx.account_id}"- )- result = await backend.update(data)- logger.debug(f"[VikingVectorIndexBackend.update] Completed, result={result}")- return result-async def get(self, ids: List[str], *, ctx: RequestContext) -> List[Dict[str, Any]]:backend = self._get_backend_for_context(ctx)return await backend.get(ids)+ async def get_strict(self, ids: List[str], *, ctx: RequestContext) -> List[Dict[str, Any]]:+ return await self._get_backend_for_context(ctx).get_strict(ids)+async def delete(self, ids: List[str], *, ctx: RequestContext) -> int:backend = self._get_backend_for_context(ctx)return await backend.delete(ids)@@ -1217,6 +1284,7 @@ class VikingVectorIndexBackend:) -> List[Dict[str, Any]]:if ctx:backend = self._get_backend_for_context(ctx)+ filter = self._merge_filters(filter, self._tenant_filter(ctx))else:backend = self._get_default_backend()return await backend.search_by_keywords(@@ -1414,7 +1482,7 @@ class VikingVectorIndexBackend:records = await self.filter(filter=And(conds),limit=100,- output_fields=URI_REWRITE_OUTPUT_FIELDS,+ output_fields=["id"],ctx=ctx,)if not records:@@ -1446,7 +1514,7 @@ class VikingVectorIndexBackend:return uri if uri.endswith("/.overview.md") else f"{uri}/.overview.md"return uri- success = False+ updated_records: List[Dict[str, Any]] = []ids_to_delete: List[str] = []for record in full_records:if "id" not in record:@@ -1466,6 +1534,10 @@ class VikingVectorIndexBackend:"id": new_id,"uri": new_uri,}+ if self.acl_manager:+ updated.update(+ await self.acl_manager.materialize_moved_record(record, new_uri, ctx)+ )vector = updated.get("vector")if not vector:logger.warning(@@ -1477,17 +1549,23 @@ class VikingVectorIndexBackend:record.get("id"),)continue- result = await self.upsert(updated, ctx=ctx)- if result:- success = True- old_id = record.get("id")- if old_id and old_id != new_id:- ids_to_delete.append(old_id)+ updated_records.append(updated)+ old_id = record.get("id")+ if old_id and old_id != new_id:+ ids_to_delete.append(old_id)++ if not updated_records:+ return False+ new_ids = await self._upsert_many_raw(updated_records, ctx=ctx)+ if len(new_ids) != len(updated_records):+ raise RuntimeError(+ f"Failed to update {len(updated_records) - len(new_ids)} URI mapping record(s)"+ )if ids_to_delete:await self.delete(list(set(ids_to_delete)), ctx=ctx)- return success+ return Trueasync def increment_active_count(self, ctx: RequestContext, uris: List[str]) -> int:updated = 0@@ -1523,8 +1601,12 @@ class VikingVectorIndexBackend:filters.append(Eq("context_type", context_type))targets = [target_dir for target_dir in target_directories or [] if target_dir]- tenant_filter = self._tenant_filter(ctx, context_type=context_type)- if tenant_filter and self._targets_within_visible_roots(ctx, targets):+ tenant_filter = self._tenant_filter(ctx)+ if (+ tenant_filter+ and not self.acl_manager+ and self._targets_within_visible_roots(ctx, targets)+ ):# The target scopes are already narrower than the tenant-visible# roots. Keep account isolation, but avoid recursively evaluating# the broader path scopes as an additional filter.@@ -1562,18 +1644,47 @@ class VikingVectorIndexBackend:for target_parts in (tuple(uri_parts(target)) for target in targets))- @staticmethod- def _tenant_filter(- ctx: RequestContext, context_type: Optional[str] = None- ) -> Optional[FilterExpr]:+ def _tenant_filter(self, ctx: RequestContext) -> Optional[FilterExpr]:+ if ctx.bypass_acl:+ return Eq("account_id", ctx.account_id)if ctx.role == Role.ROOT:return Noneaccount_filter = Eq("account_id", ctx.account_id)- path_filter = Or([PathScope("uri", root, depth=-1) for root in visible_roots(ctx)])- if context_type:- return And([account_filter, path_filter])- return And([account_filter, path_filter])+ if not self.acl_manager:+ return And(+ [+ account_filter,+ Or([PathScope("uri", root, depth=-1) for root in visible_roots(ctx)]),+ ]+ )++ legacy_filter = And(+ [+ RawDSL({"op": "must_not", "field": "acl_enabled", "conds": [True]}),+ Or([PathScope("uri", root, depth=-1) for root in visible_roots(ctx)]),+ ]+ )+ read_grants = acl_grant_tokens(acl_principals(ctx), AclAction.READ)+ shared_acl_filter = And(+ [+ PathScope("uri", "viking://resources", depth=-1),+ Or(+ [+ In("acl_direct_grants", read_grants),+ In("acl_inherited_grants", read_grants),+ ]+ ),+ ]+ )+ access_filters: List[FilterExpr] = [+ legacy_filter,+ shared_acl_filter,+ PathScope("uri", f"{canonical_user_root(ctx)}/resources", depth=-1),+ ]+ if ctx.role == Role.ADMIN:+ access_filters.append(PathScope("uri", "viking://resources", depth=-1))+ return And([account_filter, Or(access_filters)])@staticmethoddef _merge_filters(*filters: Optional[FilterExpr]) -> Optional[FilterExpr]:diff --git a/openviking/utils/embedding_utils.py b/openviking/utils/embedding_utils.pyindex bc6a3fdb0..227e04040 100644--- a/openviking/utils/embedding_utils.py+++ b/openviking/utils/embedding_utils.py@@ -27,6 +27,7 @@ from openviking.parse.parsers.upload_utils import is_text_filefrom openviking.server.identity import RequestContextfrom openviking.service.task_work_index import TaskWorkRejectedfrom openviking.storage.abstract_overview import body_for_preview, embedding_text_for_body+from openviking.storage.acl import CreatorAclGrantfrom openviking.storage.queuefs import get_queue_managerfrom openviking.storage.queuefs.embedding_msg_converter import EmbeddingMsgConverterfrom openviking.storage.viking_fs import LS_ALL_NODES, get_viking_fs@@ -362,6 +363,7 @@ async def vectorize_directory_meta(include_overview: bool = True,scalar_overrides: Optional[Dict[int, Dict[str, Any]]] = None,ingest_options: IngestOptions | None = None,+ creator_acl_grant: CreatorAclGrant | None = None,include_abstract: bool = True,) -> None:"""@@ -411,7 +413,9 @@ async def vectorize_directory_meta(context_abstract.set_vectorize(Vectorize(text=embedding_text_for_body(ContextLevel.ABSTRACT, uri, abstract)))- msg_abstract = EmbeddingMsgConverter.from_context(context_abstract)+ msg_abstract = EmbeddingMsgConverter.from_context(+ context_abstract, creator_acl_grant+ )_apply_scalar_overrides(msg_abstract,(scalar_overrides or {}).get(int(ContextLevel.ABSTRACT.value)),@@ -456,7 +460,9 @@ async def vectorize_directory_meta(context_overview.set_vectorize(Vectorize(text=embedding_text_for_body(ContextLevel.OVERVIEW, uri, overview)))- msg_overview = EmbeddingMsgConverter.from_context(context_overview)+ msg_overview = EmbeddingMsgConverter.from_context(+ context_overview, creator_acl_grant+ )_apply_scalar_overrides(msg_overview,(scalar_overrides or {}).get(int(ContextLevel.OVERVIEW.value)),@@ -501,6 +507,7 @@ async def vectorize_file(preserve_existing_created_at: bool = False,scalar_override: Optional[Dict[str, Any]] = None,ingest_options: IngestOptions | None = None,+ creator_acl_grant: CreatorAclGrant | None = None,) -> bool:"""Vectorize a single file.@@ -616,7 +623,7 @@ async def vectorize_file(logger.debug(f"Skipping file {file_path} (no text content or summary)")return False- embedding_msg = EmbeddingMsgConverter.from_context(context)+ embedding_msg = EmbeddingMsgConverter.from_context(context, creator_acl_grant)if not embedding_msg:return Falsediff --git a/openviking/utils/resource_processor.py b/openviking/utils/resource_processor.pyindex 2ed846fa6..b031020d0 100644--- a/openviking/utils/resource_processor.py+++ b/openviking/utils/resource_processor.py@@ -25,6 +25,7 @@ from openviking.resource.processing_mode import (normalize_processing_mode,)from openviking.server.identity import RequestContext+from openviking.storage.acl import AclAction, CreatorAclGrantfrom openviking.storage.errors import LockAcquisitionErrorfrom openviking.storage.expr import And, Eq, PathScopefrom openviking.storage.internal_names import STORAGE_INTERNAL_ENTRY_NAMES@@ -590,11 +591,15 @@ class ResourceProcessor:ctx=ctx,skip_vectorization=not build_index,ingest_options=ingest_options,+ created=not target_preexisting,)elif build_index:if root_is_file:await self._vectorize_resource_file(- root_uri, ctx=ctx, ingest_options=ingest_options+ root_uri, ctx=ctx, ingest_options=ingest_options,+ creator_acl_grant=(+ CreatorAclGrant.DIRECT if not target_preexisting else None+ ),)elif vectors_only:await self._vectorize_resource_files(@@ -608,13 +613,17 @@ class ResourceProcessor:ctx=ctx,skip_vectorization=not build_index,ingest_options=ingest_options,+ created=not target_preexisting,)elif vectors_only or root_is_file:if not build_index:return resultif root_is_file:await self._vectorize_resource_file(- root_uri, ctx=ctx, ingest_options=ingest_options+ root_uri, ctx=ctx, ingest_options=ingest_options,+ creator_acl_grant=(+ CreatorAclGrant.DIRECT if not target_preexisting else None+ ),)else:await self._vectorize_resource_files(@@ -746,6 +755,7 @@ class ResourceProcessor:*,ctx: RequestContext,ingest_options: IngestOptions | None = None,+ creator_acl_grant: CreatorAclGrant | None = None,) -> None:parent = VikingURI(file_uri).parentif parent is None:@@ -758,6 +768,7 @@ class ResourceProcessor:context_type=context_type_for_uri(file_uri),ctx=ctx,ingest_options=IngestOptions.from_value(ingest_options),+ creator_acl_grant=creator_acl_grant,)async def reserve_unique_candidate(@@ -773,6 +784,7 @@ class ResourceProcessor:viking_fs = get_viking_fs()last_busy_error: Optional[ResourceBusyError] = None+ await self.ensure_candidate_parent_write_access(candidate_uri=candidate_uri, ctx=ctx)for attempt in range(max_attempts + 1):root_uri = candidate_uri if attempt == 0 else f"{candidate_uri}_{attempt}"@@ -805,6 +817,22 @@ class ResourceProcessor:f"Cannot resolve unique name for {candidate_uri} after {max_attempts} attempts")+ async def ensure_candidate_parent_write_access(+ self,+ *,+ candidate_uri: str,+ ctx: RequestContext,+ ) -> None:+ """Require create permission for an auto-named resource candidate."""+ parent_uri = VikingURI(candidate_uri).parent+ if parent_uri is None:+ raise ValueError(f"Resource candidate must have a parent: {candidate_uri}")+ await get_viking_fs()._ensure_access(+ parent_uri.uri,+ ctx,+ action=AclAction.WRITE,+ )+@staticmethodasync def acquire_resource_lock(path: str,diff --git a/openviking/utils/summarizer.py b/openviking/utils/summarizer.pyindex 4577dca3c..c39f6d443 100644--- a/openviking/utils/summarizer.py+++ b/openviking/utils/summarizer.py@@ -39,6 +39,7 @@ class Summarizer:ctx: "RequestContext",skip_vectorization: bool = False,ingest_options: IngestOptions | None = None,+ created: bool = False,) -> Dict[str, Any]:"""Summarize one flat file and refresh its parent directory semantics."""parent = VikingURI(file_uri).parent@@ -59,7 +60,7 @@ class Summarizer:role=str(ctx.role),skip_vectorization=skip_vectorization,telemetry_id=telemetry_id,- changes={"modified": [file_uri]},+ changes={"added" if created else "modified": [file_uri]},coalesce_key=build_semantic_coalesce_key(context_type=context_type_for_uri(file_uri),uri=parent_uri,@@ -182,6 +183,7 @@ class Summarizer:context_type=context_type,account_id=ctx.account_id,user_id=ctx.user.user_id,+ group_ids=ctx.group_ids,peer_id=ctx.user.user_id,role=str(ctx.role),skip_vectorization=skip_vectorization,diff --git a/sdk/go/acl.go b/sdk/go/acl.gonew file mode 100644index 000000000..b3a298e2d--- /dev/null+++ b/sdk/go/acl.go@@ -0,0 +1,60 @@+package openviking++import (+ "context"+ "net/http"+ "net/url"+)++// ACLEntry grants one user or group a read, write, or manage level.+type ACLEntry struct {+ Principal string `json:"principal"`+ Level string `json:"level"`+}++// ACL returns the direct, inherited, and effective ACL for a URI.+func (c *Client) ACL(ctx context.Context, uri string) (map[string]any, error) {+ query := url.Values{"uri": []string{NormalizeURI(uri)}}+ var result map[string]any+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/acl", query, nil, &result)+ return result, err+}++// SetACL replaces the direct ACL on a URI.+func (c *Client) SetACL(ctx context.Context, uri string, entries []ACLEntry) (map[string]any, error) {+ if entries == nil {+ entries = []ACLEntry{}+ }+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPut, "/api/v1/acl", nil, map[string]any{+ "uri": NormalizeURI(uri),+ "entries": entries,+ }, &result)+ return result, err+}++// GrantACL sets one principal's direct ACL level.+func (c *Client) GrantACL(ctx context.Context, uri, principal, level string) (map[string]any, error) {+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/acl/grant", nil, map[string]any{+ "uri": NormalizeURI(uri), "principal": principal, "level": level,+ }, &result)+ return result, err+}++// RevokeACL removes one principal's direct ACL entry.+func (c *Client) RevokeACL(ctx context.Context, uri, principal string) (map[string]any, error) {+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/acl/revoke", nil, map[string]any{+ "uri": NormalizeURI(uri), "principal": principal,+ }, &result)+ return result, err+}++// DeleteACL clears the direct ACL on a URI.+func (c *Client) DeleteACL(ctx context.Context, uri string) (map[string]any, error) {+ query := url.Values{"uri": []string{NormalizeURI(uri)}}+ var result map[string]any+ err := c.doJSON(ctx, http.MethodDelete, "/api/v1/acl", query, nil, &result)+ return result, err+}diff --git a/sdk/go/admin.go b/sdk/go/admin.goindex 656af5bff..591a79090 100644--- a/sdk/go/admin.go+++ b/sdk/go/admin.go@@ -143,6 +143,48 @@ func (c *Client) AdminRegenerateKeyWithOptions(ctx context.Context, accountID, ureturn result, err}+// AdminCreateGroup creates an empty account-scoped group.+func (c *Client) AdminCreateGroup(ctx context.Context, accountID, groupID string) (map[string]any, error) {+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/admin/accounts/"+url.PathEscape(accountID)+"/groups", nil, map[string]any{"group_id": groupID}, &result)+ return result, err+}++// AdminListGroups lists account-scoped groups.+func (c *Client) AdminListGroups(ctx context.Context, accountID string) ([]any, error) {+ var result []any+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/admin/accounts/"+url.PathEscape(accountID)+"/groups", nil, nil, &result)+ return result, err+}++// AdminDeleteGroup deletes an empty group.+func (c *Client) AdminDeleteGroup(ctx context.Context, accountID, groupID string) (map[string]any, error) {+ var result map[string]any+ err := c.doJSON(ctx, http.MethodDelete, "/api/v1/admin/accounts/"+url.PathEscape(accountID)+"/groups/"+url.PathEscape(groupID), nil, nil, &result)+ return result, err+}++// AdminListGroupMembers lists a group's user IDs.+func (c *Client) AdminListGroupMembers(ctx context.Context, accountID, groupID string) (map[string]any, error) {+ var result map[string]any+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/admin/accounts/"+url.PathEscape(accountID)+"/groups/"+url.PathEscape(groupID)+"/members", nil, nil, &result)+ return result, err+}++// AdminAddGroupMember adds an existing account user to a group.+func (c *Client) AdminAddGroupMember(ctx context.Context, accountID, groupID, userID string) (map[string]any, error) {+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPut, "/api/v1/admin/accounts/"+url.PathEscape(accountID)+"/groups/"+url.PathEscape(groupID)+"/members/"+url.PathEscape(userID), nil, nil, &result)+ return result, err+}++// AdminRemoveGroupMember removes a user from a group.+func (c *Client) AdminRemoveGroupMember(ctx context.Context, accountID, groupID, userID string) (map[string]any, error) {+ var result map[string]any+ err := c.doJSON(ctx, http.MethodDelete, "/api/v1/admin/accounts/"+url.PathEscape(accountID)+"/groups/"+url.PathEscape(groupID)+"/members/"+url.PathEscape(userID), nil, nil, &result)+ return result, err+}+// AdminMigrate starts legacy data migration or cleanup.func (c *Client) AdminMigrate(ctx context.Context, opts *AdminMigrateOptions) (map[string]any, error) {action := "migrate"diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.pyindex c0267e9d5..f75b88a14 100644--- a/sdk/python/openviking_sdk/client.py+++ b/sdk/python/openviking_sdk/client.py@@ -1261,6 +1261,45 @@ class AsyncHTTPClient:)return self._handle_response_data(response).get("result", {})+ async def acl_get(self, uri: str) -> Dict[str, Any]:+ response = await self._http.get(+ "/api/v1/acl", params={"uri": VikingURI.normalize(uri)}+ )+ return self._handle_response_data(response).get("result", {})++ async def acl_set(+ self, uri: str, entries: List[Dict[str, str]]+ ) -> Dict[str, Any]:+ response = await self._http.put(+ "/api/v1/acl",+ json={"uri": VikingURI.normalize(uri), "entries": entries},+ )+ return self._handle_response_data(response).get("result", {})++ async def acl_grant(self, uri: str, principal: str, level: str) -> Dict[str, Any]:+ response = await self._http.post(+ "/api/v1/acl/grant",+ json={+ "uri": VikingURI.normalize(uri),+ "principal": principal,+ "level": level,+ },+ )+ return self._handle_response_data(response).get("result", {})++ async def acl_revoke(self, uri: str, principal: str) -> Dict[str, Any]:+ response = await self._http.post(+ "/api/v1/acl/revoke",+ json={"uri": VikingURI.normalize(uri), "principal": principal},+ )+ return self._handle_response_data(response).get("result", {})++ async def acl_delete(self, uri: str) -> Dict[str, Any]:+ response = await self._http.request(+ "DELETE", "/api/v1/acl", params={"uri": VikingURI.normalize(uri)}+ )+ return self._handle_response_data(response).get("result", {})+async def find(self,query: str = "",@@ -1779,6 +1818,47 @@ class AsyncHTTPClient:)return self._handle_response(response)+ async def admin_create_group(self, account_id: str, group_id: str) -> Dict[str, Any]:+ response = await self._http.post(+ f"/api/v1/admin/accounts/{account_id}/groups",+ json={"group_id": group_id},+ )+ return self._handle_response(response)++ async def admin_list_groups(self, account_id: str) -> List[Any]:+ response = await self._http.get(f"/api/v1/admin/accounts/{account_id}/groups")+ return self._handle_response(response)++ async def admin_delete_group(self, account_id: str, group_id: str) -> Dict[str, Any]:+ response = await self._http.delete(+ f"/api/v1/admin/accounts/{account_id}/groups/{group_id}"+ )+ return self._handle_response(response)++ async def admin_list_group_members(+ self, account_id: str, group_id: str+ ) -> Dict[str, Any]:+ response = await self._http.get(+ f"/api/v1/admin/accounts/{account_id}/groups/{group_id}/members"+ )+ return self._handle_response(response)++ async def admin_add_group_member(+ self, account_id: str, group_id: str, user_id: str+ ) -> Dict[str, Any]:+ response = await self._http.put(+ f"/api/v1/admin/accounts/{account_id}/groups/{group_id}/members/{user_id}"+ )+ return self._handle_response(response)++ async def admin_remove_group_member(+ self, account_id: str, group_id: str, user_id: str+ ) -> Dict[str, Any]:+ response = await self._http.delete(+ f"/api/v1/admin/accounts/{account_id}/groups/{group_id}/members/{user_id}"+ )+ return self._handle_response(response)+async def admin_migrate(self, cleanup: bool = False) -> Dict[str, Any]:action = "cleanup" if cleanup else "migrate"response = await self._request("POST", "/api/v1/admin/migrate", json={"action": action})@@ -2363,6 +2443,21 @@ class SyncHTTPClient:))+ def acl_get(self, uri: str) -> Dict[str, Any]:+ return run_async(self._async_client.acl_get(uri))++ def acl_set(self, uri: str, entries: List[Dict[str, str]]) -> Dict[str, Any]:+ return run_async(self._async_client.acl_set(uri, entries))++ def acl_grant(self, uri: str, principal: str, level: str) -> Dict[str, Any]:+ return run_async(self._async_client.acl_grant(uri, principal, level))++ def acl_revoke(self, uri: str, principal: str) -> Dict[str, Any]:+ return run_async(self._async_client.acl_revoke(uri, principal))++ def acl_delete(self, uri: str) -> Dict[str, Any]:+ return run_async(self._async_client.acl_delete(uri))+def find(self,query: str = "",@@ -2668,6 +2763,32 @@ class SyncHTTPClient:) -> Dict[str, Any]:return run_async(self._async_client.admin_regenerate_key(account_id, user_id, seed=seed))+ def admin_create_group(self, account_id: str, group_id: str) -> Dict[str, Any]:+ return run_async(self._async_client.admin_create_group(account_id, group_id))++ def admin_list_groups(self, account_id: str) -> List[Any]:+ return run_async(self._async_client.admin_list_groups(account_id))++ def admin_delete_group(self, account_id: str, group_id: str) -> Dict[str, Any]:+ return run_async(self._async_client.admin_delete_group(account_id, group_id))++ def admin_list_group_members(self, account_id: str, group_id: str) -> Dict[str, Any]:+ return run_async(self._async_client.admin_list_group_members(account_id, group_id))++ def admin_add_group_member(+ self, account_id: str, group_id: str, user_id: str+ ) -> Dict[str, Any]:+ return run_async(+ self._async_client.admin_add_group_member(account_id, group_id, user_id)+ )++ def admin_remove_group_member(+ self, account_id: str, group_id: str, user_id: str+ ) -> Dict[str, Any]:+ return run_async(+ self._async_client.admin_remove_group_member(account_id, group_id, user_id)+ )+def admin_migrate(self, cleanup: bool = False) -> Dict[str, Any]:return run_async(self._async_client.admin_migrate(cleanup=cleanup))diff --git a/tests/cli/conftest.py b/tests/cli/conftest.pyindex b8bff483b..3fb8915b1 100644--- a/tests/cli/conftest.py+++ b/tests/cli/conftest.py@@ -137,12 +137,24 @@ def _admin_headers() -> dict[str, str]:return {"Authorization": f"Bearer {ROOT_API_KEY}"}-def _extract_user_key(users: list[object], user_id: str) -> str:+def _find_user(users: list[object], user_id: str) -> dict[str, object] | None:for user in users:if isinstance(user, dict) and user.get("user_id") == user_id:- api_key = user.get("api_key")- if isinstance(api_key, str):- return api_key+ return user+ return None+++def _register_regular_user(account_id: str, user_id: str) -> str:+ register_resp = httpx.post(+ f"{BASE_URL}/api/v1/admin/accounts/{account_id}/users",+ headers=_admin_headers(),+ json={"user_id": user_id, "role": "user"},+ timeout=10.0,+ )+ if register_resp.status_code in (200, 201):+ user_key = register_resp.json().get("result", {}).get("user_key")+ if isinstance(user_key, str) and user_key:+ return user_keyreturn ""@@ -172,8 +184,9 @@ def _resolve_api_key() -> str:# Retry a few times to handle server startup race conditions.account_id = CLI_ACCOUNT or "test-account"user_id = CLI_USER or "test-user"+ admin_user_id = f"{user_id}-admin"- for attempt in range(5):+ for _attempt in range(5):try:list_resp = httpx.get(f"{BASE_URL}/api/v1/admin/accounts/{account_id}/users",@@ -184,54 +197,38 @@ def _resolve_api_key() -> str:create_resp = httpx.post(f"{BASE_URL}/api/v1/admin/accounts",headers=_admin_headers(),- json={"account_id": account_id, "admin_user_id": user_id},+ json={"account_id": account_id, "admin_user_id": admin_user_id},timeout=10.0,)if create_resp.status_code in (200, 201):- user_key = create_resp.json().get("result", {}).get("user_key")- if isinstance(user_key, str) and user_key:+ user_key = _register_regular_user(account_id, user_id)+ if user_key:return user_keyelif list_resp.status_code == 200:users = list_resp.json().get("result", [])if isinstance(users, list):- user_key = _extract_user_key(users, user_id)- if user_key:- return user_key- user_exists = any(- (isinstance(user, dict) and user.get("user_id") == user_id)- or (isinstance(user, str) and user == user_id)- for user in users- )- else:- user_exists = False-- if not user_exists:- register_resp = httpx.post(- f"{BASE_URL}/api/v1/admin/accounts/{account_id}/users",- headers=_admin_headers(),- json={"user_id": user_id, "role": "admin"},- timeout=10.0,- )- if register_resp.status_code in (200, 201):- user_key = register_resp.json().get("result", {}).get("user_key")- if isinstance(user_key, str) and user_key:- return user_key- else:- httpx.put(- f"{BASE_URL}/api/v1/admin/accounts/{account_id}/users/{user_id}/role",- headers=_admin_headers(),- json={"role": "admin"},- timeout=10.0,- )- key_resp = httpx.post(- f"{BASE_URL}/api/v1/admin/accounts/{account_id}/users/{user_id}/key",- headers=_admin_headers(),- json={},- timeout=10.0,- )- if key_resp.status_code == 200:- user_key = key_resp.json().get("result", {}).get("user_key")- if isinstance(user_key, str) and user_key:+ candidates = [user_id] if CLI_USER else [user_id, f"{user_id}-regular"]+ for candidate_user_id in candidates:+ user_record = _find_user(users, candidate_user_id)+ if user_record is None:+ user_key = _register_regular_user(account_id, candidate_user_id)+ elif user_record.get("role") == "user":+ api_key = user_record.get("api_key")+ user_key = api_key if isinstance(api_key, str) else ""+ if not user_key:+ key_resp = httpx.post(+ f"{BASE_URL}/api/v1/admin/accounts/{account_id}/users/"+ f"{candidate_user_id}/key",+ headers=_admin_headers(),+ json={},+ timeout=10.0,+ )+ if key_resp.status_code == 200:+ regenerated = key_resp.json().get("result", {}).get("user_key")+ user_key = regenerated if isinstance(regenerated, str) else ""+ else:+ user_key = ""+ if user_key:return user_keyexcept Exception:pass@@ -358,10 +355,12 @@ def pytest_collection_modifyitems(config, items):elif not API_KEY:skip_reason = "Could not obtain a valid user API key for data-plane operations"- if skip_reason:- skip_cli = pytest.mark.skip(reason=skip_reason)- for item in items:- if item.get_closest_marker("cli_remote"):+ skip_cli = pytest.mark.skip(reason=skip_reason) if skip_reason else None+ for item in items:+ if item.get_closest_marker("cli_remote"):+ if "ensure_resources_dir" not in item.fixturenames:+ item.fixturenames.append("ensure_resources_dir")+ if skip_cli is not None:item.add_marker(skip_cli)@@ -607,15 +606,6 @@ def _find_file_in_pack(pack_uri, retries=10, interval=5):return None-def pytest_collection_modifyitems(items):- for item in items:- if (- item.get_closest_marker("cli_remote")- and "ensure_resources_dir" not in item.fixturenames- ):- item.fixturenames.append("ensure_resources_dir")--@pytest.fixture(scope="session")def ensure_resources_dir():r = ov_mkdir("viking://resources")diff --git a/tests/cli/test_cli_content.py b/tests/cli/test_cli_content.pyindex a552fdbb5..b040d0300 100644--- a/tests/cli/test_cli_content.py+++ b/tests/cli/test_cli_content.py@@ -7,7 +7,7 @@ import tempfileimport uuidimport pytest-from conftest import ov, ov_add_resource, ov_reindex, ov_write+from conftest import ov, ov_add_resource, ov_reindex, ov_rm, ov_writepytestmark = pytest.mark.cli_remote@@ -72,20 +72,23 @@ class TestContentWrite:class TestContentReindex:- def test_reindex(self, test_dir_uri):- reindex_pack = f"{test_dir_uri}/reindex_{uuid.uuid4().hex[:6]}"+ def test_reindex(self):+ reindex_pack = f"viking://~/resources/reindex_{uuid.uuid4().hex[:6]}"with tempfile.NamedTemporaryFile(suffix=".txt", delete=False, mode="w") as f:f.write("# Reindex Test\n\nThis is an independent resource for reindex testing.")temp_path = f.nametry:- r = ov_add_resource(temp_path, reindex_pack)- assert r["exit_code"] == 0, f"add-resource for reindex failed: {r['stderr'][:300]}"+ try:+ r = ov_add_resource(temp_path, reindex_pack)+ assert r["exit_code"] == 0, f"add-resource for reindex failed: {r['stderr'][:300]}"+ finally:+ os.unlink(temp_path)++ r = ov_reindex(reindex_pack)+ assert r["exit_code"] == 0, (+ f"ov reindex should exit 0, got {r['exit_code']}: {r['stderr'][:300]}"+ )+ data = r["json"]+ assert data is not None and data.get("ok") is True, "Expected ok=true"finally:- os.unlink(temp_path)-- r = ov_reindex(reindex_pack)- assert r["exit_code"] == 0, (- f"ov reindex should exit 0, got {r['exit_code']}: {r['stderr'][:300]}"- )- data = r["json"]- assert data is not None and data.get("ok") is True, "Expected ok=true"+ ov_rm(reindex_pack)diff --git a/tests/misc/test_vikingfs_find_without_rerank.py b/tests/misc/test_vikingfs_find_without_rerank.pyindex c250aaa46..9453a3bd3 100644--- a/tests/misc/test_vikingfs_find_without_rerank.py+++ b/tests/misc/test_vikingfs_find_without_rerank.py@@ -3,7 +3,7 @@"""Regression test for VikingFS.find without rerank configuration."""import contextvars-from unittest.mock import MagicMock+from unittest.mock import AsyncMock, MagicMockimport pytest@@ -24,8 +24,9 @@ def _make_viking_fs() -> VikingFS:fs.rerank_config = Nonefs.retrieval_config = Nonefs.vector_store = MagicMock(name="vector_store")+ fs.acl_manager = Nonefs._bound_ctx = contextvars.ContextVar("vikingfs_bound_ctx_test", default=None)- fs._ensure_access = MagicMock()+ fs._ensure_access = AsyncMock()fs._get_vector_store = MagicMock(return_value=fs.vector_store)fs._get_embedder = MagicMock(return_value=fs.query_embedder)fs._ctx_or_default = MagicMock(return_value=_ctx())diff --git a/tests/misc/test_vikingfs_uri_guard.py b/tests/misc/test_vikingfs_uri_guard.pyindex e97d48f3f..5dd2ec144 100644--- a/tests/misc/test_vikingfs_uri_guard.py+++ b/tests/misc/test_vikingfs_uri_guard.py@@ -23,6 +23,7 @@ def _make_viking_fs() -> VikingFS:fs.rerank_config = Nonefs.grep_config = Nonefs.vector_store = None+ fs.acl_manager = Nonefs._encryptor = Nonefs._bound_ctx = contextvars.ContextVar("vikingfs_bound_ctx_test", default=None)return fs@@ -85,11 +86,13 @@ class TestVikingFSURITraversalGuard:fs.agfs.read.assert_not_called()@pytest.mark.asyncio- async def test_write_rejects_traversal_before_agfs_write(self) -> None:+ async def test_write_rejects_unauthorized_paths_before_agfs_write(self) -> None:fs = _make_viking_fs()with pytest.raises(PermissionDeniedError, match="Unsafe URI"):await fs.write("viking://resources/../../_system/accounts.json", "pwned")+ with pytest.raises(PermissionDeniedError, match="requires an administrator"):+ await fs.write("viking://", "pwned", ctx=_user_ctx())fs.agfs.write.assert_not_called()@@ -309,7 +312,7 @@ class TestVikingFSURITraversalGuard:async def test_grep_propagates_agfs_errors_instead_of_falling_back(self) -> None:fs = _make_viking_fs()fs._encryptor = None- fs._ensure_access = MagicMock()+ fs._ensure_access = AsyncMock()fs._grep_with_agfs = AsyncMock(side_effect=AGFSInvalidOperationError("invalid regex"))fs._grep_encrypted = AsyncMock(return_value={"matches": [], "count": 0, "match_count": 0, "files_scanned": 0}@@ -326,7 +329,7 @@ class TestVikingFSURITraversalGuard:"""Query-root-relative grep matches should be reconstructed into the final Viking URI."""fs = _make_viking_fs()fs._encryptor = None- fs._ensure_access = MagicMock()+ fs._ensure_access = AsyncMock()fs.agfs.grep = AsyncMock(return_value={"matches": [@@ -352,7 +355,7 @@ class TestVikingFSURITraversalGuard:"""A '.' grep match should resolve back to the queried Viking URI itself."""fs = _make_viking_fs()fs._encryptor = None- fs._ensure_access = MagicMock()+ fs._ensure_access = AsyncMock()fs.agfs.grep = AsyncMock(return_value={"matches": [diff --git a/tests/parse/test_feishu_parser_api.py b/tests/parse/test_feishu_parser_api.pyindex 76b36fc94..2751d64e2 100644--- a/tests/parse/test_feishu_parser_api.py+++ b/tests/parse/test_feishu_parser_api.py@@ -385,6 +385,7 @@ def test_add_resource_message_round_trips_internal_fields():account_id="account-1",user_id="user-1",role="user",+ bypass_acl=True,defer_target_resolution=True,understanding_response_id="response-1",internal_task=True,@@ -394,6 +395,7 @@ def test_add_resource_message_round_trips_internal_fields():assert restored.args == {}assert "feishu_access_token" not in json.dumps(restored.to_dict())+ assert restored.bypass_acl is Trueassert restored.defer_target_resolution is Trueassert restored.understanding_response_id == "response-1"assert restored.job_phase is AddResourcePhase.SOURCE@@ -688,6 +690,8 @@ async def test_uat_producer_cancellation_respects_queue_ownership(viking_fs=SimpleNamespace(_uri_to_path=lambda _uri, ctx: "/resources/fixed",_async_agfs=agfs,+ exists=AsyncMock(return_value=False),+ _ensure_access=AsyncMock(),),resource_processor=resource_processor,skill_processor=SimpleNamespace(),@@ -955,6 +959,7 @@ async def test_add_resource_processor_persists_final_uri_and_cleans_staged_sourcaccount_id="account-1",user_id="user-1",role="user",+ bypass_acl=True,telemetry_id=telemetry_id,defer_target_resolution=True,internal_task=True,@@ -977,6 +982,7 @@ async def test_add_resource_processor_persists_final_uri_and_cleans_staged_sourcdata[TASK_WORK_ID_FIELD] = "work-1"await processor._process(msg, data)+ assert service.execute_add_resource_job.await_args.kwargs["ctx"].bypass_acl is Truetask_tracker.create.assert_awaited_once_with("add_resource",resource_id=None,diff --git a/tests/resource/test_watch_scheduler.py b/tests/resource/test_watch_scheduler.pyindex 869e3580d..a2f75c928 100644--- a/tests/resource/test_watch_scheduler.py+++ b/tests/resource/test_watch_scheduler.py@@ -6,6 +6,7 @@ import pytestfrom openviking.resource.uri_mutation_coordinator import UriMutationCoordinatorfrom openviking.resource.watch_manager import WatchManagerfrom openviking.resource.watch_scheduler import WatchScheduler+from openviking.server.identity import Rolefrom openviking.service.resource_service import ResourceService@@ -162,3 +163,5 @@ class TestWatchSchedulerResourceExistence:assert resource_service.calls[0]["to"] == new_uriassert resource_service.calls[0]["processing_mode"] == "vectors_only"assert resource_service.calls[0]["enforce_public_remote_targets"] is True+ assert resource_service.calls[0]["ctx"].role == Role.USER+ assert resource_service.calls[0]["ctx"].bypass_acl is Truediff --git a/tests/retrieve/test_hierarchical_retriever_rerank.py b/tests/retrieve/test_hierarchical_retriever_rerank.pyindex 5d695b19a..b2ab7675f 100644--- a/tests/retrieve/test_hierarchical_retriever_rerank.py+++ b/tests/retrieve/test_hierarchical_retriever_rerank.py@@ -51,6 +51,7 @@ class DummyEmbedder:class DummyStorage:def __init__(self) -> None:self.collection_name = "context"+ self.acl_manager = Noneself.search_calls = []self.child_search_calls = []@@ -365,8 +366,18 @@ async def test_retrieve_falls_back_to_vector_scores_when_rerank_returns_none(monlambda config: fake_client,)+ storage = QuickSearchStorage([+ _result("viking://resources/a/deep-a.md", 0.2, abstract="deep A"),+ _result("viking://resources/b/deep-b.md", 0.8, abstract="deep B"),+ ])+ storage.acl_manager = object()++ async def no_hierarchical_children(*_args, **_kwargs):+ return []++ storage.search_children_in_tenant = no_hierarchical_childrenretriever = HierarchicalRetriever(- storage=DummyStorage(),+ storage=storage,embedder=DummyEmbedder(),rerank_config=_config(),)@@ -374,9 +385,10 @@ async def test_retrieve_falls_back_to_vector_scores_when_rerank_returns_none(monresult = await retriever.retrieve(_query(), ctx=_ctx(), limit=2, mode=RetrieverMode.THINKING)assert [ctx.uri for ctx in result.matched_contexts] == [- "viking://resources/file-b",- "viking://resources/file-a",+ "viking://resources/b/deep-b.md",+ "viking://resources/a/deep-a.md",]+ assert [call["level"] for call in storage.search_calls] == [[0, 1], [2]]assert fake_client.callsdiff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.pyindex 324b93f28..a0c8905fa 100644--- a/tests/server/test_admin_api.py+++ b/tests/server/test_admin_api.py@@ -93,6 +93,9 @@ class _FakeVikingFS:raise FileNotFoundError(uri)return self.files[uri]+ async def _ensure_access(self, uri, ctx, *, action):+ return None+async def write_file(self, uri, content, **_kwargs):self.writes.append(uri)self.files[uri] = contentdiff --git a/tests/server/test_agent_evolution_global_setting.py b/tests/server/test_agent_evolution_global_setting.pyindex 4f15ca3ea..234c5bfc3 100644--- a/tests/server/test_agent_evolution_global_setting.py+++ b/tests/server/test_agent_evolution_global_setting.py@@ -12,6 +12,7 @@ import pytest_asynciofrom openviking.pyagfs import AGFSNotFoundErrorfrom openviking.server.account_settings import (AccountAgentEvolutionSettings,+ AccountResourceAclSettings,AccountSettingsPatch,account_settings_backup_path,account_settings_path,@@ -209,18 +210,32 @@ async def test_account_settings_admin_api_reads_and_updates_effective_value(assert initial.status_code == 200, initial.textassert initial.json()["result"] == {"account_id": "default",- "settings": {"agent_evolution": {"enabled": False}},+ "settings": {+ "agent_evolution": {"enabled": False},+ "resource_acl": {"auto_protect_new_content": False},+ },"overrides": {},}updated = await client.patch("/api/v1/admin/accounts/default/settings",- json={"agent_evolution": {"enabled": True}},+ json={+ "agent_evolution": {"enabled": True},+ "resource_acl": {"auto_protect_new_content": True},+ },)assert updated.status_code == 200, updated.textassert updated.json()["result"]["settings"]["agent_evolution"]["enabled"] is True- assert updated.json()["result"]["overrides"] == {"agent_evolution": {"enabled": True}}- assert (await read_account_settings(service.viking_fs, "default")).agent_evolution.enabled+ assert updated.json()["result"]["settings"]["resource_acl"] == {+ "auto_protect_new_content": True+ }+ assert updated.json()["result"]["overrides"] == {+ "agent_evolution": {"enabled": True},+ "resource_acl": {"auto_protect_new_content": True},+ }+ settings = await read_account_settings(service.viking_fs, "default")+ assert settings.agent_evolution.enabled+ assert settings.resource_acl == AccountResourceAclSettings(auto_protect_new_content=True)async def test_account_settings_admin_api_rejects_non_allowlisted_fields(diff --git a/tests/server/test_api_key_manager.py b/tests/server/test_api_key_manager.pyindex 9a3994718..cba8e478d 100644--- a/tests/server/test_api_key_manager.py+++ b/tests/server/test_api_key_manager.py@@ -455,15 +455,21 @@ async def test_get_accounts_pagination_and_ordering(manager: APIKeyManager):assert manager.get_accounts(name_filter=f"{prefix}*", limit=2, page=3) == []-async def test_persistence_across_reload(manager_service):- """Keys should survive manager reload from AGFS."""+async def test_user_and_group_persistence_across_reload(manager_service):+ """Reload preserves keys/groups, while user deletion removes membership."""mgr1 = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)await mgr1.load()acct = _uid()key = await mgr1.create_account(acct, "alice")+ await mgr1.register_user(acct, "bob")+ created_group = await mgr1.create_group(acct, "engineering")+ assert created_group == {"group_id": "engineering", "member_count": 0}+ group_id = created_group["group_id"]+ assert await mgr1.add_group_member(acct, group_id, "bob") is True+ assert await mgr1.add_group_member(acct, group_id, "bob") is True+ assert mgr1._accounts[acct].groups == {"engineering": {"members": ["bob"]}}- # Create new manager instance and reloadmgr2 = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)await mgr2.load()@@ -471,6 +477,21 @@ async def test_persistence_across_reload(manager_service):assert identity.account_id == acctassert identity.user_id == "alice"assert identity.role == Role.ADMIN+ assert mgr2.get_user_group_ids(acct, "bob") == (group_id,)++ await mgr2.begin_user_deletion(+ acct,+ "bob",+ task_id="delete-bob",+ owner_account_id=acct,+ owner_user_id="alice",+ )+ await mgr2.finish_user_deletion(acct, "bob", "delete-bob")++ mgr3 = APIKeyManager(root_key=ROOT_KEY, viking_fs=manager_service.viking_fs)+ await mgr3.load()+ assert mgr3.get_user_group_ids(acct, "bob") == ()+ assert mgr3.get_group_members(acct, group_id) == []async def test_legacy_account_without_settings_loads_without_namespace_settings(manager_service):diff --git a/tests/server/test_api_snapshot.py b/tests/server/test_api_snapshot.pyindex 921ea82b1..c0a3bb9ec 100644--- a/tests/server/test_api_snapshot.py+++ b/tests/server/test_api_snapshot.py@@ -2,6 +2,7 @@# SPDX-License-Identifier: AGPL-3.0"""End-to-end tests for /api/v1/snapshot/*."""+import asynciofrom types import SimpleNamespacefrom unittest.mock import AsyncMock@@ -9,11 +10,16 @@ import httpximport pytestimport pytest_asyncio-from openviking.server.auth import get_request_context+import openviking.service.reindex_executor as reindex_modfrom openviking.server.app import create_app+from openviking.server.auth import get_request_contextfrom openviking.server.config import ServerConfigfrom openviking.server.identity import RequestContext, Role-from openviking_cli.exceptions import InvalidArgumentError, InvalidURIError+from openviking_cli.exceptions import (+ InvalidArgumentError,+ InvalidURIError,+ PermissionDeniedError,+)from openviking_cli.session.user_id import UserIdentifierpytestmark = pytest.mark.asyncio@@ -186,24 +192,113 @@ async def client_with_resource_and_blob(client_with_resource, service):yield client, commit_oid, blob_uri, expected_bytes-async def test_restore_dry_run_does_not_mutate(client_with_resource):- client, _root = client_with_resource- v1 = (await client.post("/api/v1/snapshot/commit", json={"message": "v1"})).json()["result"]-- resp = await client.post(- "/api/v1/snapshot/restore",- json={- "project_dir": "viking://resources",- "source_commit": v1["commit_oid"],- "dry_run": True,+async def test_restore_acl_and_reindex_identity(client_with_resource, service, monkeypatch):+ _, _root = client_with_resource+ admin = RequestContext(user=service.user, role=Role.ADMIN)+ writer = RequestContext(+ user=UserIdentifier(admin.account_id, "snapshot_writer"),+ role=Role.USER,+ group_ids=("engineering",),+ actor_peer_id="snapshot-peer",+ )+ reader = RequestContext(+ user=UserIdentifier(admin.account_id, "snapshot_reader"),+ role=Role.USER,+ )+ root = "viking://resources/snapshot_acl_restore"+ file_uri = f"{root}/document.md"+ extra_uri = f"{root}/remove.md"++ await service.fs.mkdir(root, ctx=admin)+ assert await service.vikingdb_manager.upsert(+ {+ "id": "snapshot-acl-restore-root",+ "uri": root,+ "account_id": admin.account_id,+ "context_type": "resource",+ "level": 0,+ "vector": [0.1] * service.vikingdb_manager.vector_dim,},+ ctx=admin,)- assert resp.status_code == 200, resp.text- body = resp.json()- assert body["status"] == "ok"- result = body["result"]- # Per VikingFS.restore contract, dry_run responses carry 'diff'.- assert "diff" in result or result.get("result") == "noop"+ await service.fs.set_acl(+ root,+ [+ {"principal": "user:snapshot_writer", "level": "write"},+ {"principal": "user:snapshot_reader", "level": "read"},+ ],+ ctx=admin,+ )+ await service.fs.write(file_uri, content="v1", mode="create", wait=True, ctx=admin)+ v1 = await service.fs.commit(message="acl restore v1", paths=[root], ctx=writer)++ assert await service.fs.show(v1["commit_oid"], path=file_uri, ctx=reader)+ assert await service.fs.log(paths=[root], ctx=reader)+ with pytest.raises(PermissionDeniedError):+ await service.fs.commit(message="reader cannot commit", paths=[root], ctx=reader)++ await service.fs.write(file_uri, content="v2", mode="replace", wait=True, ctx=writer)+ await service.fs.commit(message="acl restore v2", paths=[root], ctx=writer)++ with pytest.raises(PermissionDeniedError):+ await service.fs.restore(+ project_dir=root,+ source_commit=v1["commit_oid"],+ dry_run=True,+ ctx=reader,+ )++ write_plan = await service.fs.restore(+ project_dir=root,+ source_commit=v1["commit_oid"],+ dry_run=True,+ ctx=writer,+ )+ assert [item["path"] for item in write_plan["diff"]["to_write"]] == ["document.md"]++ await service.fs.write(extra_uri, content="remove", mode="create", wait=True, ctx=admin)+ await service.fs.commit(message="acl restore delete", paths=[root], ctx=admin)+ delete_plan = await service.fs.restore(+ project_dir=root,+ source_commit=v1["commit_oid"],+ dry_run=True,+ ctx=writer,+ )+ assert delete_plan["diff"]["to_delete"] == ["remove.md"]+ assert await service.fs.read(file_uri, ctx=writer) == "v2"++ reindex_contexts: list[RequestContext] = []++ class _SpyExecutor:+ async def execute(self, *, uri, mode, wait, ctx):+ reindex_contexts.append(ctx)+ return {"ok": True}++ async def reindex_directory_marker(self, *, dir_uri, level, ctx):+ reindex_contexts.append(ctx)++ async def delete_uri_level(self, *, uri, level, ctx):+ reindex_contexts.append(ctx)+ return 0++ monkeypatch.setattr(reindex_mod, "get_reindex_executor", lambda: _SpyExecutor())+ result = await service.fs.restore(+ project_dir=root,+ source_commit=v1["commit_oid"],+ ctx=writer,+ )+ assert result["result"] == "applied"++ for _ in range(100):+ if reindex_contexts:+ break+ await asyncio.sleep(0.02)++ assert reindex_contexts+ assert all(ctx.role == Role.USER for ctx in reindex_contexts)+ assert all(ctx.group_ids == ("engineering",) for ctx in reindex_contexts)+ assert all(ctx.actor_peer_id == "snapshot-peer" for ctx in reindex_contexts)+ assert all(ctx.bypass_acl for ctx in reindex_contexts)async def test_show_commit_metadata(client_with_resource):@@ -536,10 +631,6 @@ async def test_restore_apply_triggers_reindex_hook(client_with_resource_and_blob"""Verify the HTTP restore path actually invokes the vector-reindexscheduler — protects the chain router -> viking_fs.restore -> _schedule_vector_rebuild."""- from openviking.server.identity import RequestContext, Role- from openviking_cli.session.user_id import UserIdentifier- import openviking.service.reindex_executor as reindex_mod-client, c1_oid, blob_uri, _v1 = client_with_resource_and_blobctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)@@ -583,10 +674,6 @@ async def test_restore_delete_removes_orphaned_vectors(client_with_resource_and_viking_fs.restore must route deleted source paths to the executor'slevel-precise delete (DETAIL)."""- from openviking.server.identity import RequestContext, Role- from openviking_cli.session.user_id import UserIdentifier- import openviking.service.reindex_executor as reindex_mod-client, c1_oid, _blob_uri, _v1 = client_with_resource_and_blobctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)diff --git a/tests/server/test_content_batch_write.py b/tests/server/test_content_batch_write.pyindex d1d6f9beb..749b8a164 100644--- a/tests/server/test_content_batch_write.py+++ b/tests/server/test_content_batch_write.py@@ -40,8 +40,8 @@ class _VFS:self.writes = []self._async_agfs = _PathLockClient()- def _ensure_mutable_access(self, uri, ctx):- del uri, ctx+ async def _ensure_access(self, uri, ctx, *, action):+ del uri, ctx, actiondef _uri_to_path(self, uri, ctx=None):del ctxdiff --git a/tests/server/test_content_write_service.py b/tests/server/test_content_write_service.pyindex 306791117..d3e5bfd78 100644--- a/tests/server/test_content_write_service.py+++ b/tests/server/test_content_write_service.py@@ -8,6 +8,11 @@ from unittest.mock import AsyncMockimport pytest+from openviking.server.account_settings import (+ AccountResourceAclSettings,+ AccountSettingsPatch,+ update_account_settings,+)from openviking.server.identity import RequestContext, Rolefrom openviking.session.memory.dataclass import MemoryFilefrom openviking.session.memory.utils import MemoryFileUtils@@ -104,17 +109,108 @@ async def test_memory_replace_preserves_metadata(service):@pytest.mark.asyncio-async def test_resource_append_is_plain_concatenation(service):- """Appending to a non-memory file must not inject a MEMORY_FIELDS trailer- or strip the existing trailing newline (memory namespaces only)."""- ctx = RequestContext(user=service.user, role=Role.USER)+async def test_shared_resource_creation_inherits_acl_and_preserves_plain_append(+ service, sample_markdown_file+):+ """New shared content grants creator manage without changing file content."""+ creator = RequestContext(+ user=service.user,+ role=Role.USER,+ group_ids=("writers",),+ )+ admin = RequestContext(user=service.user, role=Role.ADMIN)+ reader = RequestContext(+ user=UserIdentifier(admin.account_id, "reader"),+ role=Role.USER,+ group_ids=("readers",),+ )+ outsider = RequestContext(+ user=UserIdentifier(admin.account_id, "outsider"),+ role=Role.USER,+ )+ parent_uri = "viking://resources/append_plain"+ auto_protected_dir = "viking://resources/auto_protected"uri = "viking://resources/append_plain/journal.md"- await service.fs.write(uri, content="line1\n", ctx=ctx, mode="create")- await service.fs.write(uri, content="line2\n", ctx=ctx, mode="append")+ await update_account_settings(+ service.viking_fs,+ creator.account_id,+ AccountSettingsPatch(+ resource_acl=AccountResourceAclSettings(auto_protect_new_content=True)+ ),+ )+ await service.fs.mkdir(auto_protected_dir, ctx=creator)+ await service.resources.wait_processed()+ auto_protected_acl = await service.fs.get_acl(auto_protected_dir, ctx=creator)+ creator_entry = {+ "principal": f"user:{creator.user.user_id}",+ "level": "manage",+ }+ assert auto_protected_acl["direct_entries"] == [creator_entry]++ await service.viking_fs.mkdir(parent_uri, ctx=admin)+ assert await service.vikingdb_manager.upsert(+ {+ "id": "append-plain-parent",+ "uri": parent_uri,+ "account_id": admin.account_id,+ "context_type": "resource",+ "level": 0,+ "vector": [0.1] * service.vikingdb_manager.vector_dim,+ },+ ctx=admin,+ )+ await service.fs.set_acl(+ parent_uri,+ [+ {"principal": "group:readers", "level": "read"},+ {"principal": "group:writers", "level": "write"},+ ],+ ctx=admin,+ )- stored = await service.viking_fs.read_file(uri, ctx=ctx)+ await service.fs.write(uri, content="line1\n", ctx=creator, mode="create", wait=True)+ inherited_entries = [+ {"principal": "group:readers", "level": "read"},+ {"principal": "group:writers", "level": "write"},+ ]+ created_acl = await service.fs.get_acl(uri, ctx=creator)+ assert created_acl["direct_entries"] == [creator_entry]+ assert created_acl["inherited_entries"] == inherited_entries++ imported = await service.resources.add_resource(+ path=str(sample_markdown_file),+ parent=parent_uri,+ ctx=creator,+ reason="ACL import",+ wait=True,+ )+ import_root = imported["root_uri"]+ imported_acl = await service.fs.get_acl(import_root, ctx=creator)+ assert imported_acl["direct_entries"] == [creator_entry]+ assert imported_acl["inherited_entries"] == inherited_entries+ children = await service.fs.ls(import_root, ctx=creator, simple=True)+ child_acl = await service.fs.get_acl(children[0], ctx=creator)+ assert child_acl["direct_entries"] == []+ assert child_acl["inherited_entries"] == [*inherited_entries, creator_entry]++ await service.fs.write(uri, content="line2\n", ctx=creator, mode="append", wait=True)++ stored = await service.viking_fs.read_file(uri, ctx=reader)assert stored == "line1\nline2\n"+ with pytest.raises(PermissionDeniedError):+ await service.fs.write(uri, content="denied", ctx=reader)+ with pytest.raises(PermissionDeniedError):+ await service.viking_fs.read_file(uri, ctx=outsider)++ internal_ctx = RequestContext(+ user=outsider.user,+ role=outsider.role,+ bypass_acl=True,+ )+ assert await service.viking_fs.read_file(uri, ctx=internal_ctx) == stored+ with pytest.raises(PermissionDeniedError):+ await service.fs.get_acl(uri, ctx=internal_ctx)@pytest.mark.asyncio@@ -373,8 +469,11 @@ class _FakeVikingFS:del ctxreturn f"/fake/{uri.replace('://', '/').strip('/')}"- def _ensure_mutable_access(self, uri: str, ctx):- del uri, ctx+ async def _ensure_access(self, uri: str, ctx, *, action):+ del uri, ctx, action++ async def _ensure_access_many(self, uris, ctx, *, action):+ del uris, ctx, actionasync def delete_temp(self, temp_uri: str, ctx=None):del ctx@@ -786,8 +885,8 @@ class _FakeVikingFSForCreate:del ctxreturn f"/fake/{uri.replace('://', '/').strip('/')}"- def _ensure_mutable_access(self, uri: str, ctx):- del uri, ctx+ async def _ensure_access(self, uri: str, ctx, *, action):+ del uri, ctx, actionasync def delete_temp(self, temp_uri: str, ctx=None):del ctxdiff --git a/tests/server/test_http_client_sdk.py b/tests/server/test_http_client_sdk.pyindex 5a6324ee6..4a4aea2f6 100644--- a/tests/server/test_http_client_sdk.py+++ b/tests/server/test_http_client_sdk.py@@ -9,8 +9,10 @@ import httpximport pytestimport pytest_asyncio+from openviking.server.identity import RequestContext, Rolefrom openviking_cli.client.http import AsyncHTTPClientfrom openviking_cli.exceptions import ConflictError, ProcessingError+from openviking_cli.session.user_id import UserIdentifierfrom tests.server.conftest import SAMPLE_MD_CONTENT, TEST_TMP_DIRfrom tests.server.ovpack_test_helpers import build_ovpack_bytes@@ -49,7 +51,7 @@ async def test_sdk_health(http_client):async def test_sdk_add_resource(http_client):- client, _ = http_client+ client, service = http_clientf = TEST_TMP_DIR / "sdk_sample.md"f.parent.mkdir(parents=True, exist_ok=True)f.write_text(SAMPLE_MD_CONTENT)@@ -59,6 +61,13 @@ async def test_sdk_add_resource(http_client):assert "telemetry" not in resultassert "root_uri" in resultassert result["root_uri"].startswith("viking://")+ creator = RequestContext(+ user=UserIdentifier("sdk_test_account", "sdk_test_user"),+ role=Role.ADMIN,+ )+ acl = await service.fs.get_acl(result["root_uri"], ctx=creator)+ assert acl["acl_enabled"] is False+ assert acl["direct_entries"] == []async def test_sdk_add_resource_raises_processing_error_for_business_error(diff --git a/tests/server/test_watch_task_acl.py b/tests/server/test_watch_task_acl.pyindex 67446f3c1..85f1eccca 100644--- a/tests/server/test_watch_task_acl.py+++ b/tests/server/test_watch_task_acl.py@@ -32,13 +32,14 @@ def user_ctx() -> RequestContext:@pytest.fixturedef bare_viking_fs() -> VikingFS:fs = object.__new__(VikingFS)+ fs.acl_manager = Nonefs._bound_ctx = contextvars.ContextVar("vikingfs_bound_ctx", default=None)return fsclass _NoWriteVikingFS:- def _ensure_mutable_access(self, uri, ctx):- raise AssertionError(f"mutable access should not be reached for {uri}")+ async def _ensure_access(self, uri, ctx, *, action):+ raise AssertionError(f"write access should not be reached for {uri}")@pytest.mark.parametrize(@@ -49,12 +50,12 @@ class _NoWriteVikingFS:WATCH_TASK_STORAGE_TMP_URI,],)-def test_watch_task_control_files_are_root_only(bare_viking_fs, root_ctx, user_ctx, uri):- assert bare_viking_fs._is_accessible(uri, root_ctx) is True- assert bare_viking_fs._is_accessible(uri, user_ctx) is False-+async def test_watch_task_control_files_are_root_only(bare_viking_fs, root_ctx, user_ctx, uri):+ bare_viking_fs.acl_manager = object()+ await bare_viking_fs._ensure_access(uri, root_ctx)with pytest.raises(PermissionDeniedError):- bare_viking_fs._ensure_access(uri, user_ctx)+ await bare_viking_fs._ensure_access(uri, user_ctx)@pytest.mark.asynciodiff --git a/tests/service/test_resource_service_connector.py b/tests/service/test_resource_service_connector.pyindex 021ef6062..3867109ba 100644--- a/tests/service/test_resource_service_connector.py+++ b/tests/service/test_resource_service_connector.py@@ -1510,6 +1510,7 @@ async def test_native_git_watch_refresh_queues_with_restored_task_auth(service._enqueue_add_resource_job = AsyncMock(return_value=SimpleNamespace(task_id="task-refresh"))+ ctx.bypass_acl = Trueresult = await service.refresh_resource(path="https://git.example/org/private.git",@@ -1522,6 +1523,8 @@ async def test_native_git_watch_refresh_queues_with_restored_task_auth(assert result["task_id"] == "task-refresh"message = service._enqueue_add_resource_job.await_args.args[0]assert message.skip_watch_management is True+ assert message.bypass_acl is True+ assert AddResourceMsg.from_dict(message.to_dict()).bypass_acl is Trueassert "secret-token" not in json.dumps(message.to_dict())assert service._enqueue_add_resource_job.await_args.kwargs["task_auth"] == {"provider": "git_http_basic",diff --git a/tests/storage/test_collection_schemas.py b/tests/storage/test_collection_schemas.pyindex b0a0d09cc..4e6355d09 100644--- a/tests/storage/test_collection_schemas.py+++ b/tests/storage/test_collection_schemas.py@@ -13,6 +13,7 @@ import requestsfrom openviking.models.embedder.base import DenseEmbedderBase, EmbedResultfrom openviking.server.identity import RequestContext, Role, UserIdentifierfrom openviking.service.resource_service import ResourceService+from openviking.storage.acl import ACL_CONTEXT_FIELDS, ACL_GRANT_FIELDSfrom openviking.storage.collection_schemas import (CollectionSchemas,TextEmbeddingHandler,@@ -184,8 +185,9 @@ async def test_init_context_collection_writes_embedding_metadata(monkeypatch):@pytest.mark.asyncio-async def test_init_context_collection_backfills_metadata_for_empty_legacy_collection(monkeypatch):+async def test_init_context_collection_migrates_local_legacy_schema(monkeypatch):updates = []+ schema_updates = []class _FakeStorage:async def create_collection(self, name, schema):@@ -193,7 +195,20 @@ async def test_init_context_collection_backfills_metadata_for_empty_legacy_collereturn Falseasync def get_collection_meta(self):- return {"Description": "Unified context collection"}+ schema = CollectionSchemas.context_collection("context", 2)+ return {+ "Description": "Unified context collection",+ "Fields": [+ field+ for field in schema["Fields"]+ if field["FieldName"] not in ACL_CONTEXT_FIELDS+ ],+ "ScalarIndex": [+ field+ for field in schema["ScalarIndex"]+ if field not in ACL_CONTEXT_FIELDS+ ],+ }async def count(self):return 0@@ -202,7 +217,10 @@ async def test_init_context_collection_backfills_metadata_for_empty_legacy_colleupdates.append(description)return True- config = _DummyConfig(_DummyEmbedder())+ async def update_collection_schema(self, fields, scalar_index):+ schema_updates.append((fields, scalar_index))++ config = _DummyConfig(_DummyEmbedder(), backend="local")monkeypatch.setattr("openviking_cli.utils.config.get_openviking_config",lambda: config,@@ -212,7 +230,13 @@ async def test_init_context_collection_backfills_metadata_for_empty_legacy_colleassert created is Falseassert len(updates) == 1+ assert len(schema_updates) == 1assert '"provider": "local"' in updates[0]+ fields, scalar_index = schema_updates[0]+ fields_by_name = {field["FieldName"]: field for field in fields}+ assert fields_by_name["acl_enabled"]["FieldType"] == "bool"+ assert all(fields_by_name[field]["FieldType"] == "list<string>" for field in ACL_GRANT_FIELDS)+ assert ACL_CONTEXT_FIELDS <= set(scalar_index)@pytest.mark.asynciodiff --git a/tests/storage/test_semantic_parent_bubbling.py b/tests/storage/test_semantic_parent_bubbling.pyindex 9aca6bdcb..778fd57ec 100644--- a/tests/storage/test_semantic_parent_bubbling.py+++ b/tests/storage/test_semantic_parent_bubbling.py@@ -6,6 +6,7 @@ from unittest.mock import AsyncMockimport pytest+from openviking.server.identity import Rolefrom openviking.storage.queuefs.semantic_msg import SemanticMsgfrom openviking.storage.queuefs.semantic_ops.freshness_policy import (FreshnessAction,@@ -37,13 +38,20 @@ async def test_unchanged_l0_does_not_mark_or_enqueue_parent(monkeypatch):"openviking.storage.queuefs.get_queue_manager", get_queue_manager)- msg = SemanticMsg(uri="viking://resources/root/child", context_type="resource")+ msg = SemanticMsg(+ uri="viking://resources/root/child",+ context_type="resource",+ role=str(Role.USER),+ generation_trigger="resource_ingest",+ )await SemanticProcessor()._enqueue_parent_refresh(msg, msg.uri, l0_body_changed=False)assert plan.await_args.kwargs["l0_body_changed"] is Falseassert plan.await_args.kwargs["force_refresh"] is False+ assert plan.await_args.kwargs["ctx"].bypass_acl is True+ assert plan.await_args.kwargs["ctx"].role == Role.USERget_queue_manager.assert_not_called()diff --git a/tests/storage/test_semantic_processor_identity.py b/tests/storage/test_semantic_processor_identity.pyindex 2e8b766b1..f68cddc34 100644--- a/tests/storage/test_semantic_processor_identity.py+++ b/tests/storage/test_semantic_processor_identity.py@@ -1,17 +1,18 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: Apache-2.0-"""Tests for SemanticProcessor identity reconstruction."""+"""Tests for SemanticProcessor internal context reconstruction."""from openviking.storage.queuefs.semantic_msg import SemanticMsgfrom openviking.storage.queuefs.semantic_processor import SemanticProcessor-def test_ctx_from_semantic_msg_preserves_custom_role():+def test_ctx_from_semantic_msg_preserves_identity_and_enables_acl_bypass():msg = SemanticMsg(uri="viking://resources/doc",context_type="resource",account_id="acme",user_id="alice",+ group_ids=["reviewers"],role="reviewer",)@@ -19,16 +20,6 @@ def test_ctx_from_semantic_msg_preserves_custom_role():assert ctx.account_id == "acme"assert ctx.user.user_id == "alice"+ assert ctx.group_ids == ("reviewers",)assert str(ctx.role) == "reviewer"---def test_ctx_from_semantic_msg_defaults_empty_role_to_root():- msg = SemanticMsg(- uri="viking://resources/doc",- context_type="resource",- role="",- )-- ctx = SemanticProcessor._ctx_from_semantic_msg(msg)-- assert str(ctx.role) == "root"+ assert ctx.bypass_acl is Truediff --git a/tests/storage/test_semantic_processor_mv_vector_store.py b/tests/storage/test_semantic_processor_mv_vector_store.pyindex 389b66933..d0f950918 100644--- a/tests/storage/test_semantic_processor_mv_vector_store.py+++ b/tests/storage/test_semantic_processor_mv_vector_store.py@@ -1,4 +1,4 @@-from unittest.mock import AsyncMock+from unittest.mock import AsyncMock, callimport pytest@@ -11,6 +11,7 @@ from openviking_cli.session.user_id import UserIdentifierasync def test_mv_preserves_canonical_user_uris_for_vector_update(monkeypatch):ctx = RequestContext(user=UserIdentifier("acc", "default"), role=Role.ROOT)fs = VikingFS.__new__(VikingFS)+ fs.acl_manager = Nonefs._async_agfs = AsyncMock()fs._async_agfs.stat.return_value = {"isDir": False}fs._async_agfs.pathlock_acquire_batch.return_value = {"lease_ref": "lease-1"}@@ -33,16 +34,34 @@ async def test_mv_preserves_canonical_user_uris_for_vector_update(monkeypatch):@pytest.mark.asyncio-async def test_update_vector_store_uris_swallows_update_failure():+async def test_vector_uri_batch_rolls_back_completed_updates():ctx = RequestContext(user=UserIdentifier("acc", "default"), role=Role.ROOT)fs = VikingFS.__new__(VikingFS)fs.vector_store = AsyncMock()- fs.vector_store.update_uri_mapping.side_effect = RuntimeError("vector unavailable")+ fs.vector_store.update_uri_mapping.side_effect = [True, RuntimeError("failed"), True]- await fs._update_vector_store_uris(- ["viking://user/default/source.md"],- "viking://user/default/source.md",- "viking://user/default/target.md",- ctx=ctx,- )- fs.vector_store.update_uri_mapping.assert_awaited_once()+ with pytest.raises(RuntimeError, match="failed"):+ await fs._update_vector_store_uris(+ ["viking://resources/old/a.md", "viking://resources/old/b.md"],+ "viking://resources/old",+ "viking://resources/new",+ ctx=ctx,+ )++ assert fs.vector_store.update_uri_mapping.await_args_list == [+ call(+ ctx=ctx,+ uri="viking://resources/old/a.md",+ new_uri="viking://resources/new/a.md",+ ),+ call(+ ctx=ctx,+ uri="viking://resources/old/b.md",+ new_uri="viking://resources/new/b.md",+ ),+ call(+ ctx=ctx,+ uri="viking://resources/new/a.md",+ new_uri="viking://resources/old/a.md",+ ),+ ]diff --git a/tests/storage/test_viking_fs_git.py b/tests/storage/test_viking_fs_git.pyindex d8706c324..7a0e27873 100644--- a/tests/storage/test_viking_fs_git.py+++ b/tests/storage/test_viking_fs_git.py@@ -65,27 +65,24 @@ async def test_diff_reads_blobs_from_resolved_commit_oids():class MovingRefVikingFS:def __init__(self):- self._async_agfs = _RecordingDiffAGFS()- self.blob_refs = []+ self._async_agfs = _RecordingDiffAGFS(+ blobs={+ from_oid: b"old content\n",+ to_oid: b"new content\n",+ "base": b"moved base content\n",+ "main": b"moved main content\n",+ },+ ref_oids={"base": from_oid, "main": to_oid},+ )def _ctx_or_default(self, ctx):return ctx- def _ensure_access(self, uri, ctx):- return None+ async def _ensure_access(self, uri, ctx):+ pass- async def show(self, target_ref, *, path=None, ctx=None, max_blob_bytes=None):- if path is None:- return {"oid": from_oid if target_ref == "base" else to_oid}-- self.blob_refs.append(target_ref)- contents = {- from_oid: b"old content\n",- to_oid: b"new content\n",- "base": b"moved base content\n",- "main": b"moved main content\n",- }- return contents[target_ref]+ def _uri_to_tree_path(self, path, *, ctx):+ return path.removeprefix("viking://")vfs = MovingRefVikingFS()ctx = RequestContext(@@ -101,7 +98,7 @@ async def test_diff_reads_blobs_from_resolved_commit_oids():ctx=ctx,)- assert vfs.blob_refs == [from_oid, to_oid]+ assert vfs._async_agfs.blob_refs == [from_oid, to_oid]assert result["from_commit"] == from_oidassert result["to_commit"] == to_oidassert "-old content" in result["diff_text"]@@ -132,29 +129,42 @@ class _DiffVikingFS:def __init__(self, before: bytes, after: bytes):self._before = beforeself._after = after- self._async_agfs = _RecordingDiffAGFS()- self.blob_read_limits = []+ self._async_agfs = _RecordingDiffAGFS(blobs={"from": before, "to": after})+ self.blob_read_limits = self._async_agfs.blob_read_limitsself.access_checks = []def _ctx_or_default(self, ctx):return ctx- def _ensure_access(self, uri, ctx):+ async def _ensure_access(self, uri, ctx):self.access_checks.append((uri, ctx))- async def show(self, target_ref, *, path=None, ctx=None, max_blob_bytes=None):- if path is None:- return {"oid": target_ref}- self.blob_read_limits.append(max_blob_bytes)- return self._before if target_ref == "from" else self._after+ def _uri_to_tree_path(self, path, *, ctx):+ return path.removeprefix("viking://")class _RecordingDiffAGFS:- def __init__(self):+ def __init__(self, *, blobs=None, ref_oids=None):self.calls = []+ self.blobs = blobs or {}+ self.ref_oids = ref_oids or {}+ self.blob_errors = {}+ self.blob_refs = []+ self.blob_read_limits = []async def run(self, operation, **kwargs):self.calls.append((operation, kwargs))+ if operation == "git_show":+ target_ref = kwargs["target_ref"]+ if kwargs["path"] is None:+ return {"oid": self.ref_oids.get(target_ref, target_ref)}+ error = self.blob_errors.get(target_ref)+ if error is not None:+ raise error+ self.blob_refs.append(target_ref)+ self.blob_read_limits.append(kwargs.get("max_blob_bytes"))+ value = self.blobs[target_ref]+ return {"oid": target_ref, "size": len(value), "bytes": value}assert operation == "git_diff_text"before = kwargs["before"]after = kwargs["after"]@@ -215,6 +225,7 @@ async def test_diff_checks_access_before_reading_snapshot_content():role=Role.USER,)vfs = object.__new__(VikingFS)+ vfs.acl_manager = Noneshow_calls = []async def show(*args, **kwargs):@@ -291,7 +302,7 @@ async def test_diff_uses_bounded_native_diff_builder():ctx=_request_context(),)- assert vfs._async_agfs.calls == [+ assert vfs._async_agfs.calls[-1:] == [("git_diff_text",{@@ -311,16 +322,11 @@ async def test_diff_uses_bounded_native_diff_builder():async def test_diff_treats_only_missing_tree_path_as_absent():- class MissingPathVikingFS(_DiffVikingFS):- async def show(self, target_ref, *, path=None, ctx=None, max_blob_bytes=None):- if path is None:- return {"oid": target_ref}- if target_ref == "to":- raise AGFSPathNotFoundError("path not found in tree")- return self._before+ vfs = _DiffVikingFS(b"old\n", b"")+ vfs._async_agfs.blob_errors["to"] = AGFSPathNotFoundError("path not found in tree")result = await VikingFS.diff(- MissingPathVikingFS(b"old\n", b""),+ vfs,path="viking://user/user/memories/experiences/example.md",from_ref="from",to_ref="to",@@ -331,17 +337,12 @@ async def test_diff_treats_only_missing_tree_path_as_absent():async def test_diff_does_not_treat_missing_storage_object_as_absent():- class MissingObjectVikingFS(_DiffVikingFS):- async def show(self, target_ref, *, path=None, ctx=None, max_blob_bytes=None):- if path is None:- return {"oid": target_ref}- if target_ref == "to":- raise AGFSNotFoundError("object not found: deadbeef")- return self._before+ vfs = _DiffVikingFS(b"old\n", b"")+ vfs._async_agfs.blob_errors["to"] = AGFSNotFoundError("object not found: deadbeef")with pytest.raises(AGFSNotFoundError, match="object not found"):await VikingFS.diff(- MissingObjectVikingFS(b"old\n", b""),+ vfs,path="viking://user/user/memories/experiences/example.md",from_ref="from",to_ref="to",diff --git a/tests/storage/test_viking_fs_glob.py b/tests/storage/test_viking_fs_glob.pyindex 6ffe35d66..f103c53de 100644--- a/tests/storage/test_viking_fs_glob.py+++ b/tests/storage/test_viking_fs_glob.py@@ -166,7 +166,7 @@ async def test_glob_rejects_empty_pattern(fs):async def test_glob_checks_access_before_listing(monkeypatch, fs):called = False- def fake_ensure_access(uri, ctx):+ async def fake_ensure_access(uri, ctx):nonlocal calledcalled = Trueraise PermissionError(f"denied: {uri}")diff --git a/tests/storage/test_viking_fs_grep.py b/tests/storage/test_viking_fs_grep.pyindex d707d5b9e..249fa59f8 100644--- a/tests/storage/test_viking_fs_grep.py+++ b/tests/storage/test_viking_fs_grep.py@@ -2,6 +2,7 @@# SPDX-License-Identifier: AGPL-3.0import time+from unittest.mock import AsyncMockimport pytest@@ -152,7 +153,8 @@ async def test_grep_vikingdb_pushes_exclude_uri_to_filter(monkeypatch):fs = VikingFS(agfs=_DummyAgfs())vector_store = _DummyVectorStore()monkeypatch.setattr(fs, "_get_vector_store", lambda: vector_store)- monkeypatch.setattr(fs, "_ensure_access", lambda uri, ctx=None: None)++ monkeypatch.setattr(fs, "_ensure_access", AsyncMock())result = await fs._grep_vikingdb_then_fs(uri="viking://resources",@@ -187,7 +189,8 @@ async def test_grep_vikingdb_keeps_local_exclude_uri_guard(monkeypatch):])monkeypatch.setattr(fs, "_get_vector_store", lambda: vector_store)- monkeypatch.setattr(fs, "_ensure_access", lambda uri, ctx=None: None)++ monkeypatch.setattr(fs, "_ensure_access", AsyncMock())grep_in_files_calls = []diff --git a/tests/storage/test_viking_fs_tree.py b/tests/storage/test_viking_fs_tree.pyindex 36b940a88..3faaee73c 100644--- a/tests/storage/test_viking_fs_tree.py+++ b/tests/storage/test_viking_fs_tree.py@@ -470,8 +470,20 @@ async def test_tree_original_dfs_order(monkeypatch, fs):mode=0o644,is_dir=False,),+ make_entry("/local/test_account/resources/restricted", "restricted", is_dir=True),+ make_entry(+ "/local/test_account/resources/restricted/hidden.txt",+ "hidden.txt",+ is_dir=False,+ ),]patch_tree_env(monkeypatch, fs, entries)+ fs.acl_manager = object()++ async def fake_can_access_many(uris, _ctx):+ return {uri: "/restricted" not in uri for uri in uris}++ monkeypatch.setattr(fs, "_can_access_many", fake_can_access_many)result = await fs._tree_original("viking://resources", ctx=_default_ctx())assert result[0]["name"] == "sub"@@ -479,6 +491,14 @@ async def test_tree_original_dfs_order(monkeypatch, fs):assert result[0]["rel_path"] == "sub"assert result[1]["name"] == "file.txt"assert result[1]["rel_path"] == "sub/file.txt"+ assert result[2] == {+ "name": "restricted",+ "isDir": True,+ "rel_path": "restricted",+ "uri": "viking://resources/restricted",+ "access": "denied",+ }+ assert len(result) == 3# ── _tree_agent tests ──@@ -569,7 +589,14 @@ async def test_ls_agent_modtime_is_raw_utc_iso(monkeypatch, fs):"mode": 0o644,"modTime": "2026-06-11T00:30:17+08:00","isDir": False,- }+ },+ {+ "name": "restricted",+ "size": 4096,+ "mode": 0o755,+ "modTime": "2026-06-11T00:30:18+08:00",+ "isDir": True,+ },]monkeypatch.setattr(fs, "_uri_to_path", lambda _uri, **_kwargs: "/local/test_account/resources")@@ -578,6 +605,12 @@ async def test_ls_agent_modtime_is_raw_utc_iso(monkeypatch, fs):monkeypatch.setattr(fs, "_is_accessible", lambda _uri, _ctx: True)monkeypatch.setattr(fs, "_batch_fetch_abstracts", default_batch_fetch)monkeypatch.setattr(viking_fs_module, "datetime", _FixedDatetime)+ fs.acl_manager = object()++ async def fake_can_access_many(uris, _ctx):+ return {uri: not uri.endswith("/restricted") for uri in uris}++ monkeypatch.setattr(fs, "_can_access_many", fake_can_access_many)result = await fs._ls_agent("viking://resources",@@ -588,6 +621,12 @@ async def test_ls_agent_modtime_is_raw_utc_iso(monkeypatch, fs):assert set(result[0].keys()) == {"uri", "size", "isDir", "modTime", "abstract"}assert result[0]["modTime"] == "2026-06-10T16:30:17.000Z"+ assert result[1] == {+ "name": "restricted",+ "uri": "viking://resources/restricted",+ "isDir": True,+ "access": "denied",+ }@pytest.mark.asynciodiff --git a/tests/storage/test_viking_fs_write_locking.py b/tests/storage/test_viking_fs_write_locking.pyindex 6e1d22986..2474e619b 100644--- a/tests/storage/test_viking_fs_write_locking.py+++ b/tests/storage/test_viking_fs_write_locking.py@@ -169,7 +169,7 @@ async def test_append_file_holds_exact_lease_across_read_and_write(monkeypatch):fake.events.append(("ensure_parent", path, lease_ref))monkeypatch.setattr(fs, "_ensure_parent_dirs", ensure_parent_dirs)- monkeypatch.setattr(fs, "_ensure_mutable_access", lambda _uri, _ctx=None: None)+ monkeypatch.setattr(fs, "_ensure_access", AsyncMock())monkeypatch.setattr(fs,"_uri_to_path",@@ -206,8 +206,7 @@ async def test_mv_extends_outer_lease_with_owned_capability(monkeypatch):}copied_with = []- monkeypatch.setattr(fs, "_ensure_mutable_access", lambda *_args, **_kwargs: None)- monkeypatch.setattr(fs, "_ensure_delete_access", lambda *_args, **_kwargs: None)+ monkeypatch.setattr(fs, "_ensure_access", AsyncMock())monkeypatch.setattr(fs,"_uri_to_path",@@ -246,8 +245,7 @@ async def test_directory_mv_uses_source_tree_and_destination_exact(monkeypatch):fs = VikingFS(agfs=_FakeAGFS())fs._async_agfs = fake # type: ignore[assignment]- monkeypatch.setattr(fs, "_ensure_mutable_access", lambda *_args, **_kwargs: None)- monkeypatch.setattr(fs, "_ensure_delete_access", lambda *_args, **_kwargs: None)+ monkeypatch.setattr(fs, "_ensure_access", AsyncMock())monkeypatch.setattr(fs,"_uri_to_path",@@ -281,8 +279,7 @@ async def test_directory_mv_uses_temporary_tree_only_for_failed_copy_cleanup(monfs = VikingFS(agfs=_FakeAGFS())fs._async_agfs = fake # type: ignore[assignment]- monkeypatch.setattr(fs, "_ensure_mutable_access", lambda *_args, **_kwargs: None)- monkeypatch.setattr(fs, "_ensure_delete_access", lambda *_args, **_kwargs: None)+ monkeypatch.setattr(fs, "_ensure_access", AsyncMock())monkeypatch.setattr(fs,"_uri_to_path",diff --git a/tests/storage/test_viking_vector_scope_filter.py b/tests/storage/test_viking_vector_scope_filter.pyindex d7acc5f5b..0efd38d02 100644--- a/tests/storage/test_viking_vector_scope_filter.py+++ b/tests/storage/test_viking_vector_scope_filter.py@@ -5,7 +5,7 @@ import pytestfrom openviking.core.namespace import uri_partsfrom openviking.server.identity import RequestContext, Role-from openviking.storage.expr import And, Eq, In, Or, PathScope+from openviking.storage.expr import And, Eq, In, Or, PathScope, RawDSLfrom openviking.storage.viking_vector_index_backend import VikingVectorIndexBackendfrom openviking_cli.session.user_id import UserIdentifier@@ -27,6 +27,7 @@ def _build(level: list[int] | None = None,):backend = object.__new__(VikingVectorIndexBackend)+ backend.acl_manager = Nonereturn backend._build_scope_filter(ctx=ctx,context_type=context_type,@@ -37,7 +38,9 @@ def _build(def _tenant_filter(ctx: RequestContext):- return VikingVectorIndexBackend._tenant_filter(ctx, context_type="resource")+ backend = object.__new__(VikingVectorIndexBackend)+ backend.acl_manager = None+ return backend._tenant_filter(ctx)def test_descendant_target_elides_only_visible_root_path_filter():@@ -117,7 +120,7 @@ def test_mixed_visible_and_outside_targets_keep_original_tenant_filter():@pytest.mark.asyncio-async def test_cross_user_targets_cannot_bypass_visible_roots_in_tenant_search():+async def test_tenant_search_enforces_visible_roots_and_shared_acl():ctx = _ctx()own_uri = "viking://user/alice/resources/notes"cross_user_uri = "viking://user/bob/resources/notes"@@ -134,8 +137,43 @@ async def test_cross_user_targets_cannot_bypass_visible_roots_in_tenant_search()"account_id": "acct","context_type": "resource",},+ {+ "id": "legacy-shared",+ "uri": "viking://resources/legacy.md",+ "account_id": "acct",+ "context_type": "resource",+ },+ {+ "id": "direct-shared",+ "uri": "viking://resources/direct.md",+ "account_id": "acct",+ "context_type": "resource",+ "acl_enabled": True,+ "acl_direct_grants": ["1:user:alice"],+ },+ {+ "id": "inherited-shared",+ "uri": "viking://resources/inherited.md",+ "account_id": "acct",+ "context_type": "resource",+ "acl_enabled": True,+ "acl_inherited_grants": ["3:user:*"],+ },+ {+ "id": "denied-shared",+ "uri": "viking://resources/denied.md",+ "account_id": "acct",+ "context_type": "resource",+ "acl_enabled": True,+ "acl_direct_grants": ["7:user:bob"],+ },+ {+ "id": "foreign-account",+ "uri": "viking://resources/foreign.md",+ "account_id": "other",+ "context_type": "resource",+ },]- observed_filters = []def matches(expr, record):if isinstance(expr, And):@@ -144,6 +182,11 @@ async def test_cross_user_targets_cannot_bypass_visible_roots_in_tenant_search()return any(matches(cond, record) for cond in expr.conds)if isinstance(expr, Eq):return record.get(expr.field) == expr.value+ if isinstance(expr, In):+ return any(value in expr.values for value in record.get(expr.field, []))+ if isinstance(expr, RawDSL):+ assert expr.payload["op"] == "must_not"+ return record.get(expr.payload["field"]) not in expr.payload["conds"]if isinstance(expr, PathScope):root = uri_parts(expr.path)path = uri_parts(str(record.get(expr.field, "")))@@ -153,47 +196,47 @@ async def test_cross_user_targets_cannot_bypass_visible_roots_in_tenant_search()raise AssertionError(f"Unexpected filter expression in test: {expr!r}")async def fake_search(*, filter, **_kwargs):- observed_filters.append(filter)return [record for record in records if matches(filter, record)]backend = object.__new__(VikingVectorIndexBackend)+ backend.acl_manager = object()backend.search = fake_search+ visible = await backend.search_in_tenant(+ ctx=ctx,+ query_vector=[1.0],+ context_type="resource",+ )cross_user_only = await backend.search_in_tenant(ctx=ctx,query_vector=[1.0],context_type="resource",target_directories=[cross_user_uri],)- mixed = await backend.search_in_tenant(- ctx=ctx,+ internal = await backend.search_in_tenant(+ ctx=RequestContext(+ user=ctx.user,+ role=ctx.role,+ bypass_acl=True,+ ),query_vector=[1.0],context_type="resource",- target_directories=[own_uri, cross_user_uri],)+ assert [record["id"] for record in visible] == [+ "own",+ "legacy-shared",+ "direct-shared",+ "inherited-shared",+ ]assert cross_user_only == []- assert [record["id"] for record in mixed] == ["own"]- assert observed_filters == [- And(- [- Eq("context_type", "resource"),- _tenant_filter(ctx),- Or([PathScope("uri", cross_user_uri, depth=-1)]),- ]- ),- And(- [- Eq("context_type", "resource"),- _tenant_filter(ctx),- Or(- [- PathScope("uri", own_uri, depth=-1),- PathScope("uri", cross_user_uri, depth=-1),- ]- ),- ]- ),+ assert [record["id"] for record in internal] == [+ "own",+ "cross-user",+ "legacy-shared",+ "direct-shared",+ "inherited-shared",+ "denied-shared",]diff --git a/tests/unit/test_resource_reservation.py b/tests/unit/test_resource_reservation.pyindex a80f7a07e..784291fec 100644--- a/tests/unit/test_resource_reservation.py+++ b/tests/unit/test_resource_reservation.py@@ -14,6 +14,9 @@ class _FakeVikingFS:def __init__(self, existing=()):self.existing = set(existing)+ async def _ensure_access(self, uri, ctx, *, action):+ return None+async def exists(self, uri, *, ctx):return uri in self.existingdiff --git a/tests/unit/test_summarizer_resources_root_split.py b/tests/unit/test_summarizer_resources_root_split.pyindex 6426264fe..c105239a4 100644--- a/tests/unit/test_summarizer_resources_root_split.py+++ b/tests/unit/test_summarizer_resources_root_split.py@@ -227,6 +227,7 @@ async def test_flat_file_refresh_enqueues_incremental_parent_summary():assert msg.recursive is Falseassert msg.changes == {"modified": ["viking://resources/神雕.md"]}assert msg.skip_vectorization is False+ assert msg.role == Role.ROOTassert msg.telemetry_id == "tid"assert wait_tracker.registered == [("tid", msg.id)]diff --git a/tests/utils/test_resource_processor_processing_mode.py b/tests/utils/test_resource_processor_processing_mode.pyindex 841b5e68d..1779bcc53 100644--- a/tests/utils/test_resource_processor_processing_mode.py+++ b/tests/utils/test_resource_processor_processing_mode.py@@ -99,6 +99,7 @@ async def test_flat_file_refreshes_parent_semantics_and_vectorizes_via_summary(ctx=ctx,skip_vectorization=False,ingest_options=IngestOptions(),+ created=True,)