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: support vector record IDs across filesystem APIs (#4442)
Maojia Sheng50228a2e7043
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex c4968b5e0..fb26fb651 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -584,8 +584,9 @@ impl HttpClient {abs_limit: i32,show_all_hidden: bool,node_limit: i32,+ extra_fields: &[String],) -> Result<serde_json::Value> {- let params = vec![+ let mut params = vec![("uri".to_string(), uri.to_string()),("simple".to_string(), simple.to_string()),("recursive".to_string(), recursive.to_string()),@@ -594,6 +595,9 @@ impl HttpClient {("show_all_hidden".to_string(), show_all_hidden.to_string()),("node_limit".to_string(), node_limit.to_string()),];+ for field in extra_fields {+ params.push(("extra_fields".to_string(), field.clone()));+ }self.get("/api/v1/fs/ls", ¶ms).await}@@ -605,8 +609,9 @@ impl HttpClient {show_all_hidden: bool,node_limit: i32,level_limit: i32,+ extra_fields: &[String],) -> Result<serde_json::Value> {- let params = vec![+ let mut params = vec![("uri".to_string(), uri.to_string()),("output".to_string(), output.to_string()),("abs_limit".to_string(), abs_limit.to_string()),@@ -614,6 +619,9 @@ impl HttpClient {("node_limit".to_string(), node_limit.to_string()),("level_limit".to_string(), level_limit.to_string()),];+ for field in extra_fields {+ params.push(("extra_fields".to_string(), field.clone()));+ }self.get("/api/v1/fs/tree", ¶ms).await}@@ -758,12 +766,16 @@ impl HttpClient {pattern: &str,uri: &str,node_limit: i32,+ extra_fields: Option<&[String]>,) -> Result<serde_json::Value> {- let body = serde_json::json!({+ let mut body = serde_json::json!({"pattern": pattern,"uri": uri,"node_limit": node_limit,});+ if let Some(fields) = extra_fields {+ body["extra_fields"] = serde_json::json!(fields);+ }self.post("/api/v1/search/glob", &body).await}@@ -2246,7 +2258,7 @@ mod tests {let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None);client- .ls("viking://resources", false, false, "agent", 256, false, 1)+ .ls("viking://resources", false, false, "agent", 256, false, 1, &[]).await.expect("ls request should succeed");@@ -2372,7 +2384,7 @@ mod tests {let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None);client- .tree("viking://resources", "agent", 256, false, 1, 3)+ .tree("viking://resources", "agent", 256, false, 1, 3, &[]).await.expect("tree request should succeed");diff --git a/crates/ov_cli/src/commands/filesystem.rs b/crates/ov_cli/src/commands/filesystem.rsindex 1ad1c6951..d9d15f45f 100644--- a/crates/ov_cli/src/commands/filesystem.rs+++ b/crates/ov_cli/src/commands/filesystem.rs@@ -6,6 +6,7 @@ use crate::theme;use chrono::{DateTime, Local};use colored::Colorize;use serde_json::Value;+use std::collections::HashSet;use std::io::IsTerminal;use unicode_width::UnicodeWidthStr;@@ -16,6 +17,143 @@ const ENTRY_INDENT: &str = " ";const TREE_INDENT: &str = " ";const TREE_NAME_COLUMN_WIDTH: usize = 38;const TREE_MIN_NAME_COLUMN_WIDTH: usize = 18;+const FIELD_SEP: &str = ",";++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum FieldAlignment {+ Left,+ Right,+}++#[derive(Debug, Clone)]+struct FieldDef {+ name: &'static str,+ header: &'static str,+ alignment: FieldAlignment,+}++static ALL_FIELDS: &[FieldDef] = &[+ FieldDef { name: "name", header: "NAME", alignment: FieldAlignment::Left },+ FieldDef { name: "uri", header: "URI", alignment: FieldAlignment::Left },+ FieldDef { name: "path", header: "PATH", alignment: FieldAlignment::Left },+ FieldDef { name: "type", header: "TYPE", alignment: FieldAlignment::Left },+ FieldDef { name: "size", header: "SIZE", alignment: FieldAlignment::Right },+ FieldDef { name: "mode", header: "MODE", alignment: FieldAlignment::Left },+ FieldDef { name: "mtime", header: "MTIME", alignment: FieldAlignment::Left },+ FieldDef { name: "locked", header: "LOCKED", alignment: FieldAlignment::Left },+ FieldDef { name: "id", header: "ID", alignment: FieldAlignment::Left },+ FieldDef { name: "count", header: "COUNT", alignment: FieldAlignment::Right },+ FieldDef { name: "abstract", header: "ABSTRACT", alignment: FieldAlignment::Left },+];++fn resolve_fields(fields: &[String], is_tree: bool) -> Vec<&'static FieldDef> {+ let mut resolved = Vec::new();+ let mut seen = HashSet::new();+ let id_field = if is_tree { "path" } else { "name" };+ let has_identifier = fields.iter().any(|n| {+ let t = n.trim();+ t == "name" || t == "uri" || t == "path"+ });+ if !has_identifier {+ if let Some(def) = ALL_FIELDS.iter().find(|f| f.name == id_field) {+ seen.insert(def.name);+ resolved.push(def);+ }+ }+ for name in fields {+ let trimmed = name.trim();+ if trimmed.is_empty() {+ continue;+ }+ if let Some(def) = ALL_FIELDS.iter().find(|f| f.name == trimmed) {+ if seen.insert(def.name) {+ resolved.push(def);+ }+ }+ }+ resolved+}++fn field_value(entry: &Value, field: &FieldDef) -> String {+ let obj = entry.as_object();+ match field.name {+ "name" => entry_string(obj, "name")+ .or_else(|| {+ let p = entry_string(obj, "rel_path").or_else(|| entry_string(obj, "uri"))?;+ Some(p.trim_end_matches('/').rsplit('/').next().unwrap_or(p))+ })+ .map(|s| {+ if entry_is_dir(obj) {+ format!("{s}/")+ } else {+ s.to_string()+ }+ })+ .unwrap_or_else(|| "-".to_string()),+ "uri" => entry_string(obj, "uri").unwrap_or("-").to_string(),+ "path" => entry_string(obj, "rel_path")+ .map(|p| {+ if entry_is_dir(obj) && !p.ends_with('/') {+ format!("{p}/")+ } else {+ p.to_string()+ }+ })+ .or_else(|| entry_string(obj, "name").map(|s| s.to_string()))+ .or_else(|| entry_string(obj, "uri").map(|s| s.to_string()))+ .unwrap_or_else(|| "-".to_string()),+ "type" => {+ if entry_is_dir(obj) {+ "dir".to_string()+ } else {+ "file".to_string()+ }+ }+ "size" => obj+ .and_then(|o| o.get("size"))+ .and_then(Value::as_u64)+ .map(format_size)+ .unwrap_or_else(|| "-".to_string()),+ "mode" => obj+ .and_then(|o| o.get("mode"))+ .and_then(Value::as_u64)+ .map(|m| format_mode(m, entry_is_dir(obj)))+ .unwrap_or_else(|| "-".to_string()),+ "mtime" => entry_mod_time(obj).unwrap_or_else(|| "-".to_string()),+ "locked" => obj+ .and_then(|o| o.get("isLocked"))+ .and_then(Value::as_bool)+ .map(|v| if v { "yes".to_string() } else { "no".to_string() })+ .unwrap_or_else(|| "-".to_string()),+ "id" => entry_string(obj, "id")+ .map(str::to_string)+ .unwrap_or_else(|| "-".to_string()),+ "count" => obj+ .and_then(|o| o.get("count"))+ .and_then(Value::as_u64)+ .map(|c| c.to_string())+ .unwrap_or_else(|| "-".to_string()),+ "abstract" => entry_string(obj, "abstract")+ .map(|s| {+ if is_directory_abstract_placeholder(s) {+ "-".to_string()+ } else {+ s.chars().take(80).collect::<String>()+ }+ })+ .unwrap_or_else(|| "-".to_string()),+ _ => "-".to_string(),+ }+}++fn tree_depth(entry: &Value) -> usize {+ entry+ .as_object()+ .and_then(|o| o.get("rel_path"))+ .and_then(Value::as_str)+ .map(|p| p.matches('/').count())+ .unwrap_or(0)+}pub async fn ls(client: &HttpClient,@@ -28,19 +166,24 @@ pub async fn ls(node_limit: i32,output_format: OutputFormat,compact: bool,+ fields: Option<Vec<String>>,) -> Result<()> {+ let extra = extra_fields_from(&fields);+ // When fields are requested we need entry objects (not URI strings) regardless of --simple.+ let api_simple = simple && fields.is_none();let result = client.ls(uri,- simple,+ api_simple,recursive,output,abs_limit,show_all_hidden,node_limit,+ &extra,).await?;- output_filesystem_entries(&result, output_format, compact, false);+ output_filesystem_entries(&result, output_format, compact, false, simple, fields.as_deref());Ok(())}@@ -54,7 +197,10 @@ pub async fn tree(level_limit: i32,output_format: OutputFormat,compact: bool,+ simple: bool,+ fields: Option<Vec<String>>,) -> Result<()> {+ let extra = extra_fields_from(&fields);let result = client.tree(uri,@@ -63,35 +209,261 @@ pub async fn tree(show_all_hidden,node_limit,level_limit,+ &extra,).await?;- output_filesystem_entries(&result, output_format, compact, true);+ output_filesystem_entries(&result, output_format, compact, true, simple, fields.as_deref());Ok(())}+fn extra_fields_from(fields: &Option<Vec<String>>) -> Vec<String> {+ let Some(fields) = fields else {+ return Vec::new();+ };+ let mut extra = Vec::new();+ for f in fields {+ let key = match f.as_str() {+ "locked" => Some("locked"),+ "id" => Some("id"),+ "count" => Some("count"),+ _ => None,+ };+ if let Some(k) = key {+ if !extra.iter().any(|e: &String| e == k) {+ extra.push(k.to_string());+ }+ }+ }+ extra+}+fn output_filesystem_entries(result: &Value,output_format: OutputFormat,compact: bool,is_tree: bool,+ simple: bool,+ fields: Option<&[String]>,) {- if let Some(rendered) = render_filesystem_entries_for_table(result, output_format, is_tree) {- println!("{rendered}");- } else {- output_success(result, output_format, compact);+ match output_format {+ OutputFormat::Json => {+ output_success(result, output_format, compact);+ }+ OutputFormat::Table => {+ if let Some(fields) = fields {+ let defs = resolve_fields(fields, is_tree);+ if defs.is_empty() {+ output_success(result, output_format, compact);+ return;+ }+ if simple {+ if let Some(rendered) = render_simple_fields(result, &defs, is_tree) {+ println!("{rendered}");+ } else {+ output_success(result, output_format, compact);+ }+ } else {+ render_fields_table(result, &defs, is_tree);+ }+ } else if let Some(rendered) =+ render_filesystem_entries_for_table(result, output_format, is_tree, simple)+ {+ println!("{rendered}");+ } else {+ output_success(result, output_format, compact);+ }+ }+ }+}++/// Print one URI per line from a glob-style `{matches:[...],count:N}` result (URI strings).+pub fn print_uri_blob_per_line(result: &Value) {+ let Some(matches) = result.get("result").and_then(|v| v.get("matches")).or_else(|| result.get("matches")) else {+ return;+ };+ let Some(arr) = matches.as_array() else { return };+ for item in arr {+ if let Some(s) = item.as_str() {+ println!("{s}");+ }+ }+}++pub fn output_entry_list(+ result: &Value,+ output_format: OutputFormat,+ compact: bool,+ simple: bool,+ fields: Option<&[String]>,+) {+ output_filesystem_entries(result, output_format, compact, false, simple, fields);+}++fn render_simple_fields(+ result: &Value,+ fields: &[&FieldDef],+ is_tree: bool,+) -> Option<String> {+ let entries = extract_entries(result)?;+ let mut lines = Vec::with_capacity(entries.len());+ for entry in entries {+ let vals: Vec<String> = fields+ .iter()+ .map(|f| {+ let mut v = field_value(entry, f);+ if f.name == "name" && is_tree {+ let depth = tree_depth(entry);+ let indent = TREE_INDENT.repeat(depth);+ v = format!("{indent}{v}");+ }+ v+ })+ .collect();+ lines.push(vals.join(FIELD_SEP));}+ Some(lines.join("\n"))+}++fn render_simple_tree_paths(result: &Value) -> Option<String> {+ let path = ALL_FIELDS.iter().find(|field| field.name == "path")?;+ render_simple_fields(result, &[path], false)+}++fn render_fields_table(result: &Value, fields: &[&FieldDef], is_tree: bool) {+ let (entries, profile) = match filesystem_entries(result) {+ Some(v) => v,+ None => {+ output_success(result, OutputFormat::Json, false);+ return;+ }+ };+ let mut lines = Vec::new();+ if entries.is_empty() {+ lines.push(theme::muted("(empty)").to_string());+ append_profile_lines(profile, &mut lines);+ println!("{}", lines.join("\n"));+ return;+ }++ let mut rows: Vec<Vec<String>> = Vec::with_capacity(entries.len());+ for entry in entries {+ let mut row: Vec<String> = fields+ .iter()+ .map(|f| {+ let mut v = field_value(entry, f);+ if f.name == "name" && is_tree {+ let depth = tree_depth(entry);+ let indent = TREE_INDENT.repeat(depth);+ v = format!("{indent}{v}");+ }+ v+ })+ .collect();+ if is_tree {+ if let Some(path_field_idx) = fields.iter().position(|f| f.name == "path") {+ let depth = tree_depth(entry);+ let indent = TREE_INDENT.repeat(depth);+ let val = &row[path_field_idx];+ row[path_field_idx] = format!("{indent}{val}");+ }+ }+ rows.push(row);+ }++ let headers: Vec<String> = fields.iter().map(|f| f.header.to_string()).collect();+ let mut col_widths: Vec<usize> = headers.iter().map(|h| h.width()).collect();+ for row in &rows {+ for (i, cell) in row.iter().enumerate() {+ let w = display_width(cell);+ if i < col_widths.len() && w > col_widths[i] {+ col_widths[i] = w;+ }+ }+ }++ let header_line = headers+ .iter()+ .enumerate()+ .map(|(i, h)| pad_cell(h, col_widths[i], fields[i].alignment == FieldAlignment::Right))+ .collect::<Vec<_>>()+ .join(" ");+ lines.push(theme::heading(header_line).bold().to_string());++ for row in &rows {+ let line = row+ .iter()+ .enumerate()+ .map(|(i, cell)| {+ let content = fit_display_text(cell, col_widths[i]);+ pad_cell(+ &content,+ col_widths[i],+ fields[i].alignment == FieldAlignment::Right,+ )+ })+ .collect::<Vec<_>>()+ .join(" ");+ lines.push(line);+ }++ append_profile_lines(profile, &mut lines);+ println!("{}", lines.join("\n"));+}++fn display_width(s: &str) -> usize {+ s.width()+}++fn extract_entries(value: &Value) -> Option<Vec<&Value>> {+ if let Some(arr) = value.as_array() {+ if arr.iter().all(Value::is_object) {+ return Some(arr.iter().collect());+ }+ return None;+ }+ let obj = value.as_object()?;+ // glob shape: top-level {matches:[...], count:N} (unwrapped from the success envelope+ // as a result object, with no nested "result" key).+ if let Some(matches) = obj.get("matches") {+ if let Some(arr) = matches.as_array() {+ if arr.iter().all(Value::is_object) {+ return Some(arr.iter().collect());+ }+ }+ }+ let result = obj.get("result")?;+ if let Some(arr) = result.as_array() {+ if arr.iter().all(Value::is_object) {+ return Some(arr.iter().collect());+ }+ }+ if let Some(obj_res) = result.as_object() {+ if let Some(matches) = obj_res.get("matches") {+ if let Some(arr) = matches.as_array() {+ if arr.iter().all(Value::is_object) {+ return Some(arr.iter().collect());+ }+ }+ }+ }+ None}fn render_filesystem_entries_for_table(value: &Value,output_format: OutputFormat,is_tree: bool,+ simple: bool,) -> Option<String> {if matches!(output_format, OutputFormat::Json) {return None;}if is_tree {- render_tree_entries_for_table(value)+ if simple {+ render_simple_tree_paths(value)+ } else {+ render_tree_entries_for_table(value)+ }} else {render_ls_entries_for_table(value)}@@ -148,11 +520,30 @@ fn filesystem_entries(value: &Value) -> Option<(Vec<&Value>, Option<&Value>)> {let object = value.as_object()?;let profile = object.get("profile").filter(|profile| !profile.is_null());- let entries = object.get("result")?.as_array()?;- if !entries.iter().all(Value::is_object) {- return None;+ // glob shape: top-level {matches:[...], count:N}+ if let Some(matches) = object.get("matches") {+ if let Some(arr) = matches.as_array() {+ if arr.iter().all(Value::is_object) {+ return Some((arr.iter().collect(), profile));+ }+ }}- Some((entries.iter().collect(), profile))+ let result = object.get("result")?;+ if let Some(arr) = result.as_array() {+ if arr.iter().all(Value::is_object) {+ return Some((arr.iter().collect(), profile));+ }+ }+ if let Some(obj_res) = result.as_object() {+ if let Some(matches) = obj_res.get("matches") {+ if let Some(arr) = matches.as_array() {+ if arr.iter().all(Value::is_object) {+ return Some((arr.iter().collect(), profile));+ }+ }+ }+ }+ None}fn render_ls_entry(rank: usize, entry: &Value, text_width: usize, lines: &mut Vec<String>) {@@ -351,6 +742,7 @@ fn format_mod_time_for_display(value: &str) -> String {fn is_directory_abstract_placeholder(value: &str) -> bool {value.contains("[Directory abstract is not ready]")+ || value.contains("[.abstract.md is not ready]")}fn format_size(bytes: u64) -> String {@@ -369,6 +761,32 @@ fn format_size(bytes: u64) -> String {}}+fn format_mode(mode: u64, is_dir: bool) -> String {+ let file_type = if is_dir { 'd' } else { '-' };+ let perm = |read: bool, write: bool, execute: bool| -> String {+ format!(+ "{}{}{}",+ if read { 'r' } else { '-' },+ if write { 'w' } else { '-' },+ if execute { 'x' } else { '-' }+ )+ };+ let owner = perm(mode & 0o400 != 0, mode & 0o200 != 0, mode & 0o100 != 0);+ let group = perm(mode & 0o040 != 0, mode & 0o020 != 0, mode & 0o010 != 0);+ let other = perm(mode & 0o004 != 0, mode & 0o002 != 0, mode & 0o001 != 0);+ format!("{file_type}{owner}{group}{other}")+}++fn pad_cell(content: &str, width: usize, align_right: bool) -> String {+ let visible = display_width(content);+ let pad = width.saturating_sub(visible);+ if align_right {+ format!("{}{content}", " ".repeat(pad))+ } else {+ format!("{content}{}", " ".repeat(pad))+ }+}+fn entry_text_width() -> usize {if std::io::stdout().is_terminal()&& let Ok((columns, _)) = crossterm::terminal::size()@@ -496,7 +914,7 @@ fn output_message_result(#[cfg(test)]mod tests {use super::{- render_filesystem_entries_for_table, render_ls_entries_for_table,+ render_filesystem_entries_for_table, render_ls_entries_for_table, render_simple_fields,render_tree_entries_for_table,};use crate::output::render_profiled_scalar_result;@@ -681,11 +1099,88 @@ mod tests {]);assert!(- render_filesystem_entries_for_table(&result, crate::output::OutputFormat::Json, false)+ render_filesystem_entries_for_table(&result, crate::output::OutputFormat::Json, false, false).is_none());}+ #[test]+ fn tree_simple_without_fields_renders_one_path_per_line() {+ let result = json!([+ {"rel_path": "docs", "isDir": true},+ {"rel_path": "docs/readme.md", "isDir": false}+ ]);++ let rendered = render_filesystem_entries_for_table(+ &result,+ crate::output::OutputFormat::Table,+ true,+ true,+ );++ assert_eq!(rendered.as_deref(), Some("docs/\ndocs/readme.md"));+ }++ #[test]+ fn simple_id_field_keeps_complete_record_id() {+ let record_id = "0123456789abcdef0123456789abcdef";+ let result = json!([{"name": "readme.md", "id": record_id, "isDir": false}]);+ let fields = vec!["id".to_string()];+ let defs = super::resolve_fields(&fields, false);++ let rendered = render_simple_fields(&result, &defs, false);+ let expected = format!("readme.md,{record_id}");++ assert_eq!(rendered.as_deref(), Some(expected.as_str()));+ assert!(!rendered.expect("simple fields").contains(".."));+ }++ #[test]+ fn table_id_field_keeps_complete_record_id() {+ let record_id = "0123456789abcdef0123456789abcdef";+ let entry = json!({"name": "readme.md", "id": record_id, "isDir": false});+ let id_field = super::ALL_FIELDS+ .iter()+ .find(|field| field.name == "id")+ .expect("id field");++ assert_eq!(super::field_value(&entry, id_field), record_id);+ }++ #[test]+ fn format_mode_formats_permissions() {+ assert_eq!(super::format_mode(0o40755, true), "drwxr-xr-x");+ assert_eq!(super::format_mode(0o100644, false), "-rw-r--r--");+ assert_eq!(super::format_mode(0o100755, false), "-rwxr-xr-x");+ // AGFS omits S_IFMT bits; isDir flag drives the file-type char+ assert_eq!(super::format_mode(0o755, true), "drwxr-xr-x");+ assert_eq!(super::format_mode(0o644, false), "-rw-r--r--");+ }++ #[test]+ fn resolve_fields_prepends_name_when_no_identifier_given_ls() {+ let fields = vec!["size".to_string(), "mtime".to_string()];+ let defs = super::resolve_fields(&fields, false);+ let names: Vec<&str> = defs.iter().map(|d| d.name).collect();+ assert_eq!(names, vec!["name", "size", "mtime"]);+ }++ #[test]+ fn resolve_fields_prepends_path_when_no_identifier_given_tree() {+ let fields = vec!["size".to_string()];+ let defs = super::resolve_fields(&fields, true);+ let names: Vec<&str> = defs.iter().map(|d| d.name).collect();+ assert_eq!(names, vec!["path", "size"]);+ }++ #[test]+ fn resolve_fields_keeps_user_provided_identifier() {+ let fields = vec!["uri".to_string(), "size".to_string()];+ let defs = super::resolve_fields(&fields, false);+ let names: Vec<&str> = defs.iter().map(|d| d.name).collect();+ assert_eq!(names, vec!["uri", "size"]);+ }+fn strip_ansi(input: &str) -> String {let mut output = String::with_capacity(input.len());let mut chars = input.chars().peekable();@@ -712,7 +1207,6 @@ mod tests {impl ScopedEnvVar {fn set(key: &'static str, value: &str) -> Self {let previous = std::env::var(key).ok();- // Test-only process environment override; Drop restores the prior value.unsafe {std::env::set_var(key, value);}diff --git a/crates/ov_cli/src/commands/search.rs b/crates/ov_cli/src/commands/search.rsindex 632fbd6aa..4ee848981 100644--- a/crates/ov_cli/src/commands/search.rs+++ b/crates/ov_cli/src/commands/search.rs@@ -756,9 +756,32 @@ pub async fn glob(node_limit: i32,output_format: OutputFormat,compact: bool,+ simple: bool,+ fields: Option<Vec<String>>,) -> Result<()> {- let result = client.glob(pattern, uri, node_limit).await?;- output_success(&result, output_format, compact);+ let has_fields = fields.is_some();+ let extra: Option<&[String]> = if has_fields {+ fields.as_deref()+ } else {+ None+ };+ let result = client.glob(pattern, uri, node_limit, extra).await?;+ if simple && !has_fields {+ super::filesystem::print_uri_blob_per_line(&result);+ return Ok(());+ }+ if has_fields || simple {+ let effective_fields = fields.or_else(|| Some(vec!["uri".to_string()]));+ super::filesystem::output_entry_list(+ &result,+ output_format,+ compact,+ simple,+ effective_fields.as_deref(),+ );+ } else {+ output_success(&result, output_format, compact);+ }Ok(())}diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rsindex 8eb22c0bd..8b7e8b45b 100644--- a/crates/ov_cli/src/handlers.rs+++ b/crates/ov_cli/src/handlers.rs@@ -1640,6 +1640,7 @@ pub async fn handle_ls(abs_limit: i32,show_all_hidden: bool,node_limit: i32,+ fields: Option<Vec<String>>,ctx: CliContext,) -> Result<()> {let mut params = vec![@@ -1656,10 +1657,17 @@ pub async fn handle_ls(if show_all_hidden {params.push("-a".to_string());}+ if let Some(fields) = &fields {+ params.push(format!("-f {}", fields.join(",")));+ }print_command_echo("ov ls", ¶ms.join(" "), ctx.config.echo_command);let client = ctx.get_client();- let api_output = if ctx.compact { "agent" } else { "original" };+ let api_output = if fields.is_some() || !ctx.compact {+ "original"+ } else {+ "agent"+ };commands::filesystem::ls(&client,&uri,@@ -1671,6 +1679,7 @@ pub async fn handle_ls(node_limit,ctx.output_format,ctx.compact,+ fields,).await}@@ -1681,6 +1690,8 @@ pub async fn handle_tree(show_all_hidden: bool,node_limit: i32,level_limit: i32,+ simple: bool,+ fields: Option<Vec<String>>,ctx: CliContext,) -> Result<()> {let mut params = vec![@@ -1692,10 +1703,20 @@ pub async fn handle_tree(if show_all_hidden {params.push("-a".to_string());}+ if simple {+ params.push("-s".to_string());+ }+ if let Some(fields) = &fields {+ params.push(format!("-f {}", fields.join(",")));+ }print_command_echo("ov tree", ¶ms.join(" "), ctx.config.echo_command);let client = ctx.get_client();- let api_output = if ctx.compact { "agent" } else { "original" };+ let api_output = if fields.is_some() || !ctx.compact {+ "original"+ } else {+ "agent"+ };commands::filesystem::tree(&client,&uri,@@ -1706,6 +1727,8 @@ pub async fn handle_tree(level_limit,ctx.output_format,ctx.compact,+ simple,+ fields,).await}@@ -1845,13 +1868,21 @@ pub async fn handle_glob(pattern: String,uri: String,node_limit: i32,+ simple: bool,+ fields: Option<Vec<String>>,ctx: CliContext,) -> Result<()> {- let params = [+ let mut params = vec![format!("--uri={}", uri),format!("-n {}", node_limit),format!("\"{}\"", pattern),];+ if simple {+ params.push("-s".to_string());+ }+ if let Some(fields) = &fields {+ params.push(format!("-f {}", fields.join(",")));+ }print_command_echo("ov glob", ¶ms.join(" "), ctx.config.echo_command);let client = ctx.get_client();commands::search::glob(@@ -1861,6 +1892,8 @@ pub async fn handle_glob(node_limit,ctx.output_format,ctx.compact,+ simple,+ fields,).await}diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex 89c323303..2b843d4c3 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -530,6 +530,9 @@ enum Commands {help_heading = "Common options")]node_limit: i32,+ /// Comma-separated fields to display (name,uri,path,type,size,mode,mtime,locked,id,count,abstract)+ #[arg(short = 'f', long = "fields", value_delimiter = ',', value_name = "FIELDS", help_heading = "Output options")]+ fields: Option<Vec<String>>,},/// [Data] Get directory treeTree {@@ -568,6 +571,12 @@ enum Commands {help_heading = "Common options")]level_limit: i32,+ /// Simple path output (just paths, no tree formatting)+ #[arg(short, long, help_heading = "Common options")]+ simple: bool,+ /// Comma-separated fields to display (name,uri,path,type,size,mode,mtime,locked,id,count)+ #[arg(short = 'f', long = "fields", value_delimiter = ',', value_name = "FIELDS", help_heading = "Output options")]+ fields: Option<Vec<String>>,},/// [Data] Create directoryMkdir {@@ -931,6 +940,12 @@ enum Commands {help_heading = "Common options")]node_limit: i32,+ /// Simple output (one entry per line)+ #[arg(short, long, help_heading = "Common options")]+ simple: bool,+ /// Comma-separated fields to display (name,uri,path,type,size,mode,mtime,locked,id)+ #[arg(short = 'f', long = "fields", value_delimiter = ',', value_name = "FIELDS", help_heading = "Output options")]+ fields: Option<Vec<String>>,},/// [Data] Session management commandsSession {@@ -3470,14 +3485,17 @@ async fn main() {abs_limit,all,node_limit,- } => handlers::handle_ls(uri, simple, recursive, abs_limit, all, node_limit, ctx).await,+ fields,+ } => handlers::handle_ls(uri, simple, recursive, abs_limit, all, node_limit, fields, ctx).await,Commands::Tree {uri,abs_limit,all,node_limit,level_limit,- } => handlers::handle_tree(uri, abs_limit, all, node_limit, level_limit, ctx).await,+ simple,+ fields,+ } => handlers::handle_tree(uri, abs_limit, all, node_limit, level_limit, simple, fields, ctx).await,Commands::Mkdir { uri, description } => handlers::handle_mkdir(uri, description, ctx).await,Commands::Rm {uri,@@ -3716,7 +3734,9 @@ async fn main() {pattern,uri,node_limit,- } => handlers::handle_glob(pattern, uri, node_limit, ctx).await,+ simple,+ fields,+ } => handlers::handle_glob(pattern, uri, node_limit, simple, fields, ctx).await,};if let Err(e) = result {diff --git a/crates/ov_cli/src/tui/tree.rs b/crates/ov_cli/src/tui/tree.rsindex 9c1008f04..78ac443ee 100644--- a/crates/ov_cli/src/tui/tree.rs+++ b/crates/ov_cli/src/tui/tree.rs@@ -139,7 +139,7 @@ impl TreeState {async fn fetch_children(client: &HttpClient, uri: &str) -> Result<Vec<TreeNode>, String> {let result = client- .ls(uri, false, false, "original", 256, false, 1000)+ .ls(uri, false, false, "original", 256, false, 1000, &[]).await.map_err(|e| e.to_string())?;diff --git a/docs/en/api/03-filesystem.md b/docs/en/api/03-filesystem.mdindex 8c7a2e79c..48c3f43ac 100644--- a/docs/en/api/03-filesystem.md+++ b/docs/en/api/03-filesystem.md@@ -25,6 +25,7 @@ List directory contents.| node_limit | int | No | 1000 | Maximum number of results || sort_by | str | No | None | Sort directories and files within their groups by `name` or `mtime` before applying `node_limit`; directories remain first || sort_order | str | No | `asc` | Sort direction: `asc` or `desc` |+| extra_fields | list[str] | No | None | Extra fields to include: `locked`, `id`, `count` |**Entry Structure**@@ -117,9 +118,13 @@ curl -X GET "http://localhost:1933/api/v1/fs/ls?uri=viking://resources/&recursiv**CLI**```bash-openviking ls viking://resources/ [--simple] [--recursive]+openviking ls viking://resources/ [--simple] [--recursive] [-f FIELDS]+openviking tree viking://resources/my-project/ [--simple] [-f FIELDS]+openviking glob "**/*.md" [--uri viking://resources/] [--simple] [-f FIELDS]```+`-f`/`--fields` accepts a comma-separated list of columns to display (ps `-o` style), producing a column-aligned table with a header row. Available fields: `name`, `uri`, `path`, `type`, `size`, `mode`, `mtime`, `locked`, `id`, `count`, `abstract`. Combining `--simple` with `-f` outputs comma-separated values (no header, no tree indentation), one entry per line — suitable for scripting pipelines. When `--simple` is used without `-f`, the previous behavior (bare URI per line) is preserved.+**Response**@@ -156,6 +161,7 @@ Get directory tree structure.| show_all_hidden | bool | No | False | Include hidden files like `-a` || node_limit | int | No | 1000 | Maximum number of results || level_limit | int | No | 3 | Maximum directory depth to traverse |+| extra_fields | list[str] | No | None | Extra fields to include: `locked`, `id`, `count` |**Python HTTP SDK**@@ -239,7 +245,7 @@ Get file or directory status information. For directories, returns the count of| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|-| uri | str | Yes | - | Viking URI |+| uri | str | Yes | - | Viking URI (e.g. `viking://resources/docs/api.md`) or a 32-character hex vector record `id` |**Python HTTP SDK**@@ -303,6 +309,7 @@ openviking stat viking://resources/my-project/docs"modTime": "2024-01-01T00:00:00Z","isDir": false,"isLocked": false,+ "id": "a1b2c3d4e5f678901234567890abcdef","uri": "viking://resources/docs/api.md"},"time": 0.1@@ -330,6 +337,8 @@ openviking stat viking://resources/my-project/docsThe `isLocked` field reports whether the path is currently held by a path lock: the path itself has a valid lock (including an exact-path lock for the target), or any ancestor directory holds a TreeLock. Returns `false` when the LockManager is unavailable or the lookup fails, so callers can avoid attempting a write only to observe `ResourceBusyError`.+The `id` field (files only) is the deterministic vector record primary key in VikingDB, computed as `md5(f"{account_id}:{uri}")` for level 2 (regular file) records. This value matches the `id` field in the vector collection schema and can be used to cross-reference vector records without an additional lookup. The field is omitted for directories because a directory may have multiple vector records across semantic levels (L0 abstract, L1 overview). Because indexing is asynchronous, a newly returned ID might not be resolvable immediately; lookup by ID can also fail after its vector record is deleted. In either case, `stat(id)` returns `NOT_FOUND` with a reason indicating that the data may not have been indexed yet or may have been deleted.+The `count` field (directories only) contains the estimated number of items (files and subdirectories) under this directory (from vector index).---diff --git a/docs/en/api/06-retrieval.md b/docs/en/api/06-retrieval.mdindex f48b95ae5..bab95f993 100644--- a/docs/en/api/06-retrieval.md+++ b/docs/en/api/06-retrieval.md@@ -931,6 +931,7 @@ The `glob()` method uses file wildcard pattern matching URIs, similar to Unix sh| pattern | str | Yes | - | Glob pattern (e.g., `**/*.md`) || uri | str | No | "viking://" | Starting URI || node_limit | int | No | 256 | Maximum number of matches to return. Omitted requests default to 256; pass a larger integer when you need more results |+| extra_fields | list[str] | No | None | Extra fields to include per match. Recognized names: `name`, `uri`, `path`, `type`, `size`, `mode`, `mtime`, `locked`, `id`. When omitted, the response contains URI strings only; when provided, `result.matches` becomes a list of entry objects |#### 3. Usage Examples@@ -946,7 +947,8 @@ curl -X POST http://localhost:1933/api/v1/search/glob \-H "X-API-Key: your-key" \-d '{"pattern": "**/*.md",- "uri": "viking://resources"+ "uri": "viking://resources",+ "extra_fields": ["name", "size", "mtime"]}'```@@ -964,13 +966,16 @@ print(f"Found {results['count']} markdown files:")for uri in results['matches']:print(f" {uri}")-# Find all Python files with a higher explicit cap+# Find all Python files with extra stat fieldsresults = client.glob(pattern="**/*.py",uri="viking://resources",node_limit=1024,+ extra_fields=["name", "size", "mtime", "mode"],)print(f"Found {results['count']} Python files")+for entry in results['matches']:+ print(f" {entry['name']} {entry['size']} {entry['mtime']}")```**TypeScript SDK**@@ -999,10 +1004,18 @@ openviking glob "**/*.md" --uri viking://resources# Find all Python filesopenviking glob "**/*.py"++# Table output with extra fields (ps -o style -f)+openviking glob "**/*.py" -f name,size,mtime,mode++# Script-friendly simple output with selected fields (comma-separated, no header)+openviking glob "**/*.py" --simple -f name,size```**Response Example**+Default (URI strings):+```json{"status": "ok",@@ -1017,6 +1030,22 @@ openviking glob "**/*.py"}```+With `extra_fields=["name","size","mtime"]`:++```json+{+ "status": "ok",+ "result": {+ "matches": [+ {"name": "api.md", "uri": "viking://resources/docs/api.md", "size": 12345, "mtime": 1720000000},+ {"name": "guide.md", "uri": "viking://resources/docs/guide.md", "size": 8234, "mtime": 1720000001}+ ],+ "count": 2+ },+ "time": 0.2+}+```+---## Working with Resultsdiff --git a/docs/en/api/12-content.md b/docs/en/api/12-content.mdindex 5218610db..e0783b5b0 100644--- a/docs/en/api/12-content.md+++ b/docs/en/api/12-content.md@@ -143,7 +143,7 @@ Read the complete text of an L0, L1, or L2 file.| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|-| uri | str | Yes | - | Viking URI |+| uri | str | Yes | - | Viking URI (e.g. `viking://resources/docs/api.md`) or a 32-character hex vector record `id` (returned by `stat()`) || offset | int | No | 0 | Starting line number (0-indexed) || limit | int | No | -1 | Number of lines to read, `-1` means read to end || raw | bool | No | false | Return raw stored content without memory-field cleanup. HTTP API only (Python SDK does not expose it yet). |@@ -151,6 +151,7 @@ Read the complete text of an L0, L1, or L2 file.**Notes**- `read()` accepts file URIs only. Passing an existing directory URI returns `INVALID_ARGUMENT` (`400`), not `NOT_FOUND`. This error carries a structured `details` payload — `details.expected` is `"file"`, `details.actual` is `"directory"`, and `details.resource` is the offending URI (present on the HTTP path) — so clients can detect a file-vs-directory mismatch programmatically (for example, fall back to `list`) instead of string-matching the message.+- Instead of a Viking URI, you may pass the 32-character hex `id` returned by `stat()` for a file. The server looks up the URI via the vector index and applies the same permission checks. Because indexing is asynchronous, a newly returned ID might not be resolvable immediately; lookup also fails if the corresponding vector record has been deleted. In both cases, the server returns `NOT_FOUND` and indicates that the data may not have been indexed yet or may have been deleted.- Public URI parameters accept `resources` and `user` scopes. For session files, use `viking://user/{user_id}/sessions/{session_id}` or the backward-compatible `viking://session/{session_id}` alias. Internal scopes such as `temp` and `queue` return `INVALID_URI`.diff --git a/docs/en/concepts/04-viking-uri.md b/docs/en/concepts/04-viking-uri.mdindex 7464adb57..07d3edb28 100644--- a/docs/en/concepts/04-viking-uri.md+++ b/docs/en/concepts/04-viking-uri.md@@ -58,6 +58,10 @@ each caller.Moving away from traditional flat database thinking, all context is organized as a filesystem. Agents no longer just find data through vector search, but can locate and browse data through deterministic paths and standard filesystem commands. Each context or directory is assigned a unique URI identifier string in the format viking://{scope}/{path}, allowing the system to precisely locate and access resources stored in different locations.+## File IDs++In addition to its URI, every file is automatically assigned a stable `id` that serves as the primary key of its vector record in VikingDB. The id is deterministically computed as `md5(f"{account_id}:{uri}")` for level 2 (regular file) records, and is returned by `stat()` and other metadata APIs. This allows callers to cross-reference vector index entries without a separate lookup. The id is scoped to the account and changes if the file is moved to a different URI (vector records are re-keyed during URI migration). Directories do not expose a single `id` because a directory may span multiple semantic levels (L0 abstract, L1 overview, L2), each with its own record.+```viking://├── user/diff --git a/docs/zh/api/03-filesystem.md b/docs/zh/api/03-filesystem.mdindex aac02e156..e3713367a 100644--- a/docs/zh/api/03-filesystem.md+++ b/docs/zh/api/03-filesystem.md@@ -237,7 +237,7 @@ openviking tree viking://resources/my-project/| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|-| uri | str | 是 | - | Viking URI |+| uri | str | 是 | - | Viking URI(如 `viking://resources/docs/api.md`)或 32 字符十六进制向量记录 `id` |**Python HTTP SDK**@@ -301,6 +301,7 @@ openviking stat viking://resources/my-project/docs"modTime": "2024-01-01T00:00:00Z","isDir": false,"isLocked": false,+ "id": "a1b2c3d4e5f678901234567890abcdef","uri": "viking://resources/docs/api.md"},"time": 0.1@@ -328,6 +329,8 @@ openviking stat viking://resources/my-project/docs`isLocked` 字段反映路径当前是否被路径锁持有:路径自身存在有效锁(包括目标路径对应的 exact-path lock),或者任一祖先目录持有 TreeLock。当 LockManager 不可用或查询失败时返回 `false`,调用方可据此避免先写入再观察到 `ResourceBusyError`。+`id` 字段(仅文件)是 VikingDB 中向量记录的确定性主键,对 level 2(常规文件)记录按 `md5(f"{account_id}:{uri}")` 计算。该值与向量集合 schema 中的 `id` 字段一致,可用于直接交叉引用向量记录而无需额外查询。目录不返回此字段,因为一个目录在多个语义层(L0 abstract、L1 overview、L2)下可能对应多条向量记录,id 不唯一。由于索引是异步生成的,新返回的 ID 可能暂时无法解析;对应向量记录被删除后,按 ID 查询也会失败。这两种情况下,`stat(id)` 都会返回 `NOT_FOUND`,并在原因中提示数据可能尚未索引或已经删除。+`count` 字段(仅目录)包含该目录下的项目(文件和子目录)估计数量(来自向量索引)。---diff --git a/docs/zh/api/12-content.md b/docs/zh/api/12-content.mdindex d834844e9..736113f65 100644--- a/docs/zh/api/12-content.md+++ b/docs/zh/api/12-content.md@@ -143,7 +143,7 @@ openviking overview viking://resources/docs/| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|-| uri | str | 是 | - | Viking URI |+| uri | str | 是 | - | Viking URI(如 `viking://resources/docs/api.md`)或 32 字符十六进制向量记录 `id`(由 `stat()` 返回) || offset | int | 否 | 0 | 起始行号(0 开始) || limit | int | 否 | -1 | 读取的行数,`-1` 表示读到结尾 || raw | bool | 否 | false | 返回未过滤 MEMORY_FIELDS 的原始存储内容(仅 HTTP API,Python SDK 暂未暴露)。 |@@ -151,6 +151,7 @@ openviking overview viking://resources/docs/**说明**- `read()` 只接受文件 URI。传入已存在的目录 URI 时返回 `INVALID_ARGUMENT`(`400`),而不是 `NOT_FOUND`。该错误会携带结构化的 `details` 字段——`details.expected` 为 `"file"`,`details.actual` 为 `"directory"`,`details.resource` 为出错的 URI(HTTP 路径上会带上)——客户端据此即可以编程方式判断"文件 vs 目录"不匹配(例如回退到 `list`),而无需对错误消息做字符串匹配。+- 除 Viking URI 外,还可以传入 `stat()` 返回的 32 字符十六进制文件 `id`。服务端通过向量索引查找对应 URI 并执行相同的权限校验。由于索引是异步生成的,新返回的 ID 可能暂时无法解析;对应向量记录被删除后,按 ID 查询也会失败。这两种情况下,服务端都会返回 `NOT_FOUND`,并提示数据可能尚未索引或已经删除。- 公开 URI 参数接受 `resources` 和 `user` 作用域。访问 session 文件时,使用 `viking://user/{user_id}/sessions/{session_id}`,也可以使用向后兼容的 `viking://session/{session_id}` 别名。`temp`、`queue` 等内部作用域会返回 `INVALID_URI`。diff --git a/docs/zh/concepts/04-viking-uri.md b/docs/zh/concepts/04-viking-uri.mdindex 2e1d0f031..9f0fd58e6 100644--- a/docs/zh/concepts/04-viking-uri.md+++ b/docs/zh/concepts/04-viking-uri.md@@ -50,6 +50,10 @@ viking://{scope}/{path}摒弃传统的扁平化数据库思维,将所有上下文组织为一套文件系统。Agent 不再仅是通过向量搜索来找数据,而是可以通过确定性的路径和标准文件系统指令来定位和浏览数据。每个上下文或目录分配唯一的 URI 标识字符串,格式为 viking://{scope}/{path},让系统能精准定位并访问存储在不同位置的资源。+## 文件 ID++除 URI 之外,每个文件会被自动分配一个稳定的 `id`,作为其在 VikingDB 中向量记录的主键。对于 level 2(常规文件)记录,该 id 按 `md5(f"{account_id}:{uri}")` 确定性计算,由 `stat()` 等元数据接口返回。调用方可凭此 id 直接交叉引用向量索引条目,无需额外查询。id 以 account 为作用域,当文件被移动到其他 URI 时 id 会随之改变(URI 迁移过程中向量记录会重新计算主键)。目录不返回单一 `id`,因为一个目录在多个语义层(L0 abstract、L1 overview、L2)下可能对应多条记录,每条各有自己的 id。+```viking://├── user/diff --git a/openviking/server/routers/content.py b/openviking/server/routers/content.pyindex 4912deeb1..b349a04b1 100644--- a/openviking/server/routers/content.py+++ b/openviking/server/routers/content.py@@ -27,6 +27,7 @@ from openviking.server.error_mapping import map_exceptionfrom openviking.server.identity import RequestContext, Rolefrom openviking.server.models import Responsefrom openviking.server.telemetry import run_operation+from openviking.storage.vector_ids import is_vector_record_idfrom openviking.telemetry import TelemetryRequestfrom openviking_cli.exceptions import InvalidArgumentError, NotFoundError, PermissionDeniedErrorfrom openviking_cli.utils import get_logger@@ -129,12 +130,17 @@ async def read():"""Read file content (L2)."""service = get_service()- uri = validate_request_viking_uri(resolve_path_variables(uri), _ctx)+ # If the argument is a raw 32-hex vector record id, skip URI validation+ # (id lookup + access check happens inside VikingFS.read_file).+ if is_vector_record_id(uri):+ resolved = uri+ else:+ resolved = validate_request_viking_uri(resolve_path_variables(uri), _ctx)try:if raw:- result = await service.fs.read(uri, ctx=_ctx, offset=offset, limit=limit)+ result = await service.fs.read(resolved, ctx=_ctx, offset=offset, limit=limit)else:- result = await service.fs.read_visible(uri, ctx=_ctx, offset=offset, limit=limit)+ result = await service.fs.read_visible(resolved, ctx=_ctx, offset=offset, limit=limit)except AGFSNotFoundError:raise NotFoundError(uri, "file")except AGFSClientError as e:diff --git a/openviking/server/routers/filesystem.py b/openviking/server/routers/filesystem.pyindex c768caa25..2b74754c5 100644--- a/openviking/server/routers/filesystem.py+++ b/openviking/server/routers/filesystem.py@@ -19,6 +19,7 @@ from openviking.server.models import Responsefrom openviking.server.routers.content import SetTagsRequestfrom openviking.server.routers.content import set_tags as content_set_tagsfrom openviking.storage.expr import And, Eq, In+from openviking.storage.vector_ids import is_vector_record_idfrom openviking.storage.vikingdb_manager import VikingDBManagerProxyfrom openviking.utils.tags import normalize_search_tagsfrom openviking_cli.exceptions import NotFoundError@@ -81,6 +82,9 @@ async def ls(description="Sort directory and file groups before applying node_limit",),sort_order: Literal["asc", "desc"] = Query("asc", description="Sort direction"),+ extra_fields: Optional[list[str]] = Query(+ None, description="Extra fields to include: locked, id, count"+ ),_ctx: RequestContext = Depends(get_request_context),):"""List directory contents."""@@ -100,6 +104,7 @@ async def ls(node_limit=actual_node_limit,sort_by=sort_by,sort_order=sort_order,+ extra_fields=extra_fields,)except AGFSNotFoundError:raise NotFoundError(uri, "file")@@ -120,6 +125,9 @@ async def tree(node_limit: int = Query(1000, description="Maximum number of nodes to list"),limit: Optional[int] = Query(None, description="Alias for node_limit"),level_limit: int = Query(3, description="Maximum depth level to traverse"),+ extra_fields: Optional[list[str]] = Query(+ None, description="Extra fields to include: locked, id, count"+ ),_ctx: RequestContext = Depends(get_request_context),):"""Get directory tree."""@@ -136,6 +144,7 @@ async def tree(show_all_hidden=show_all_hidden,node_limit=actual_node_limit,level_limit=level_limit,+ extra_fields=extra_fields,)except AGFSNotFoundError:raise NotFoundError(uri, "file")@@ -149,16 +158,23 @@ async def tree(@router.get("/stat")async def stat(- uri: str = Query(..., description="Viking URI"),+ uri: str = Query(..., description="Viking URI or vector record id (32-char hex)"),_ctx: RequestContext = Depends(get_request_context),):"""Get resource status."""service = get_service()- # Resolve path variables- uri = validate_request_viking_uri(resolve_path_variables(uri), _ctx)+ # If the argument is a raw 32-hex vector record id, skip URI validation+ # (id lookup + access check happens inside VikingFS.stat).+ if is_vector_record_id(uri):+ resolved = uri+ else:+ resolved = validate_request_viking_uri(resolve_path_variables(uri), _ctx)try:- result = await service.fs.stat(uri, ctx=_ctx)- return Response(status="ok", result={**result, "uri": uri})+ result = await service.fs.stat(resolved, ctx=_ctx)+ # URI requests use the canonical validated URI. ID requests are resolved+ # inside VikingFS, which returns the corresponding canonical URI.+ response_uri = result.get("uri", resolved)+ return Response(status="ok", result={**result, "uri": response_uri})except AGFSNotFoundError:raise NotFoundError(uri, "file")except AGFSClientError as e:diff --git a/openviking/server/routers/search.py b/openviking/server/routers/search.pyindex 19038008c..c9341303a 100644--- a/openviking/server/routers/search.py+++ b/openviking/server/routers/search.py@@ -318,6 +318,7 @@ class GlobRequest(BaseModel):pattern: struri: str = "viking://"node_limit: Optional[int] = 256+ extra_fields: Optional[list[str]] = None@router.post("/find")@@ -559,7 +560,11 @@ async def glob(resolved_uri = validate_request_viking_uri(resolve_path_variables(request.uri), _ctx)try:result = await service.fs.glob(- request.pattern, ctx=_ctx, uri=resolved_uri, node_limit=request.node_limit+ request.pattern,+ ctx=_ctx,+ uri=resolved_uri,+ node_limit=request.node_limit,+ extra_fields=request.extra_fields,)except AGFSNotFoundError:raise NotFoundError(resolved_uri or request.pattern, "file")diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.pyindex c1dac36a7..f2a6ce374 100644--- a/openviking/service/fs_service.py+++ b/openviking/service/fs_service.py@@ -30,6 +30,7 @@ from openviking.storage.content_write import ContentWriteCoordinatorfrom openviking.storage.queuefs import SemanticMsg, get_queue_managerfrom openviking.storage.queuefs.semantic_msg import build_semantic_coalesce_keyfrom openviking.storage.queuefs.semantic_ops.freshness_policy import FreshnessAction+from openviking.storage.vector_ids import is_vector_record_idfrom openviking.storage.viking_fs import VikingFSfrom openviking.telemetry import get_current_telemetryfrom openviking.telemetry.request_wait_tracker import get_request_wait_tracker@@ -106,6 +107,17 @@ class FSService:raise NotInitializedError("VikingFS")return self._viking_fs+ async def _resolve_uri(self, uri_or_id: str, ctx: RequestContext) -> str:+ """If ``uri_or_id`` is a 32-char hex vector record id, resolve it to the+ corresponding Viking URI via the vector store. Otherwise return as-is.+ Used so that service-layer helpers (classify_uri, get_skill_name_from_uri,+ visible_content) always see a real URI, even when callers pass an id.+ """+ if not is_vector_record_id(uri_or_id):+ return uri_or_id+ viking_fs = self._ensure_initialized()+ return await viking_fs.resolve_uri(uri_or_id, ctx=ctx)+def _get_watch_manager(self) -> Optional["WatchManager"]:if not self._watch_scheduler:return None@@ -124,6 +136,7 @@ class FSService:level_limit: int = 3,sort_by: Optional[str] = None,sort_order: str = "asc",+ extra_fields: Optional[List[str]] = None,) -> List[Any]:"""List directory contents.@@ -137,10 +150,14 @@ class FSService:node_limit: int = 1000 (maximum number of nodes to list)sort_by: Optional sort field for non-recursive listingssort_order: Sort direction, "asc" or "desc"+ extra_fields: Optional extra fields to include (locked, id, count)"""viking_fs = self._ensure_initialized()+ extra_fields = extra_fields or []- if simple:+ use_simple_paths = simple and not extra_fields++ if use_simple_paths:# Only return URIs — skip expensive abstract fetching to save tokensif recursive:entries = await viking_fs.tree(@@ -172,6 +189,7 @@ class FSService:show_all_hidden=show_all_hidden,node_limit=node_limit,level_limit=level_limit,+ extra_fields=extra_fields,)else:entries = await viking_fs.ls(@@ -183,6 +201,7 @@ class FSService:node_limit=node_limit,sort_by=sort_by,sort_order=sort_order,+ extra_fields=extra_fields,)return entries@@ -568,6 +587,7 @@ class FSService:show_all_hidden: bool = False,node_limit: int = 1000,level_limit: int = 3,+ extra_fields: Optional[List[str]] = None,) -> List[Dict[str, Any]]:"""Get directory tree."""viking_fs = self._ensure_initialized()@@ -579,6 +599,7 @@ class FSService:show_all_hidden=show_all_hidden,node_limit=node_limit,level_limit=level_limit,+ extra_fields=extra_fields,)async def stat(self, uri: str, ctx: RequestContext) -> Dict[str, Any]:@@ -597,10 +618,14 @@ class FSService:return await viking_fs.system_sync_retry(uri, ctx=ctx)async def read(self, uri: str, ctx: RequestContext, offset: int = 0, limit: int = -1) -> str:- """Read file content."""+ """Read file content. Accepts a Viking URI or a 32-char hex vector record id."""viking_fs = self._ensure_initialized()- content = await viking_fs.read_file(uri, ctx=ctx)- skill_name = get_skill_name_from_uri(uri)+ # Resolve ids to URIs so that downstream helpers (get_skill_name_from_uri)+ # always see a real viking:// URI. VikingFS.read_file also resolves, which+ # is harmless defense-in-depth when the input was already a URI.+ resolved_uri = await self._resolve_uri(uri, ctx)+ content = await viking_fs.read_file(resolved_uri, ctx=ctx)+ skill_name = get_skill_name_from_uri(resolved_uri)if skill_name and self._privacy_config_service:current = await self._privacy_config_service.get_current(ctx=ctx,@@ -623,11 +648,16 @@ class FSService:offset: int = 0,limit: int = -1,) -> str:- """Read public content, hiding reserved metadata from memory files."""- if not classify_uri(uri).is_memory:- return await self.read(uri, ctx=ctx, offset=offset, limit=limit)- content = await self.read(uri, ctx=ctx)- return visible_content(content, uri=uri, offset=offset, limit=limit)+ """Read public content, hiding reserved metadata from memory files.+ Accepts a Viking URI or a 32-char hex vector record id.+ """+ # Resolve id to URI before classify_uri / visible_content which expect+ # a real viking:// URI.+ resolved_uri = await self._resolve_uri(uri, ctx)+ if not classify_uri(resolved_uri).is_memory:+ return await self.read(resolved_uri, ctx=ctx, offset=offset, limit=limit)+ content = await self.read(resolved_uri, ctx=ctx)+ return visible_content(content, uri=resolved_uri, offset=offset, limit=limit)async def abstract(self, uri: str, ctx: RequestContext) -> str:"""Read L0 abstract (.abstract.md)."""@@ -668,10 +698,13 @@ class FSService:ctx: RequestContext,uri: str = "viking://",node_limit: Optional[int] = None,+ extra_fields: Optional[List[str]] = None,) -> Dict:"""File pattern matching."""viking_fs = self._ensure_initialized()- return await viking_fs.glob(pattern, uri=uri, node_limit=node_limit, ctx=ctx)+ return await viking_fs.glob(+ pattern, uri=uri, node_limit=node_limit, ctx=ctx, extra_fields=extra_fields+ )async def read_file_bytes(self, uri: str, ctx: RequestContext) -> bytes:"""Read file as raw bytes."""diff --git a/openviking/storage/collection_schemas.py b/openviking/storage/collection_schemas.pyindex 33499acff..8679227fe 100644--- a/openviking/storage/collection_schemas.py+++ b/openviking/storage/collection_schemas.py@@ -27,6 +27,7 @@ from openviking.storage.errors import ()from openviking.storage.queuefs.embedding_msg import EmbeddingMsgfrom openviking.storage.queuefs.named_queue import DequeueHandlerBase+from openviking.storage.vector_ids import vector_record_idfrom openviking.storage.viking_vector_index_backend import (VIKINGDB_CONTENT_MAX_SIZE,VikingVectorIndexBackend,@@ -539,20 +540,6 @@ class TextEmbeddingHandler(DequeueHandlerBase):with cls._request_stats_lock:return cls._request_stats_by_telemetry_id.pop(telemetry_id, None)- @staticmethod- def _seed_uri_for_id(uri: str, level: Any) -> str:- """Build deterministic id seed URI from canonical uri + hierarchy level."""- try:- level_int = int(level)- except (TypeError, ValueError):- level_int = 2-- if level_int == 0:- return uri if uri.endswith("/.abstract.md") else f"{uri}/.abstract.md"- if level_int == 1:- return uri if uri.endswith("/.overview.md") else f"{uri}/.overview.md"- return uri-@staticmethoddef _embedding_msg_log_context(embedding_msg: Optional[EmbeddingMsg]) -> str:"""Return the URI allowed in embedding logs."""@@ -835,9 +822,9 @@ class TextEmbeddingHandler(DequeueHandlerBase):# Ensure vector DB has deterministic IDs per semantic layer.uri = inserted_data.get("uri")if uri:- seed_uri = self._seed_uri_for_id(uri, inserted_data.get("level", 2))- id_seed = f"{account_id}:{seed_uri}"- inserted_data["id"] = hashlib.md5(id_seed.encode("utf-8")).hexdigest()+ inserted_data["id"] = vector_record_id(+ account_id, uri, inserted_data.get("level", 2)+ )if self._vikingdb.uses_content_field:inserted_data["content"] = await self._materialize_content(diff --git a/openviking/storage/ovpack/vectors.py b/openviking/storage/ovpack/vectors.pyindex d7cb40233..84d8e5e02 100644--- a/openviking/storage/ovpack/vectors.py+++ b/openviking/storage/ovpack/vectors.py@@ -4,7 +4,6 @@from __future__ import annotations-import hashlibimport structimport zipfilefrom typing import Any@@ -23,6 +22,7 @@ from openviking.storage.ovpack.format import (sha256_hex,)from openviking.storage.ovpack.manifest import manifest_dense_info, manifest_entry_target_uri+from openviking.storage.vector_ids import vector_record_idfrom openviking.storage.ovpack.validation import dense_record_count, record_dense_reffrom openviking.utils.time_utils import get_current_timestampfrom openviking_cli.exceptions import InvalidArgumentError@@ -256,17 +256,7 @@ def choose_vector_restore_action(def _vector_record_id(target_uri: str, level: int, ctx: RequestContext) -> str:- if level == 0:- seed_uri = (- target_uri if target_uri.endswith("/.abstract.md") else f"{target_uri}/.abstract.md"- )- elif level == 1:- seed_uri = (- target_uri if target_uri.endswith("/.overview.md") else f"{target_uri}/.overview.md"- )- else:- seed_uri = target_uri- return hashlib.md5(f"{ctx.account_id}:{seed_uri}".encode("utf-8")).hexdigest()+ return vector_record_id(ctx.account_id, target_uri, level)async def _upsert_vector_snapshot_record(diff --git a/openviking/storage/vector_ids.py b/openviking/storage/vector_ids.pynew file mode 100644index 000000000..c29d36e2d--- /dev/null+++ b/openviking/storage/vector_ids.py@@ -0,0 +1,60 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Deterministic vector record ID generation.++Every vector record in VikingDB has a stable primary key derived from+``account_id``, the resource ``uri``, and the semantic ``level``:++- Level 0 (directory abstract): seed URI is ``{uri}/.abstract.md``+- Level 1 (directory overview): seed URI is ``{uri}/.overview.md``+- Level 2 (file / chunk): seed URI is the ``uri`` itself++The final record ID is ``md5(f"{account_id}:{seed_uri}")``.++This is the single source of truth for computing vector record IDs.+All code paths that need to derive or re-derive a record ID MUST use+``vector_record_id`` / ``seed_uri_for_vector_id`` from this module rather than+re-implementing the hash inline, so that future changes to the ID scheme stay+consistent.+"""++import hashlib+import re+from typing import Any, Optional, Tuple++_VECTOR_ID_RE = re.compile(r"^[0-9a-f]{32}$")+++def is_vector_record_id(value: str) -> bool:+ """Return True if ``value`` looks like a 32-char hex MD5 vector record ID."""+ return bool(_VECTOR_ID_RE.fullmatch(value.strip()))+++def seed_uri_for_vector_id(uri: str, level: Any) -> str:+ """Return the seed URI used to compute a vector record ID.++ For L0/L1 semantic sidecars the appropriate suffix is appended if not+ already present; for L2 (regular files / chunks) the URI is returned+ unchanged.+ """+ try:+ level_int = int(level)+ except (TypeError, ValueError):+ level_int = 2++ if level_int == 0:+ return uri if uri.endswith("/.abstract.md") else f"{uri}/.abstract.md"+ if level_int == 1:+ return uri if uri.endswith("/.overview.md") else f"{uri}/.overview.md"+ return uri+++def vector_record_id(account_id: str, uri: str, level: Any = 2) -> str:+ """Return the deterministic vector DB primary key for (account_id, uri, level).++ This MUST match the ID produced at upsert time so that callers (stat, ovpack,+ migrations, URI remapping) can compute the same key without a round-trip to+ the database.+ """+ seed_uri = seed_uri_for_vector_id(uri, level)+ return hashlib.md5(f"{account_id}:{seed_uri}".encode("utf-8")).hexdigest()diff --git a/openviking/storage/vector_migration.py b/openviking/storage/vector_migration.pyindex 806233a3f..0e33820d2 100644--- a/openviking/storage/vector_migration.py+++ b/openviking/storage/vector_migration.py@@ -4,13 +4,13 @@from __future__ import annotations-import hashlibfrom dataclasses import dataclass, fieldfrom typing import Anyfrom openviking.core.namespace import context_type_for_uri, owner_fields_for_urifrom openviking.server.identity import RequestContext, Rolefrom openviking.storage.expr import And, Contains, Eq, Or, PathScope+from openviking.storage.vector_ids import vector_record_idfrom openviking.utils.time_utils import get_current_timestampfrom openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils.uri import VikingURI@@ -58,22 +58,8 @@ def _root_ctx(account_id: str) -> RequestContext:return RequestContext(user=UserIdentifier(account_id, "default"), role=Role.ROOT)-def _seed_uri_for_id(uri: str, level: Any) -> str:- try:- level_int = int(level)- except (TypeError, ValueError):- level_int = 2-- if level_int == 0:- return uri if uri.endswith("/.abstract.md") else f"{uri}/.abstract.md"- if level_int == 1:- return uri if uri.endswith("/.overview.md") else f"{uri}/.overview.md"- return uri--def _vector_record_id(account_id: str, uri: str, level: Any) -> str:- seed_uri = _seed_uri_for_id(uri, level)- return hashlib.md5(f"{account_id}:{seed_uri}".encode("utf-8")).hexdigest()+ return vector_record_id(account_id, uri, level)def _has_vector_payload(record: dict[str, Any]) -> bool:diff --git a/openviking/storage/viking_fs/_ops.py b/openviking/storage/viking_fs/_ops.pyindex b9a79cebe..4def75a05 100644--- a/openviking/storage/viking_fs/_ops.py+++ b/openviking/storage/viking_fs/_ops.py@@ -20,6 +20,7 @@ from openviking.server.identity import RequestContextfrom openviking.storage.acl import AclAction, is_acl_urifrom openviking.storage.expr import PathScopefrom openviking.storage.internal_names import STORAGE_INTERNAL_ENTRY_NAMES+from openviking.storage.vector_ids import is_vector_record_id, vector_record_idfrom openviking.storage.viking_fs._base import (_ABSTRACT_WORKER_COUNT,LS_ALL_NODES,@@ -60,9 +61,10 @@ class _OpsMixin:size: int = -1,ctx: Optional[RequestContext] = None,) -> bytes:- """Read file"""- await self._ensure_access(uri, ctx)+ """Read file. Accepts a Viking URI or a 32-char hex vector record id."""real_ctx = self._ctx_or_default(ctx)+ uri = await self.resolve_uri(uri, real_ctx)+ await self._ensure_access(uri, ctx)primary_path = self._uri_to_path(uri, ctx=ctx)# Decryption + offset/size slicing now happen inside the ragfs encryption layer@@ -602,6 +604,25 @@ class _OpsMixin:finally:await self._async_agfs.pathlock_release(child_lease)+ async def resolve_uri(self, uri_or_id: str, ctx: RequestContext) -> str:+ """If ``uri_or_id`` is a 32-char hex vector record id, look it up in the+ vector store and return the corresponding URI. Otherwise return it as-is.+ Account scoping is enforced by the vector store's get() post-filter.+ """+ if not is_vector_record_id(uri_or_id):+ return uri_or_id+ missing_reason = "The data may not have been indexed yet or may have been deleted"+ vector_store = self._get_vector_store()+ if vector_store is None:+ raise NotFoundError(uri_or_id, "file", reason=missing_reason)+ records = await vector_store.get([uri_or_id], ctx=ctx)+ if not records:+ raise NotFoundError(uri_or_id, "file", reason=missing_reason)+ resolved = records[0].get("uri")+ if not resolved or not isinstance(resolved, str):+ raise NotFoundError(uri_or_id, "file", reason=missing_reason)+ return resolved+async def stat(self, uri: str, ctx: Optional[RequestContext] = None, skip_count: bool = False) -> Dict[str, Any]:@@ -610,24 +631,31 @@ class _OpsMixin:example: {'name': 'resources', 'size': 128, 'mode': 2147484141, 'modTime': '2026-02-10T21:26:02.934376379+08:00', 'isDir': True, 'isLocked': False, 'count': 42, 'meta': {'Name': 'localfs', 'Type': 'local', 'Content': {'local_path': '...'}}}- Extra field:+ Extra fields:isLocked (bool): Whether the path is currently held by a path lock(either the path itself or any ancestor directory). ReturnsFalse when the pathlock system is not enabled or the lookupfails.+ id (str): For files (non-directories), the deterministic VikingDB+ vector record primary key (level 2), computed as+ ``md5(f"{account_id}:{uri}")``. This matches the ID used in the+ vector collection so callers can cross-reference without an+ extra lookup. Not present for directories (which may have+ multiple records across L0/L1/L2 levels).count (int): For directories, the number of nodes in the vector indexunder this directory (including subdirectories). For files, thisfield is not included.Args:- uri: Viking URI+ uri: Viking URI, or a 32-char hex vector record id (resolves to URI via vector store)ctx: Request contextskip_count: If True, skip the vector_store.count() call for directories.Use this when the count field is not needed (e.g. in grep) to avoidan extra VikingDB API call."""- await self._ensure_access(uri, ctx)real_ctx = self._ctx_or_default(ctx)+ uri = await self.resolve_uri(uri, real_ctx)+ await self._ensure_access(uri, ctx)primary_path = self._uri_to_path(uri, ctx=ctx)path = primary_pathlast_not_found: Optional[Exception] = None@@ -656,7 +684,13 @@ class _OpsMixin:}raise NotFoundError(uri, "file") from last_not_foundif isinstance(result, dict):+ result["uri"] = uriresult["isLocked"] = await self._is_path_locked_async(path)+ # Add deterministic vector record id for files (level 2).+ # This matches the ID used in VikingDB so callers can cross-reference+ # vector records without an extra lookup.+ if not result.get("isDir", False):+ result["id"] = vector_record_id(real_ctx.account_id, uri, level=2)# Add count for directories if vector store availableif not skip_count and result.get("isDir", False):try:@@ -699,11 +733,20 @@ class _OpsMixin:uri: str = "viking://",node_limit: Optional[int] = None,ctx: Optional[RequestContext] = None,+ extra_fields: Optional[List[str]] = None,) -> Dict:- """File pattern matching, supports **/*.md recursive."""+ """File pattern matching, supports **/*.md recursive.++ When extra_fields is None (default), returns URI strings.+ When extra_fields is a list (possibly empty), returns entry dicts; entries in the list+ request additional augmentation (locked, id, count). An empty list still returns dicts+ (with name/uri/size/mode/mtime/isDir populated from stat) for CLI table rendering.+ """_ensure_non_empty_search_query(pattern)await self._ensure_access(uri, ctx)real_ctx = self._ctx_or_default(ctx)+ return_entries = extra_fields is not None+ aug_fields = list(extra_fields) if extra_fields else []primary_path = self._uri_to_path(uri, ctx=ctx)path: Optional[str] = Nonefor candidate_path in self._read_paths(uri, ctx=ctx):@@ -730,10 +773,9 @@ class _OpsMixin:continuation_token=continuation_token,)- # (acl_uri, match_uri): ACL lookups keep the bare uri, while the uri we- # hand back marks directories with a trailing slash so callers can tell- # them apart -- the flat `matches` list carries no other type signal.- page_matches: List[tuple[str, str]] = []+ # ACL lookups and metadata reads keep the bare URI. Only flat string+ # results need a trailing slash to identify directory matches.+ page_matches: List[tuple[str, str, Dict[str, Any]]] = []for entry in page.get("entries", []):if not self._is_path_entry_visible(entry["path"],@@ -751,30 +793,42 @@ class _OpsMixin:ctx=ctx,)match_uri = _glob_match_uri(entry_uri, entry.get("is_dir"))- if self.acl_manager is None:- matches.append(match_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, match_uri, entry))- page_matches.append((entry_uri, match_uri))-- if self.acl_manager is not None:- access = await self._can_access_many(- [acl_uri for acl_uri, _ in page_matches], real_ctx- )- for acl_uri, match_uri in page_matches:- if not access.get(acl_uri, False):- continue+ access = await self._can_access_many(+ [entry_uri for entry_uri, _, _ in page_matches], real_ctx+ )+ for entry_uri, match_uri, entry in page_matches:+ if not access.get(entry_uri, False):+ continue+ if return_entries:+ try:+ entry_stat = await self.stat(entry_uri, ctx=ctx, skip_count=True)+ except NotFoundError:+ name = entry.get("name") or entry["path"].rsplit("/", 1)[-1]+ entry_stat = {+ "uri": entry_uri,+ "name": name,+ "isDir": bool(entry.get("is_dir", False)),+ }+ entry_stat.setdefault("uri", entry_uri)+ matches.append(entry_stat)+ else:matches.append(match_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:+ if return_entries:+ await self._augment_entries_extra_fields(matches, aug_fields, ctx=ctx)+ return {"matches": matches, "count": len(matches)}if node_limit is not None and node_limit > 0 and len(matches) >= node_limit:+ if return_entries:+ await self._augment_entries_extra_fields(matches, aug_fields, ctx=ctx)return {"matches": matches, "count": len(matches)}continuation_token = page.get("next_token")if not continuation_token:break+ if return_entries:+ await self._augment_entries_extra_fields(matches, aug_fields, ctx=ctx)return {"matches": matches, "count": len(matches)}async def _batch_fetch_abstracts(@@ -841,6 +895,7 @@ class _OpsMixin:node_limit: Optional[int] = 1000,level_limit: Optional[int] = 3,ctx: Optional[RequestContext] = None,+ extra_fields: Optional[List[str]] = None,) -> List[Dict[str, Any]]:"""Recursively list all contents (includes rel_path).@@ -852,6 +907,7 @@ class _OpsMixin:show_all_hidden: bool = False (list all hidden files, like -a)node_limit: int | None = 1000 (maximum number of nodes to list, None means unlimited)level_limit: int | None = 3 (maximum depth level to traverse, None means unlimited)+ extra_fields: optional list of extra fields to include: "locked", "id", "count"output="original"[{'name': '.abstract.md', 'size': 100, 'mode': 420, 'modTime': '2026-02-11T16:52:16.256334192+08:00', 'isDir': False, 'rel_path': '.abstract.md', 'uri': 'viking://resources...'}]@@ -860,14 +916,18 @@ class _OpsMixin:[{'uri': 'viking://resources...', 'size': 100, 'isDir': False, 'modTime': '2026-02-11T08:52:16.256Z', 'rel_path': '.abstract.md', 'abstract': "..."}]"""await self._ensure_access(uri, ctx)+ extra_fields = extra_fields or []if output == "original":- return await self._tree_original(uri, show_all_hidden, node_limit, level_limit, ctx=ctx)+ entries = await self._tree_original(uri, show_all_hidden, node_limit, level_limit, ctx=ctx)elif output == "agent":- return await self._tree_agent(+ entries = await self._tree_agent(uri, abs_limit, show_all_hidden, node_limit, level_limit, ctx=ctx)else:raise ValueError(f"Invalid output format: {output}")+ if extra_fields and output == "original":+ await self._augment_entries_extra_fields(entries, extra_fields, ctx=ctx)+ return entriesasync def _tree_original(self,@@ -1094,15 +1154,16 @@ class _OpsMixin:"""Read single file, optionally sliced by line range.Args:- uri: Viking URI+ uri: Viking URI, or a 32-char hex vector record id (resolves to URI via vector store)offset: Starting line number (0-indexed). Default 0.limit: Number of lines to read. -1 means read to end. Default -1.Raises:FileNotFoundError: If the file does not exist."""- await self._ensure_access(uri, ctx)real_ctx = self._ctx_or_default(ctx)+ uri = await self.resolve_uri(uri, real_ctx)+ await self._ensure_access(uri, ctx)primary_path = self._uri_to_path(uri, ctx=ctx)# Verify the file exists before reading, because AGFS read returns# empty bytes for non-existent files instead of raising an error.@@ -1150,9 +1211,10 @@ class _OpsMixin:uri: str,ctx: Optional[RequestContext] = None,) -> bytes:- """Read single binary file."""- await self._ensure_access(uri, ctx)+ """Read single binary file. Accepts a Viking URI or a 32-char hex vector record id."""real_ctx = self._ctx_or_default(ctx)+ uri = await self.resolve_uri(uri, real_ctx)+ await self._ensure_access(uri, ctx)primary_path = self._uri_to_path(uri, ctx=ctx)last_not_found: Optional[Exception] = Nonefor path in self._read_paths(uri, ctx=ctx):@@ -1263,6 +1325,7 @@ class _OpsMixin:sort_by: Optional[str] = None,sort_order: str = "asc",ctx: Optional[RequestContext] = None,+ extra_fields: Optional[List[str]] = None,) -> List[Dict[str, Any]]:"""List directory contents (URI version).@@ -1275,6 +1338,7 @@ class _OpsMixin:node_limit: int = 1000 (maximum number of nodes to list)sort_by: Optional sort field, "name" or "mtime"sort_order: Sort direction, "asc" or "desc"+ extra_fields: optional list of extra fields to include: "locked", "id", "count"output="original"[{'name': '.abstract.md', 'size': 100, 'mode': 420, 'modTime': '2026-02-11T16:52:16.256334192+08:00', 'isDir': False, 'meta': {'Name': 'localfs', 'Type': 'local', 'Content': None}, 'uri': 'viking://resources/.abstract.md'}]@@ -1283,12 +1347,13 @@ class _OpsMixin:[{'name': '.abstract.md', 'size': 100, 'modTime': '2026-02-11T08:52:16.256Z', 'isDir': False, 'uri': 'viking://resources/.abstract.md', 'abstract': "..."}]"""await self._ensure_access(uri, ctx)+ extra_fields = extra_fields or []if sort_by not in {None, "name", "mtime"}:raise ValueError("sort_by must be 'name' or 'mtime'")if sort_order not in {"asc", "desc"}:raise ValueError("sort_order must be 'asc' or 'desc'")if output == "original":- return await self._ls_original(+ entries = await self._ls_original(uri,show_all_hidden,node_limit,@@ -1297,7 +1362,7 @@ class _OpsMixin:ctx=ctx,)elif output == "agent":- return await self._ls_agent(+ entries = await self._ls_agent(uri,abs_limit,show_all_hidden,@@ -1308,6 +1373,9 @@ class _OpsMixin:)else:raise ValueError(f"Invalid output format: {output}")+ if extra_fields and output == "original":+ await self._augment_entries_extra_fields(entries, extra_fields, ctx=ctx)+ return entries@staticmethoddef _ls_entry_mtime(entry: Dict[str, Any]) -> Optional[float]:@@ -1492,6 +1560,61 @@ class _OpsMixin:)return browsable+ async def _augment_entries_extra_fields(+ self,+ entries: List[Dict[str, Any]],+ extra_fields: List[str],+ ctx: Optional[RequestContext] = None,+ ) -> None:+ """Augment entries in-place with extra fields (locked, id, count)."""+ real_ctx = self._ctx_or_default(ctx)+ need_locked = "locked" in extra_fields+ need_id = "id" in extra_fields+ need_count = "count" in extra_fields+ vector_store = self._get_vector_store() if need_count else None++ lock_paths: List[tuple[int, str]] = []+ for i, entry in enumerate(entries):+ # ACL directory enumeration may expose only a name/type placeholder.+ # Do not enrich denied entries with metadata from inaccessible paths.+ if entry.get("access") == "denied":+ continue+ entry_uri = entry.get("uri", "")+ is_dir = entry.get("isDir", False)+ if need_locked:+ path = self._try_uri_to_path(entry_uri, ctx=ctx)+ if path is not None:+ lock_paths.append((i, path))+ if need_id and not is_dir:+ entry["id"] = vector_record_id(real_ctx.account_id, entry_uri, level=2)+ if need_count and is_dir and vector_store and entry_uri:+ try:+ if not may_include_hidden_actor_peers(entry_uri, real_ctx):+ filter_expr = PathScope("uri", entry_uri, depth=-1)+ entry["count"] = await vector_store.count(+ filter=filter_expr, ctx=real_ctx,+ )+ except Exception as e:+ logger.warning(+ f"[VikingFS] Failed to count nodes for {entry_uri}: {e}"+ )++ if need_locked and lock_paths:+ for i, path in lock_paths:+ try:+ entries[i]["isLocked"] = await self._is_path_locked_async(path)+ except Exception:+ entries[i]["isLocked"] = False++ def _try_uri_to_path(+ self, uri: str, ctx: Optional[RequestContext] = None+ ) -> Optional[str]:+ """Best-effort URI to path conversion; returns None on failure."""+ try:+ return self._uri_to_path(uri, ctx=ctx)+ except Exception:+ return None+async def move_file(self,from_uri: str,diff --git a/openviking/storage/viking_vector_index_backend.py b/openviking/storage/viking_vector_index_backend.pyindex 2c3ae592a..4d8cf1202 100644--- a/openviking/storage/viking_vector_index_backend.py+++ b/openviking/storage/viking_vector_index_backend.py@@ -20,6 +20,7 @@ from openviking.storage.acl import (acl_principals,)from openviking.storage.expr import And, Eq, FilterExpr, In, Or, PathScope, RawDSL+from openviking.storage.vector_ids import vector_record_idfrom openviking.storage.vectordb.collection.collection import Collectionfrom openviking.storage.vectordb.collection.result import UpdateResultfrom openviking.storage.vectordb.utils.logging_init import init_cpp_logging@@ -1473,8 +1474,6 @@ class VikingVectorIndexBackend:new_uri: str,levels: Optional[List[int]] = None,) -> bool:- import hashlib-conds: List[FilterExpr] = [Eq("uri", uri), Eq("account_id", ctx.account_id)]if levels:conds.append(In("level", levels))@@ -1507,13 +1506,6 @@ class VikingVectorIndexBackend:)return False- def _seed_uri_for_id(uri: str, level: int) -> str:- if level == 0:- return uri if uri.endswith("/.abstract.md") else f"{uri}/.abstract.md"- if level == 1:- return uri if uri.endswith("/.overview.md") else f"{uri}/.overview.md"- return uri-updated_records: List[Dict[str, Any]] = []ids_to_delete: List[str] = []for record in full_records:@@ -1525,9 +1517,7 @@ class VikingVectorIndexBackend:except (TypeError, ValueError):level = 2- seed_uri = _seed_uri_for_id(new_uri, level)- id_seed = f"{ctx.account_id}:{seed_uri}"- new_id = hashlib.md5(id_seed.encode("utf-8")).hexdigest()+ new_id = vector_record_id(ctx.account_id, new_uri, level)updated = {**record,diff --git a/openviking_cli/doctor.py b/openviking_cli/doctor.pyindex 4e6d23b03..0d1b621b7 100644--- a/openviking_cli/doctor.py+++ b/openviking_cli/doctor.py@@ -351,7 +351,15 @@ def check_vlm() -> tuple[bool, str, Optional[str]]:raw_vlm = data.get("vlm", {})normalized_vlm = VLMConfig.sync_provider_backend(dict(raw_vlm))- vlm = VLMConfig.model_validate(normalized_vlm)+ try:+ # Doctor owns the runtime credential probe below. Skip only the model's+ # Codex availability check while retaining all structural validation.+ vlm = VLMConfig.model_validate(+ normalized_vlm,+ context={"skip_codex_auth_availability": True},+ )+ except Exception as exc:+ return False, f"Invalid VLM config: {exc}", "Fix vlm section in ov.conf"_, provider = vlm.get_provider_config()model = vlm.model or ""diff --git a/openviking_cli/exceptions.py b/openviking_cli/exceptions.pyindex 9305a2c6d..68b934e3d 100644--- a/openviking_cli/exceptions.py+++ b/openviking_cli/exceptions.py@@ -54,13 +54,21 @@ class UnsupportedDirectoryFilesError(InvalidArgumentError):class NotFoundError(OpenVikingError):"""Resource not found."""- def __init__(self, resource: str, resource_type: str = "resource"):+ def __init__(+ self,+ resource: str,+ resource_type: str = "resource",+ reason: Optional[str] = None,+ ):details = {"type": resource_type}if resource:details["resource"] = resourcemessage = f"{resource_type.capitalize()} not found: {resource}"else:message = f"{resource_type.capitalize()} not found"+ if reason:+ details["reason"] = reason+ message = f"{message}. {reason}"super().__init__(message, code="NOT_FOUND", details=details)diff --git a/openviking_cli/utils/config/vlm_config.py b/openviking_cli/utils/config/vlm_config.pyindex df555929d..f77ac5357 100644--- a/openviking_cli/utils/config/vlm_config.py+++ b/openviking_cli/utils/config/vlm_config.py@@ -7,7 +7,7 @@ import weakreffrom pathlib import Pathfrom typing import Any, Awaitable, Callable, Dict, List, Optional, Union-from pydantic import BaseModel, Field, PrivateAttr, model_validator+from pydantic import BaseModel, Field, PrivateAttr, ValidationInfo, model_validatordef _load_codex_auth_module():@@ -224,7 +224,7 @@ class VLMConfig(BaseModel):return data@model_validator(mode="after")- def validate_config(self):+ def validate_config(self, info: ValidationInfo):"""Validate configuration completeness and consistency"""# Validate recursive backup BEFORE normalizing credentials (which clears backup)self._validate_no_recursive_backup()@@ -232,6 +232,10 @@ class VLMConfig(BaseModel):self._migrate_legacy_config()self._normalize_credentials()+ skip_codex_auth_availability = bool(+ info.context and info.context.get("skip_codex_auth_availability")+ )+if self._has_any_config():if not self.model:raise ValueError("VLM configuration requires 'model' to be set")@@ -243,7 +247,11 @@ class VLMConfig(BaseModel):has_codex_auth_available = (_load_codex_auth_module().has_codex_auth_available)- if not cred.api_key and not has_codex_auth_available():+ if (+ not cred.api_key+ and not skip_codex_auth_availability+ and not has_codex_auth_available()+ ):raise ValueError(f"Credential {i} ({cred.id or 'unnamed'}): requires Codex OAuth credentials in ~/.openviking/codex_auth.json")@@ -258,7 +266,11 @@ class VLMConfig(BaseModel):provider_name = self._resolve_provider_name()if provider_name == "openai-codex":has_codex_auth_available = _load_codex_auth_module().has_codex_auth_available- if not self._get_effective_api_key() and not has_codex_auth_available():+ if (+ not self._get_effective_api_key()+ and not skip_codex_auth_availability+ and not has_codex_auth_available()+ ):raise ValueError("VLM configuration requires Codex OAuth credentials in ~/.openviking/codex_auth.json or an importable Codex CLI auth file")diff --git a/scripts/maintenance/vikingdb_content_backfill/backfill_vikingdb_content.py b/scripts/maintenance/vikingdb_content_backfill/backfill_vikingdb_content.pyindex a561badc3..06532d4d1 100644--- a/scripts/maintenance/vikingdb_content_backfill/backfill_vikingdb_content.py+++ b/scripts/maintenance/vikingdb_content_backfill/backfill_vikingdb_content.py@@ -5,7 +5,6 @@ from __future__ import annotationsimport argparseimport asyncio-import hashlibimport jsonimport sysfrom dataclasses import dataclass@@ -17,6 +16,7 @@ from openviking.core.namespace import context_type_for_uri, owner_fields_for_urifrom openviking.server.identity import RequestContext, Rolefrom openviking.storage.vectordb_adapters import create_collection_adapterfrom openviking.storage.vectordb_adapters.base import _truncate_text_field+from openviking.storage.vector_ids import vector_record_idfrom openviking.storage.viking_fs import VikingFSfrom openviking.utils.agfs_utils import (RagfsBindingConfig,@@ -27,26 +27,6 @@ from openviking.utils.time_utils import parse_iso_datetimefrom openviking_cli.session.user_id import UserIdentifier-def seed_uri_for_level(uri: str, level: Any) -> str:- """Build the deterministic ID seed URI used by embedding writes."""- try:- level_int = int(level)- except (TypeError, ValueError):- level_int = 2-- if level_int == 0:- return uri if uri.endswith("/.abstract.md") else f"{uri}/.abstract.md"- if level_int == 1:- return uri if uri.endswith("/.overview.md") else f"{uri}/.overview.md"- return uri---def vector_record_id(account_id: str, uri: str, level: Any) -> str:- """Return the deterministic vector record ID for account, URI, and level."""- seed_uri = seed_uri_for_level(uri, level)- return hashlib.md5(f"{account_id}:{seed_uri}".encode("utf-8")).hexdigest()--def has_empty_content(record: dict[str, Any]) -> bool:"""Return whether a vector record needs content backfill."""value = record.get("content")diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.pyindex f75b88a14..ca8bb6ebd 100644--- a/sdk/python/openviking_sdk/client.py+++ b/sdk/python/openviking_sdk/client.py@@ -151,6 +151,14 @@ class VikingURI:cleaned = cleaned[1:]return f"viking://{cleaned}"+ @staticmethod+ def normalize_file_reference(uri_or_id: str) -> str:+ """Normalize a URI while preserving record IDs for read-only file lookup APIs."""+ cleaned = uri_or_id.strip()+ if len(cleaned) == 32 and all(char in "0123456789abcdef" for char in cleaned):+ return cleaned+ return VikingURI.normalize(uri_or_id)+class Session:def __init__(self, client: "AsyncHTTPClient", session_id: str):@@ -648,7 +656,8 @@ class AsyncHTTPClient:if exc_class == NotFoundError:resource = details.get("resource", "") if details else ""resource_type = details.get("type", "resource") if details else "resource"- raise exc_class(resource, resource_type)+ reason = details.get("reason") if details else None+ raise exc_class(resource, resource_type, reason=reason)if exc_class == AlreadyExistsError:resource = details.get("resource", "") if details else ""resource_type = details.get("type", "resource") if details else "resource"@@ -1049,6 +1058,7 @@ class AsyncHTTPClient:node_limit: int = 1000,sort_by: Optional[str] = None,sort_order: str = "asc",+ extra_fields: Optional[List[str]] = None,) -> List[Any]:params: Dict[str, Any] = {"uri": VikingURI.normalize(uri),@@ -1062,6 +1072,8 @@ class AsyncHTTPClient:if sort_by is not None:params["sort_by"] = sort_byparams["sort_order"] = sort_order+ if extra_fields:+ params["extra_fields"] = list(extra_fields)response = await self._request("GET","/api/v1/fs/ls",@@ -1077,24 +1089,30 @@ class AsyncHTTPClient:show_all_hidden: bool = False,node_limit: int = 1000,level_limit: int = 3,+ extra_fields: Optional[List[str]] = None,) -> List[Dict[str, Any]]:+ params: Dict[str, Any] = {+ "uri": VikingURI.normalize(uri),+ "output": output,+ "abs_limit": abs_limit,+ "show_all_hidden": show_all_hidden,+ "node_limit": node_limit,+ "level_limit": level_limit,+ }+ if extra_fields:+ params["extra_fields"] = list(extra_fields)response = await self._request("GET","/api/v1/fs/tree",- params={- "uri": VikingURI.normalize(uri),- "output": output,- "abs_limit": abs_limit,- "show_all_hidden": show_all_hidden,- "node_limit": node_limit,- "level_limit": level_limit,- },+ params=params,)return self._handle_response(response)async def stat(self, uri: str) -> Dict[str, Any]:response = await self._request(- "GET", "/api/v1/fs/stat", params={"uri": VikingURI.normalize(uri)}+ "GET",+ "/api/v1/fs/stat",+ params={"uri": VikingURI.normalize_file_reference(uri)},)return self._handle_response(response)@@ -1136,7 +1154,11 @@ class AsyncHTTPClient:response = await self._request("GET","/api/v1/content/read",- params={"uri": VikingURI.normalize(uri), "offset": offset, "limit": limit},+ params={+ "uri": VikingURI.normalize_file_reference(uri),+ "offset": offset,+ "limit": limit,+ },)return self._handle_response(response)@@ -1146,7 +1168,7 @@ class AsyncHTTPClient:"GET","/api/v1/content/read",params={- "uri": VikingURI.normalize(uri),+ "uri": VikingURI.normalize_file_reference(uri),"offset": offset,"limit": limit,"raw": True,@@ -1398,15 +1420,19 @@ class AsyncHTTPClient:pattern: str,uri: str = "viking://",node_limit: int = 256,+ extra_fields: Optional[List[str]] = None,) -> Dict[str, Any]:+ json_body: Dict[str, Any] = {+ "pattern": pattern,+ "uri": VikingURI.normalize(uri),+ "node_limit": node_limit,+ }+ if extra_fields is not None:+ json_body["extra_fields"] = list(extra_fields)response = await self._request("POST","/api/v1/search/glob",- json={- "pattern": pattern,- "uri": VikingURI.normalize(uri),- "node_limit": node_limit,- },+ json=json_body,)return self._handle_response(response)@@ -2329,6 +2355,7 @@ class SyncHTTPClient:node_limit: int = 1000,sort_by: Optional[str] = None,sort_order: str = "asc",+ extra_fields: Optional[List[str]] = None,) -> List[Any]:return run_async(self._async_client.ls(@@ -2341,6 +2368,7 @@ class SyncHTTPClient:node_limit=node_limit,sort_by=sort_by,sort_order=sort_order,+ extra_fields=extra_fields,))@@ -2352,6 +2380,7 @@ class SyncHTTPClient:show_all_hidden: bool = False,node_limit: int = 1000,level_limit: int = 3,+ extra_fields: Optional[List[str]] = None,) -> List[Dict[str, Any]]:return run_async(self._async_client.tree(@@ -2361,6 +2390,7 @@ class SyncHTTPClient:show_all_hidden=show_all_hidden,node_limit=node_limit,level_limit=level_limit,+ extra_fields=extra_fields,))@@ -2539,8 +2569,13 @@ class SyncHTTPClient:pattern: str,uri: str = "viking://",node_limit: int = 256,+ extra_fields: Optional[List[str]] = None,) -> Dict[str, Any]:- return run_async(self._async_client.glob(pattern, uri=uri, node_limit=node_limit))+ return run_async(+ self._async_client.glob(+ pattern, uri=uri, node_limit=node_limit, extra_fields=extra_fields+ )+ )def create_session(self,diff --git a/sdk/python/openviking_sdk/errors.py b/sdk/python/openviking_sdk/errors.pyindex 14075c8cc..d973d7ad6 100644--- a/sdk/python/openviking_sdk/errors.py+++ b/sdk/python/openviking_sdk/errors.py@@ -26,13 +26,21 @@ class InvalidURIError(InvalidArgumentError):class NotFoundError(OpenVikingError):- def __init__(self, resource: str, resource_type: str = "resource"):+ def __init__(+ self,+ resource: str,+ resource_type: str = "resource",+ reason: Optional[str] = None,+ ):details = {"type": resource_type}if resource:details["resource"] = resourcemessage = f"{resource_type.capitalize()} not found: {resource}"else:message = f"{resource_type.capitalize()} not found"+ if reason:+ details["reason"] = reason+ message = f"{message}. {reason}"super().__init__(message, code="NOT_FOUND", details=details)diff --git a/sdk/python/tests/test_async_client_behaviors.py b/sdk/python/tests/test_async_client_behaviors.pyindex 77310b1d3..909802b27 100644--- a/sdk/python/tests/test_async_client_behaviors.py+++ b/sdk/python/tests/test_async_client_behaviors.py@@ -1163,6 +1163,63 @@ async def test_glob_normalizes_scope_uri():)+async def test_glob_preserves_explicit_empty_extra_fields():+ client = AsyncHTTPClient(url="http://localhost:1933")+ fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))+ client._http = fake_http+ client._handle_response = lambda _response: {"count": 0, "matches": []}++ await client.glob("**/*.md", extra_fields=[])++ fake_http.post.assert_awaited_once_with(+ "/api/v1/search/glob",+ json={+ "pattern": "**/*.md",+ "uri": "viking://",+ "node_limit": 256,+ "extra_fields": [],+ },+ )+++async def test_record_id_passthrough_is_limited_to_stat_and_read():+ record_id = "0123456789abcdef0123456789abcdef"+ client = AsyncHTTPClient(url="http://localhost:1933")+ client._request = AsyncMock(return_value=object())+ client._handle_response = lambda _response: {}++ await client.stat(record_id)+ await client.read(record_id)+ await client.rm(record_id)++ calls = client._request.await_args_list+ assert calls[0].kwargs["params"]["uri"] == record_id+ assert calls[1].kwargs["params"]["uri"] == record_id+ assert calls[2].kwargs["params"]["uri"] == f"viking://{record_id}"+++def test_not_found_reason_is_preserved_by_sdk_error_mapping():+ client = AsyncHTTPClient(url="http://localhost:1933")+ reason = "The data may not have been indexed yet or may have been deleted"++ with pytest.raises(NotFoundError, match="not have been indexed yet") as exc_info:+ client._raise_exception(+ {+ "code": "NOT_FOUND",+ "message": "server message",+ "details": {+ "resource": "0123456789abcdef0123456789abcdef",+ "type": "file",+ "reason": reason,+ },+ }+ )++ assert exc_info.value.details["reason"] == reason++@pytest.mark.asyncioasync def test_ls_and_tree_pass_query_params():client = AsyncHTTPClient(url="http://localhost:1933")diff --git a/tests/cli/test_doctor.py b/tests/cli/test_doctor.pyindex f8bfcca83..409d59dbe 100644--- a/tests/cli/test_doctor.py+++ b/tests/cli/test_doctor.py@@ -554,6 +554,17 @@ class TestCheckVlm:assert okassert "oauth via openviking" in detail+ def test_codex_oauth_path_still_validates_other_fields(self, tmp_path: Path):+ config = tmp_path / "ov.conf"+ config.write_text(json.dumps({"vlm": {"provider": "openai-codex"}}))++ with patch("openviking_cli.doctor._find_config", return_value=config):+ ok, detail, fix = check_vlm()++ assert not ok+ assert "requires 'model'" in detail+ assert fix == "Fix vlm section in ov.conf"+def test_fail_with_codex_oauth_missing_auth(self, tmp_path: Path):config = tmp_path / "ov.conf"config.write_text(diff --git a/tests/server/test_api_fs_content_endpoint_suite.py b/tests/server/test_api_fs_content_endpoint_suite.pyindex f7c6137bd..f07d39014 100644--- a/tests/server/test_api_fs_content_endpoint_suite.py+++ b/tests/server/test_api_fs_content_endpoint_suite.py@@ -6,6 +6,7 @@ from types import SimpleNamespaceimport httpxfrom openviking.pyagfs.exceptions import AGFSHTTPError+from openviking_cli.exceptions import NotFoundErrordef _assert_error(@@ -109,6 +110,32 @@ async def test_stat_backend_unavailable_returns_structured_error(app, service, m_assert_error(response, status_code=503, error_code="UNAVAILABLE")+async def test_record_id_miss_hint_reaches_stat_and_read_responses(app, service, monkeypatch):+ record_id = "0123456789abcdef0123456789abcdef"+ reason = "The data may not have been indexed yet or may have been deleted"++ async def fake_not_found(*args, **kwargs):+ raise NotFoundError(record_id, "file", reason=reason)++ monkeypatch.setattr(service.fs, "stat", fake_not_found)+ monkeypatch.setattr(service.fs, "read_visible", fake_not_found)++ for endpoint in ("/api/v1/fs/stat", "/api/v1/content/read"):+ response = await _request_with_handler(+ app,+ "GET",+ endpoint,+ params={"uri": record_id},+ )+ _assert_error(+ response,+ status_code=404,+ error_code="NOT_FOUND",+ message_fragment=reason,+ )+ assert response.json()["error"]["details"]["reason"] == reason++async def test_mkdir_permission_denied_returns_structured_error(app, service, monkeypatch):async def fake_mkdir(*args, **kwargs):raise PermissionError("Access denied for viking://resources/blocked")diff --git a/tests/server/test_api_search.py b/tests/server/test_api_search.pyindex cdde5c1b4..926d4023f 100644--- a/tests/server/test_api_search.py+++ b/tests/server/test_api_search.py@@ -1160,3 +1160,18 @@ async def test_glob(client_with_resource):)assert resp.status_code == 200assert resp.json()["status"] == "ok"+ assert all(isinstance(match, str) for match in resp.json()["result"]["matches"])+++async def test_glob_explicit_empty_extra_fields_returns_entry_objects(client_with_resource):+ client, _ = client_with_resource+ resp = await client.post(+ "/api/v1/search/glob",+ json={"pattern": "**/*.md", "extra_fields": []},+ )++ assert resp.status_code == 200+ matches = resp.json()["result"]["matches"]+ assert matches+ assert all(isinstance(match, dict) for match in matches)+ assert all("uri" in match and "isDir" in match for match in matches)diff --git a/tests/server/test_filesystem_router.py b/tests/server/test_filesystem_router.pyindex 128efc233..4cdf734d2 100644--- a/tests/server/test_filesystem_router.py+++ b/tests/server/test_filesystem_router.py@@ -186,6 +186,47 @@ async def test_http_stat_returns_canonical_request_uri(monkeypatch):assert seen["ctx"].user.user_id == "alice"+async def test_http_stat_by_record_id_returns_resolved_uri(monkeypatch):+ record_id = "0123456789abcdef0123456789abcdef"+ resolved_uri = "viking://user/alice/resources/notes.md"+ seen = {}++ async def fake_stat(uri, ctx=None):+ seen.update(uri=uri, ctx=ctx)+ return {+ "uri": resolved_uri,+ "name": "notes.md",+ "size": 12,+ "mode": 0o644,+ "modTime": "2026-08-28T00:00:00Z",+ "isDir": False,+ "isLocked": False,+ "id": record_id,+ }++ monkeypatch.setattr(+ filesystem,+ "get_service",+ lambda: SimpleNamespace(fs=SimpleNamespace(stat=fake_stat)),+ )++ app = FastAPI()+ app.include_router(filesystem.router)+ app.dependency_overrides[get_request_context] = lambda: RequestContext(+ user=UserIdentifier("acct", "alice"), role=Role.USER+ )+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(+ transport=transport, base_url="http://testserver"+ ) as client:+ response = await client.get("/api/v1/fs/stat", params={"uri": record_id})++ assert response.status_code == 200, response.text+ assert response.json()["result"]["uri"] == resolved_uri+ assert seen["uri"] == record_id++@pytest.mark.asyncioasync def test_ls_user_container_lists_only_caller_space(app, client, service):"""`viking://user` is the container of user spaces, not a current-user shorthand."""diff --git a/tests/storage/test_viking_fs_glob.py b/tests/storage/test_viking_fs_glob.pyindex 67e54a226..24f876f2c 100644--- a/tests/storage/test_viking_fs_glob.py+++ b/tests/storage/test_viking_fs_glob.py@@ -5,7 +5,7 @@ import pytestfrom openviking.server.identity import RequestContext, Rolefrom openviking.storage.viking_fs import VikingFS-from openviking_cli.exceptions import InvalidArgumentError+from openviking_cli.exceptions import InvalidArgumentError, NotFoundErrorfrom openviking_cli.session.user_id import UserIdentifier@@ -295,6 +295,47 @@ async def test_glob_marks_directories_but_not_files(monkeypatch, fs):]+async def test_glob_directory_metadata_uses_is_dir_instead_of_trailing_slash(monkeypatch, fs):+ async def fake_glob_directory(path, pattern, **kwargs):+ return {+ "entries": [+ {+ "path": "/local/test_account/resources/folder",+ "rel_path": "folder",+ "name": "folder",+ "is_dir": True,+ }+ ],+ "next_token": None,+ }++ monkeypatch.setattr(fs._async_agfs, "glob_directory", fake_glob_directory)++ async def fake_stat(*_args, **_kwargs):+ raise NotFoundError("viking://resources/folder", "file")++ monkeypatch.setattr(fs, "stat", fake_stat)++ result = await fs.glob(+ "**/*",+ uri="viking://resources",+ ctx=_default_ctx(),+ extra_fields=[],+ )++ assert result == {+ "matches": [+ {+ "uri": "viking://resources/folder",+ "name": "folder",+ "isDir": True,+ }+ ],+ "count": 1,+ }++@pytest.mark.asyncioasync def test_glob_preserves_canonical_session_uri(monkeypatch, fs):monkeypatch.setattr(diff --git a/tests/storage/test_viking_fs_record_ids.py b/tests/storage/test_viking_fs_record_ids.pynew file mode 100644index 000000000..5aa22bfbf--- /dev/null+++ b/tests/storage/test_viking_fs_record_ids.py@@ -0,0 +1,34 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++import pytest++from openviking.server.identity import RequestContext, Role+from openviking.storage.viking_fs import VikingFS+from openviking_cli.exceptions import NotFoundError+from openviking_cli.session.user_id import UserIdentifier+++class _DummyAgfs:+ pass+++def _default_ctx() -> RequestContext:+ return RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)+++async def test_missing_record_id_explains_index_or_deletion_state(monkeypatch):+ fs = VikingFS(agfs=_DummyAgfs())+ monkeypatch.setattr(fs, "_get_vector_store", lambda: None)+ record_id = "0123456789abcdef0123456789abcdef"++ with pytest.raises(NotFoundError) as exc_info:+ await fs.resolve_uri(record_id, ctx=_default_ctx())++ error = exc_info.value+ assert "not have been indexed yet" in error.message+ assert "may have been deleted" in error.message+ assert error.details["reason"] == (+ "The data may not have been indexed yet or may have been deleted"+ )diff --git a/tests/storage/test_viking_fs_tree.py b/tests/storage/test_viking_fs_tree.pyindex 3faaee73c..8fc192424 100644--- a/tests/storage/test_viking_fs_tree.py+++ b/tests/storage/test_viking_fs_tree.py@@ -458,6 +458,35 @@ async def test_tree_original_extra_fields_preserved(monkeypatch, fs):assert result[0]["meta"] == {"Name": "s3fs", "Type": "s3"}+async def test_extra_fields_do_not_enrich_acl_denied_entries(monkeypatch, fs):+ denied = {+ "name": "restricted",+ "isDir": True,+ "uri": "viking://resources/restricted",+ "access": "denied",+ }++ async def fail_locked(_path):+ raise AssertionError("denied entry must not query lock metadata")++ monkeypatch.setattr(fs, "_is_path_locked_async", fail_locked)+ monkeypatch.setattr(fs, "_get_vector_store", lambda: None)++ await fs._augment_entries_extra_fields(+ [denied],+ ["locked", "id", "count"],+ ctx=_default_ctx(),+ )++ assert denied == {+ "name": "restricted",+ "isDir": True,+ "uri": "viking://resources/restricted",+ "access": "denied",+ }++@pytest.mark.asyncioasync def test_tree_original_dfs_order(monkeypatch, fs):"""PY-ORIG-006: DFS order preserved — directories before their children."""