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(tree): 支持目录过滤及 L0/L1 内容展示 (#5334)
hezhang-121685b40a1fcd67
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex b2f522cb8..c49055cea 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -606,7 +606,11 @@ impl HttpClient {uri: &str,output: &str,abs_limit: i32,+ include_abstract: Option<bool>,+ include_overview: Option<bool>,+ overview_limit: i32,show_all_hidden: bool,+ directories_only: bool,node_limit: i32,level_limit: i32,offset: i32,@@ -622,7 +626,17 @@ impl HttpClient {("show_all_hidden".to_string(), show_all_hidden.to_string()),("node_limit".to_string(), node_limit.to_string()),("level_limit".to_string(), level_limit.to_string()),+ ("overview_limit".to_string(), overview_limit.to_string()),];+ if let Some(value) = include_abstract {+ params.push(("include_abstract".to_string(), value.to_string()));+ }+ if let Some(value) = include_overview {+ params.push(("include_overview".to_string(), value.to_string()));+ }+ if directories_only {+ params.push(("directories_only".to_string(), "true".to_string()));+ }if offset != 0 {params.push(("offset".to_string(), offset.to_string()));}@@ -2477,7 +2491,11 @@ mod tests {"viking://resources","agent",256,+ Some(false),+ Some(true),+ 512,false,+ true,20,3,4,@@ -2494,6 +2512,10 @@ mod tests {assert!(request.contains("node_limit=20"));assert!(request.contains("offset=4"));assert!(request.contains("limit=5"));+ assert!(request.contains("include_abstract=false"));+ assert!(request.contains("include_overview=true"));+ assert!(request.contains("overview_limit=512"));+ assert!(request.contains("directories_only=true"));assert!(!request.contains("tz="));assert!(!request.contains("include_mod_time_iso="));@@ -2504,6 +2526,10 @@ mod tests {"viking://resources","agent",256,+ None,+ None,+ 4000,+ false,false,20,3,@@ -2519,6 +2545,9 @@ mod tests {.await.expect("default request should be captured");assert!(!default_request.contains("offset="));+ assert!(!default_request.contains("include_abstract="));+ assert!(!default_request.contains("include_overview="));+ assert!(!default_request.contains("directories_only="));assert!(!default_request.contains("&limit="));}diff --git a/crates/ov_cli/src/commands/filesystem.rs b/crates/ov_cli/src/commands/filesystem.rsindex 5428fd3a5..8beff0e5e 100644--- a/crates/ov_cli/src/commands/filesystem.rs+++ b/crates/ov_cli/src/commands/filesystem.rs@@ -13,6 +13,7 @@ use unicode_width::UnicodeWidthStr;const ENTRY_TEXT_WIDTH: usize = 96;const ENTRY_MIN_TEXT_WIDTH: usize = 32;const ENTRY_MAX_ABSTRACT_LINES: usize = 2;+const ENTRY_MAX_OVERVIEW_LINES: usize = 6;const ENTRY_INDENT: &str = " ";const TREE_INDENT: &str = " ";const TREE_NAME_COLUMN_WIDTH: usize = 38;@@ -45,6 +46,7 @@ static ALL_FIELDS: &[FieldDef] = &[FieldDef { name: "count", header: "COUNT", alignment: FieldAlignment::Right },FieldDef { name: "tags", header: "TAGS", alignment: FieldAlignment::Left },FieldDef { name: "abstract", header: "ABSTRACT", alignment: FieldAlignment::Left },+ FieldDef { name: "overview", header: "OVERVIEW", alignment: FieldAlignment::Left },];fn resolve_fields(fields: &[String], is_tree: bool) -> Vec<&'static FieldDef> {@@ -63,7 +65,7 @@ fn resolve_fields(fields: &[String], is_tree: bool) -> Vec<&'static FieldDef> {}for name in fields {let trimmed = name.trim();- if trimmed.is_empty() {+ if trimmed.is_empty() || (trimmed == "overview" && !is_tree) {continue;}if let Some(def) = ALL_FIELDS.iter().find(|f| f.name == trimmed) {@@ -142,7 +144,16 @@ fn field_value(entry: &Value, field: &FieldDef) -> String {.unwrap_or_else(|| "-".to_string()),"abstract" => entry_string(obj, "abstract").map(|s| {- if is_directory_abstract_placeholder(s) {+ if is_directory_summary_placeholder(s) {+ "-".to_string()+ } else {+ s.chars().take(80).collect::<String>()+ }+ })+ .unwrap_or_else(|| "-".to_string()),+ "overview" => entry_string(obj, "overview")+ .map(|s| {+ if is_directory_summary_placeholder(s) {"-".to_string()} else {s.chars().take(80).collect::<String>()@@ -210,7 +221,11 @@ pub async fn tree(uri: &str,output: &str,abs_limit: i32,+ include_abstract: Option<bool>,+ include_overview: Option<bool>,+ overview_limit: i32,show_all_hidden: bool,+ directories_only: bool,node_limit: i32,level_limit: i32,offset: i32,@@ -227,7 +242,11 @@ pub async fn tree(uri,output,abs_limit,+ include_abstract,+ include_overview,+ overview_limit,show_all_hidden,+ directories_only,node_limit,level_limit,offset,@@ -618,7 +637,14 @@ fn render_ls_entry(rank: usize, entry: &Value, text_width: usize, lines: &mut Ve}}- append_entry_abstract(object, ENTRY_INDENT, text_width, lines);+ append_entry_summary(+ object,+ "abstract",+ ENTRY_INDENT,+ text_width,+ ENTRY_MAX_ABSTRACT_LINES,+ lines,+ );}fn render_tree_entry(rank: usize, entry: &Value, text_width: usize, lines: &mut Vec<String>) {@@ -654,6 +680,23 @@ fn render_tree_entry(rank: usize, entry: &Value, text_width: usize, lines: &mut&metadata.join(" "),text_width,));+ let content_indent = format!("{indent}{TREE_INDENT}");+ append_entry_summary(+ object,+ "abstract",+ &content_indent,+ text_width,+ ENTRY_MAX_ABSTRACT_LINES,+ lines,+ );+ append_entry_summary(+ object,+ "overview",+ &content_indent,+ text_width,+ ENTRY_MAX_OVERVIEW_LINES,+ lines,+ );}fn entry_metadata(object: Option<&serde_json::Map<String, Value>>) -> Vec<String> {@@ -683,20 +726,22 @@ fn entry_metadata(object: Option<&serde_json::Map<String, Value>>) -> Vec<Stringmetadata}-fn append_entry_abstract(+fn append_entry_summary(object: Option<&serde_json::Map<String, Value>>,+ field: &str,indent: &str,text_width: usize,+ max_lines: usize,lines: &mut Vec<String>,) {- let Some(abstract_text) = entry_string(object, "abstract") else {+ let Some(text) = entry_string(object, field) else {return;};- if abstract_text.trim().is_empty() || is_directory_abstract_placeholder(abstract_text) {+ if text.trim().is_empty() || is_directory_summary_placeholder(text) {return;}- for line in wrap_display_text(abstract_text, text_width, ENTRY_MAX_ABSTRACT_LINES) {+ for line in wrap_display_text(text, text_width, max_lines) {lines.push(format!("{indent}{}", theme::body(line)));}}@@ -797,9 +842,11 @@ fn format_mod_time_for_display(value: &str) -> String {.unwrap_or_else(|_| value.to_string())}-fn is_directory_abstract_placeholder(value: &str) -> bool {+fn is_directory_summary_placeholder(value: &str) -> bool {value.contains("[Directory abstract is not ready]")|| value.contains("[.abstract.md is not ready]")+ || value.contains("[Directory overview is not ready]")+ || value.contains("[.overview.md is not ready]")}fn format_size(bytes: u64) -> String {@@ -1127,7 +1174,8 @@ mod tests {"isDir": true,"modTime": "2026-05-25","rel_path": "program",- "abstract": ""+ "abstract": "Program summaries",+ "overview": "Detailed program overview"},{"uri": "viking://user/haozhe/memories/entities/restricted",@@ -1143,6 +1191,8 @@ mod tests {assert!(rendered.contains(" 2026_fifa_world_cup.md"));assert!(rendered.contains("1.3 KB 2026-05-25"));assert!(rendered.contains("program/"));+ assert!(rendered.contains("Program summaries"));+ assert!(rendered.contains("Detailed program overview"));assert!(rendered.contains("restricted/"));assert!(rendered.contains("permission denied"));assert!(!rendered.contains("1. dir"));diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rsindex 40fd73931..160b51d92 100644--- a/crates/ov_cli/src/handlers.rs+++ b/crates/ov_cli/src/handlers.rs@@ -1724,7 +1724,11 @@ pub async fn handle_ls(pub async fn handle_tree(uri: String,abs_limit: i32,+ include_abstract: Option<bool>,+ include_overview: Option<bool>,+ overview_limit: i32,show_all_hidden: bool,+ directories_only: bool,node_limit: i32,offset: i32,limit: Option<i32>,@@ -1743,6 +1747,18 @@ pub async fn handle_tree(if show_all_hidden {params.push("-a".to_string());}+ if directories_only {+ params.push("--directories-only".to_string());+ }+ if let Some(value) = include_abstract {+ params.push(format!("--include-abstract={value}"));+ }+ if let Some(value) = include_overview {+ params.push(format!("--include-overview={value}"));+ }+ if include_overview == Some(true) {+ params.push(format!("--overview-limit {overview_limit}"));+ }if simple {params.push("-s".to_string());}@@ -1766,12 +1782,28 @@ pub async fn handle_tree(} else {"agent"};+ let include_abstract = include_abstract.or_else(|| {+ fields+ .as_ref()+ .is_some_and(|items| items.iter().any(|item| item == "abstract"))+ .then_some(true)+ });+ let include_overview = include_overview.or_else(|| {+ fields+ .as_ref()+ .is_some_and(|items| items.iter().any(|item| item == "overview"))+ .then_some(true)+ });commands::filesystem::tree(&client,&uri,api_output,abs_limit,+ include_abstract,+ include_overview,+ overview_limit,show_all_hidden,+ directories_only,node_limit,level_limit,offset,diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex cda4023e2..00acdf6f2 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -551,7 +551,7 @@ enum Commands {/// Viking URI to get tree for#[arg(value_name = "uri")]uri: String,- /// Abstract content limit (only for agent output)+ /// Maximum returned abstract length#[arg(long = "abs-limit",short = 'l',@@ -560,9 +560,43 @@ enum Commands {help_heading = "Advanced options")]abs_limit: i32,+ /// Include directory L0 abstracts (defaults to the selected output mode)+ #[arg(+ long = "include-abstract",+ default_missing_value = "true",+ num_args = 0..=1,+ require_equals = true,+ action = ArgAction::Set,+ value_name = "bool",+ help_heading = "Output options"+ )]+ include_abstract: Option<bool>,+ /// Include directory L1 overviews+ #[arg(+ long = "include-overview",+ default_missing_value = "true",+ num_args = 0..=1,+ require_equals = true,+ action = ArgAction::Set,+ value_name = "bool",+ help_heading = "Output options"+ )]+ include_overview: Option<bool>,+ /// Maximum overview content length+ #[arg(+ long = "overview-limit",+ default_value = "4000",+ value_parser = clap::value_parser!(i32).range(1..),+ value_name = "n",+ help_heading = "Advanced options"+ )]+ overview_limit: i32,/// Show all hidden files#[arg(short, long, help_heading = "Common options")]all: bool,+ /// Only include directories+ #[arg(long = "directories-only", help_heading = "Common options")]+ directories_only: bool,/// Maximum number of nodes to list#[arg(long = "node-limit",@@ -602,7 +636,7 @@ enum Commands {/// 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,tags)+ /// Comma-separated fields to display (name,uri,path,type,size,mode,mtime,locked,id,count,tags,abstract,overview)#[arg(short = 'f', long = "fields", value_delimiter = ',', value_name = "FIELDS", help_heading = "Output options")]fields: Option<Vec<String>>,/// Comma-separated k=v retrieval tags; all tags must match@@ -3566,7 +3600,11 @@ async fn main() {Commands::Tree {uri,abs_limit,+ include_abstract,+ include_overview,+ overview_limit,all,+ directories_only,node_limit,offset,limit,@@ -3578,7 +3616,11 @@ async fn main() {handlers::handle_tree(uri,abs_limit,+ include_abstract,+ include_overview,+ overview_limit,all,+ directories_only,node_limit,offset,limit,@@ -4240,6 +4282,11 @@ mod tests {"6","--limit","7",+ "--directories-only",+ "--include-abstract",+ "--include-overview=false",+ "--overview-limit",+ "512",]).expect("paged tree should parse");let health = Cli::try_parse_from(["ov", "health"]).expect("health should parse");@@ -4266,11 +4313,19 @@ mod tests {offset,limit,node_limit,+ directories_only,+ include_abstract,+ include_overview,+ overview_limit,..} => {assert_eq!(offset, 6);assert_eq!(limit, Some(7));assert_eq!(node_limit, 256);+ assert!(directories_only);+ assert_eq!(include_abstract, Some(true));+ assert_eq!(include_overview, Some(false));+ assert_eq!(overview_limit, 512);}_ => panic!("expected tree command"),}diff --git a/crates/ragfs-python/src/lib.rs b/crates/ragfs-python/src/lib.rsindex be31d2a22..bab219ebc 100644--- a/crates/ragfs-python/src/lib.rs+++ b/crates/ragfs-python/src/lib.rs@@ -2329,11 +2329,12 @@ impl RAGFSBindingClient {/// show_hidden: Whether to include hidden files (default: False)/// node_limit: Maximum number of nodes to return (default: None, no limit)/// level_limit: Maximum depth relative to query root (default: None, no limit)+ /// directories_only: Whether to return only directory entries (default: False)/// ctx: Optional FsContext dict (e.g. {"account_id": ...})////// Returns:/// A list of dicts, each with keys: path, rel_path, info, extra- #[pyo3(signature = (path, show_hidden=false, node_limit=None, level_limit=None, ctx=None, *, offset=0, sort_by=None, sort_order=None))]+ #[pyo3(signature = (path, show_hidden=false, node_limit=None, level_limit=None, ctx=None, *, offset=0, sort_by=None, sort_order=None, directories_only=false))]fn tree_directory(&self,py: Python<'_>,@@ -2345,6 +2346,7 @@ impl RAGFSBindingClient {offset: i64,sort_by: Option<&str>,sort_order: Option<&str>,+ directories_only: bool,) -> PyResult<Py<PyAny>> {let fs_ctx = build_fs_context(ctx);let top = self.top.clone();@@ -2364,6 +2366,7 @@ impl RAGFSBindingClient {Some(offset),sort_by,sort_order,+ directories_only,).await})diff --git a/crates/ragfs/src/cache/wrapper.rs b/crates/ragfs/src/cache/wrapper.rsindex 15f92755a..b6ee65198 100644--- a/crates/ragfs/src/cache/wrapper.rs+++ b/crates/ragfs/src/cache/wrapper.rs@@ -129,6 +129,7 @@ impl CachedFileSystem {offset: Option<usize>,sort_by: Option<ListSortBy>,sort_order: Option<SortOrder>,+ directories_only: bool,) -> Result<Vec<TreeEntry>> {enum TreeTask {VisitDir(String),@@ -181,7 +182,9 @@ impl CachedFileSystem {if is_dir {stack.push(TreeTask::VisitDir(entry_path));}- stack.push(TreeTask::Emit(tree_entry));+ if is_dir || !directories_only {+ stack.push(TreeTask::Emit(tree_entry));+ }}}}@@ -1269,6 +1272,7 @@ impl FileSystem for CachedFileSystem {offset: Option<usize>,sort_by: Option<ListSortBy>,sort_order: Option<SortOrder>,+ directories_only: bool,) -> Result<Vec<TreeEntry>> {if self.policy.traversal_mode() == CacheTraversalMode::CachedTraversal&& !self.wraps_multiwrite()@@ -1282,6 +1286,7 @@ impl FileSystem for CachedFileSystem {offset,sort_by,sort_order,+ directories_only,).await;}@@ -1295,6 +1300,7 @@ impl FileSystem for CachedFileSystem {offset,sort_by,sort_order,+ directories_only,).await}diff --git a/crates/ragfs/src/core/encryption_wrapper.rs b/crates/ragfs/src/core/encryption_wrapper.rsindex 904521097..8c5d356a7 100644--- a/crates/ragfs/src/core/encryption_wrapper.rs+++ b/crates/ragfs/src/core/encryption_wrapper.rs@@ -535,6 +535,7 @@ impl FileSystem for EncryptionWrappedFS {offset: Option<usize>,sort_by: Option<ListSortBy>,sort_order: Option<SortOrder>,+ directories_only: bool,) -> Result<Vec<TreeEntry>> {// Metadata only — no content read, so delegate to preserve plugin-native tree optimizations.let entries = self@@ -547,6 +548,7 @@ impl FileSystem for EncryptionWrappedFS {None,sort_by,sort_order,+ directories_only,).await?;let entries = entriesdiff --git a/crates/ragfs/src/core/filesystem.rs b/crates/ragfs/src/core/filesystem.rsindex 8ce18bbb0..80d0411db 100644--- a/crates/ragfs/src/core/filesystem.rs+++ b/crates/ragfs/src/core/filesystem.rs@@ -595,6 +595,7 @@ pub trait FileSystem: Send + Sync + Any {/// * `offset` - Number of flattened DFS entries to skip/// * `sort_by` - Optional sibling sort field/// * `sort_order` - Optional sibling sort direction+ /// * `directories_only` - Whether to return only directory entries////// # Returns/// A flat `Vec<TreeEntry>` in DFS order (directories before their children).@@ -607,6 +608,7 @@ pub trait FileSystem: Send + Sync + Any {offset: Option<usize>,sort_by: Option<ListSortBy>,sort_order: Option<SortOrder>,+ directories_only: bool,) -> Result<Vec<TreeEntry>> {let normalized_path = normalize_prefix_path(path);let mut result = Vec::new();@@ -620,6 +622,7 @@ pub trait FileSystem: Send + Sync + Any {level_limit,sort_by,sort_order,+ directories_only,&mut result,).await?;@@ -647,7 +650,16 @@ pub trait FileSystem: Send + Sync + Any {}let entries = self- .tree_directory(path, show_hidden, None, level_limit, None, None, None)+ .tree_directory(+ path,+ show_hidden,+ None,+ level_limit,+ None,+ None,+ None,+ false,+ ).await?;let mut matched = Vec::new();@@ -696,6 +708,7 @@ pub trait FileSystem: Send + Sync + Any {/// * `level_limit` - Maximum depth relative to base_path/// * `sort_by` - Optional sibling sort field/// * `sort_order` - Optional sibling sort direction+ /// * `directories_only` - Whether to add only directory entries to the result/// * `result` - Accumulator for the flat result listasync fn tree_directory_internal(&self,@@ -706,6 +719,7 @@ pub trait FileSystem: Send + Sync + Any {level_limit: Option<usize>,sort_by: Option<ListSortBy>,sort_order: Option<SortOrder>,+ directories_only: bool,result: &mut Vec<TreeEntry>,) -> Result<()> {if node_limit.is_some_and(|limit| result.len() >= limit) {@@ -746,12 +760,14 @@ pub trait FileSystem: Send + Sync + Any {let rel_path = relative_match_file(base_path, &entry_path);- result.push(TreeEntry {- path: entry_path.clone(),- rel_path,- info: entry.clone(),- extra: std::collections::HashMap::new(),- });+ if entry.is_dir || !directories_only {+ result.push(TreeEntry {+ path: entry_path.clone(),+ rel_path,+ info: entry.clone(),+ extra: std::collections::HashMap::new(),+ });+ }if entry.is_dir {self.tree_directory_internal(@@ -762,6 +778,7 @@ pub trait FileSystem: Send + Sync + Any {level_limit,sort_by,sort_order,+ directories_only,result,).await?;@@ -1123,6 +1140,7 @@ mod tests {None,None,None,+ false,).await.unwrap()@@ -1251,6 +1269,7 @@ mod tests {Some(1),Some(ListSortBy::Name),Some(SortOrder::Asc),+ false,).await.unwrap();@@ -1259,6 +1278,38 @@ mod tests {assert_tree_names(&entries, &["b.txt", "c.txt", "d.txt"]);}+ #[tokio::test]+ async fn test_tree_directories_only_filters_before_pagination() {+ let fs = TreeFS::default()+ .with_dir_entries(+ "/root",+ vec![+ ("file-a.txt", false),+ ("dir-a", true),+ ("file-b.txt", false),+ ("dir-b", true),+ ],+ )+ .with_dir_entries("/root/dir-a", vec![])+ .with_dir_entries("/root/dir-b", vec![]);++ let entries = fs+ .tree_directory(+ "/root",+ false,+ Some(1),+ None,+ Some(1),+ Some(ListSortBy::Name),+ Some(SortOrder::Asc),+ true,+ )+ .await+ .unwrap();++ assert_tree_names(&entries, &["dir-b"]);+ }+#[tokio::test]async fn test_tree_node_limit_zero() {let fs = TreeFS::default().with_dir_entries("/root", vec![("a.txt", false)]);@@ -1354,7 +1405,7 @@ mod tests {let fs = TreeFS::default().with_dir_entries("/", vec![("a.txt", false), ("sub", true)]);let entries = fs- .tree_directory("/", false, None, None, None, None, None)+ .tree_directory("/", false, None, None, None, None, None, false).await.unwrap();@@ -1373,7 +1424,7 @@ mod tests {.with_dir_entries("/a/b/c/d/e", vec![("f.txt", false)]);let entries = fs- .tree_directory("/a", false, None, None, None, None, None)+ .tree_directory("/a", false, None, None, None, None, None, false).await.unwrap();diff --git a/crates/ragfs/src/core/mountable.rs b/crates/ragfs/src/core/mountable.rsindex dedd10f15..2b7f625ab 100644--- a/crates/ragfs/src/core/mountable.rs+++ b/crates/ragfs/src/core/mountable.rs@@ -1149,6 +1149,7 @@ impl FileSystem for MountableFS {offset: Option<usize>,sort_by: Option<crate::core::ListSortBy>,sort_order: Option<crate::core::SortOrder>,+ directories_only: bool,) -> Result<Vec<TreeEntry>> {let (mount_info, rel_path) = self.find_mount(path).await?;@@ -1168,6 +1169,7 @@ impl FileSystem for MountableFS {None,sort_by,sort_order,+ directories_only,).await?;@@ -1187,6 +1189,7 @@ impl FileSystem for MountableFS {.rsplit('/').next().map_or(true, |name| !is_hidden_internal_name(name))+ && (!directories_only || e.info.is_dir)});Ok(paginate_entries(entries, offset, node_limit))@@ -1402,6 +1405,7 @@ mod tests {_offset: Option<usize>,_sort_by: Option<crate::core::ListSortBy>,_sort_order: Option<crate::core::SortOrder>,+ _directories_only: bool,) -> Result<Vec<TreeEntry>> {Ok(self.tree_entries.clone())}@@ -2274,7 +2278,16 @@ mod tests {async fn test_tree_directory_no_mount_returns_error() {let mfs = MountableFS::new();let result = mfs- .tree_directory("/nonexistent/subdir", false, None, None, None, None, None)+ .tree_directory(+ "/nonexistent/subdir",+ false,+ None,+ None,+ None,+ None,+ None,+ false,+ ).await;assert!(result.is_err());}@@ -2295,7 +2308,7 @@ mod tests {mfs.mount(test_config("rewrite", "/rewrite")).await.unwrap();let result = mfs- .tree_directory("/rewrite/sub", false, None, None, None, None, None)+ .tree_directory("/rewrite/sub", false, None, None, None, None, None, false).await.unwrap();assert_eq!(result.len(), 1);@@ -2316,7 +2329,16 @@ mod tests {.unwrap();let result = mfs- .tree_directory("/local/test_account/a", false, None, None, None, None, None)+ .tree_directory(+ "/local/test_account/a",+ false,+ None,+ None,+ None,+ None,+ None,+ false,+ ).await.unwrap();assert_eq!(result.len(), 1);diff --git a/crates/ragfs/src/core/multibackend_wrapper.rs b/crates/ragfs/src/core/multibackend_wrapper.rsindex 4edc19054..c8f8149d8 100644--- a/crates/ragfs/src/core/multibackend_wrapper.rs+++ b/crates/ragfs/src/core/multibackend_wrapper.rs@@ -1615,7 +1615,16 @@ impl FileSystem for MultiWriteWrappedFS {if recursive && search_dir == path_owned {let redirect_entries = self- .tree_directory(&path_owned, true, None, level_limit, None, None, None)+ .tree_directory(+ &path_owned,+ true,+ None,+ level_limit,+ None,+ None,+ None,+ false,+ ).await?;for entry in redirect_entries {if node_limit.is_some_and(|limit| result.count >= limit) {@@ -1734,7 +1743,16 @@ impl FileSystem for MultiWriteWrappedFS {}let entries = self- .tree_directory(path, show_hidden, None, level_limit, None, None, None)+ .tree_directory(+ path,+ show_hidden,+ None,+ level_limit,+ None,+ None,+ None,+ false,+ ).await?;let mut matched = Vec::new();@@ -1782,6 +1800,7 @@ impl FileSystem for MultiWriteWrappedFS {offset: Option<usize>,sort_by: Option<ListSortBy>,sort_order: Option<SortOrder>,+ directories_only: bool,) -> Result<Vec<TreeEntry>> {let base = normalize_prefix_path(path);if sort_by.is_some() {@@ -1795,6 +1814,7 @@ impl FileSystem for MultiWriteWrappedFS {level_limit,sort_by,sort_order,+ directories_only,&mut entries,).await?;@@ -1805,12 +1825,21 @@ impl FileSystem for MultiWriteWrappedFS {.inner.primary().backend- .tree_directory(path, show_hidden, None, level_limit, None, None, None)+ .tree_directory(+ path,+ show_hidden,+ None,+ level_limit,+ None,+ None,+ None,+ directories_only,+ ).await?;entries.retain(|e| {let name = file_name(&e.path);- !MULTIWRITE_INTERNAL_NAMES.contains(&name)+ !MULTIWRITE_INTERNAL_NAMES.contains(&name) && (!directories_only || e.info.is_dir)});if self.inner.redirects.is_empty() {@@ -1894,6 +1923,9 @@ impl FileSystem for MultiWriteWrappedFS {}}+ if directories_only {+ entries.retain(|entry| entry.info.is_dir);+ }Ok(paginate_entries(entries, offset, node_limit))}}diff --git a/crates/ragfs/src/core/multibackend_wrapper/tests.rs b/crates/ragfs/src/core/multibackend_wrapper/tests.rsindex 1547e55e7..1a6752d88 100644--- a/crates/ragfs/src/core/multibackend_wrapper/tests.rs+++ b/crates/ragfs/src/core/multibackend_wrapper/tests.rs@@ -152,7 +152,16 @@ async fn test_read_dir_redirect_entries_use_target_stat() {assert_eq!(names, vec!["real.txt"]);let tree = no_redirect_fs- .tree_directory("/local/acct", false, None, Some(3), None, None, None)+ .tree_directory(+ "/local/acct",+ false,+ None,+ Some(3),+ None,+ None,+ None,+ false,+ ).await?;let paths: Vec<&str> = tree.iter().map(|entry| entry.path.as_str()).collect();assert!(!paths.contains(&"/local/acct/docs/ghost.pdf"));@@ -212,6 +221,7 @@ async fn test_recursive_grep_finds_nested_redirected_files() {None,None,None,+ false,).await?;let shallow_paths: Vec<&str> =@@ -227,6 +237,7 @@ async fn test_recursive_grep_finds_nested_redirected_files() {None,None,None,+ false,).await?;assert!(root_only.is_empty());@@ -240,6 +251,7 @@ async fn test_recursive_grep_finds_nested_redirected_files() {None,None,None,+ false,).await?;let deep_paths: Vec<&str> = deep.iter().map(|entry| entry.path.as_str()).collect();@@ -260,6 +272,7 @@ async fn test_recursive_grep_finds_nested_redirected_files() {None,None,None,+ false,).await?;let capped_paths: Vec<&str> = capped.iter().map(|entry| entry.path.as_str()).collect();diff --git a/crates/ragfs/src/core/stats_wrapper.rs b/crates/ragfs/src/core/stats_wrapper.rsindex 4235328ee..ce1303c9b 100644--- a/crates/ragfs/src/core/stats_wrapper.rs+++ b/crates/ragfs/src/core/stats_wrapper.rs@@ -193,6 +193,7 @@ impl FileSystem for StatsWrappedFS {offset: Option<usize>,sort_by: Option<crate::core::ListSortBy>,sort_order: Option<crate::core::SortOrder>,+ directories_only: bool,) -> Result<Vec<TreeEntry>> {let timer = OperationTimer::start(FsOperation::TreeDir, Arc::clone(&self.stats));let result = self@@ -205,6 +206,7 @@ impl FileSystem for StatsWrappedFS {offset,sort_by,sort_order,+ directories_only,).await;timer.finish(result.is_ok()).await;diff --git a/crates/ragfs/src/git/enumerate.rs b/crates/ragfs/src/git/enumerate.rsindex a06c0d14d..1da229f5c 100644--- a/crates/ragfs/src/git/enumerate.rs+++ b/crates/ragfs/src/git/enumerate.rs@@ -107,7 +107,7 @@ pub async fn collect_under(let account_prefix = format!("/local/{}/", account);let entries = vfs- .tree_directory(&root, true, None, None, None, None, None)+ .tree_directory(&root, true, None, None, None, None, None, false).await?;let mut survivors = Vec::new();@@ -226,6 +226,7 @@ mod tests {_offset: Option<usize>,_sort_by: Option<crate::core::ListSortBy>,_sort_order: Option<crate::core::SortOrder>,+ _directories_only: bool,) -> Result<Vec<TreeEntry>> {let raw = self.entries_by_root.get(path).cloned().unwrap_or_default();diff --git a/crates/ragfs/src/git/service.rs b/crates/ragfs/src/git/service.rsindex 47777654d..def2e1135 100644--- a/crates/ragfs/src/git/service.rs+++ b/crates/ragfs/src/git/service.rs@@ -1988,6 +1988,7 @@ mod tests {_offset: Option<usize>,_sort_by: Option<crate::core::ListSortBy>,_sort_order: Option<crate::core::SortOrder>,+ _directories_only: bool,) -> Result<Vec<TreeEntry>> {let prefix = if path == "/" {"/".to_string()@@ -6126,6 +6127,7 @@ mod fast_path1_tests {_offset: Option<usize>,_sort_by: Option<crate::core::ListSortBy>,_sort_order: Option<crate::core::SortOrder>,+ _directories_only: bool,) -> Result<Vec<TreeEntry>> {let prefix = if path == "/" {"/".to_string()diff --git a/crates/ragfs/src/lock/wrapper.rs b/crates/ragfs/src/lock/wrapper.rsindex d34db33e1..4e7966db2 100644--- a/crates/ragfs/src/lock/wrapper.rs+++ b/crates/ragfs/src/lock/wrapper.rs@@ -353,6 +353,7 @@ impl FileSystem for PathLockWrappedFS {offset: Option<usize>,sort_by: Option<ListSortBy>,sort_order: Option<SortOrder>,+ directories_only: bool,) -> crate::core::Result<Vec<TreeEntry>> {self.inner.tree_directory(@@ -363,6 +364,7 @@ impl FileSystem for PathLockWrappedFS {offset,sort_by,sort_order,+ directories_only,).await}diff --git a/crates/ragfs/src/multibackend/admin.rs b/crates/ragfs/src/multibackend/admin.rsindex 9a5e684a2..d0450a1b3 100644--- a/crates/ragfs/src/multibackend/admin.rs+++ b/crates/ragfs/src/multibackend/admin.rs@@ -39,7 +39,7 @@ impl MultiWriteWrappedFS {for entry in inner.primary().backend- .tree_directory(&normalized, true, None, None, None, None, None)+ .tree_directory(&normalized, true, None, None, None, None, None, false).await?{if entry.info.is_dir {diff --git a/crates/ragfs/src/plugins/s3fs/mod.rs b/crates/ragfs/src/plugins/s3fs/mod.rsindex 8e2ee5826..f7f5f74b6 100644--- a/crates/ragfs/src/plugins/s3fs/mod.rs+++ b/crates/ragfs/src/plugins/s3fs/mod.rs@@ -1032,6 +1032,7 @@ impl FileSystem for S3FileSystem {offset: Option<usize>,sort_by: Option<crate::core::ListSortBy>,sort_order: Option<crate::core::SortOrder>,+ directories_only: bool,) -> Result<Vec<TreeEntry>> {let normalized = Self::normalize_path(path);if sort_by.is_some() {@@ -1045,6 +1046,7 @@ impl FileSystem for S3FileSystem {level_limit,sort_by,sort_order,+ directories_only,&mut result,).await?;@@ -1061,13 +1063,16 @@ impl FileSystem for S3FileSystem {let objects = self.client.list_tree_objects(&prefix).await?;- let ordered = build_tree_entries_from_flat_listing(+ let mut ordered = build_tree_entries_from_flat_listing(&normalized,&objects,show_hidden,level_limit,|key| self.client.strip_prefix(key),)?;+ if directories_only {+ ordered.retain(|entry| entry.info.is_dir);+ }Ok(crate::core::filesystem::paginate_entries(ordered, offset, node_limit,diff --git a/crates/ragfs/src/shape/probe.rs b/crates/ragfs/src/shape/probe.rsindex 2dace2ed3..7aa6816e1 100644--- a/crates/ragfs/src/shape/probe.rs+++ b/crates/ragfs/src/shape/probe.rs@@ -115,7 +115,9 @@ pub async fn write_shape_guard(/// Probe existing backend files to infer the legacy storage shape.pub async fn detect_legacy_shape(raw_fs: &Arc<dyn FileSystem>) -> Result<Option<StorageShape>> {- let entries = raw_fs.tree_directory("/", true, None, None, None, None, None).await?;+ let entries = raw_fs+ .tree_directory("/", true, None, None, None, None, None, false)+ .await?;let mut candidates = Vec::new();for entry in entries {diff --git a/docs/en/api/03-filesystem.md b/docs/en/api/03-filesystem.mdindex 8393cbe65..c419ea874 100644--- a/docs/en/api/03-filesystem.md+++ b/docs/en/api/03-filesystem.md@@ -165,8 +165,12 @@ Get directory tree structure.|-----------|------|----------|---------|-------------|| uri | str | Yes | - | Viking URI || output | str | No | HTTP: `agent`; SDKs: `original` | Output format: `agent` or `original` |-| abs_limit | int | No | HTTP: 256; SDKs: 128 | Abstract length limit for `agent` output |+| abs_limit | int | No | HTTP: 256; SDKs: 128 | Maximum returned abstract length |+| include_abstract | bool | No | Unset | Include directory L0 abstracts. When unset, follows the legacy output behavior (`agent`: included; `original`: omitted) |+| include_overview | bool | No | Unset | Include directory L1 overviews. Unset means omitted |+| overview_limit | int | No | 4000 | Maximum returned overview length || show_all_hidden | bool | No | False | Include hidden files like `-a` |+| directories_only | bool | No | False | Return directory nodes only || node_limit | int | No | 1000 | Maximum number of results || offset | int | No | 0 | Number of visible results to skip || limit | int | No | None | Alias for `node_limit` |@@ -174,7 +178,7 @@ Get directory tree structure.| extra_fields | list[str] | No | None | Extra fields to include: `locked`, `id`, `count` || tags | string[] | No | Unset | Retain only nodes matching every supplied `k=v` retrieval tag |-`tags` uses AND semantics and is applied before `offset` and `limit`. Tags are included for filtered responses; for an unfiltered response, request `include_tags=true` (CLI: `-f tags`).+Directory filtering and `tags` are applied before `offset` and `limit`. Abstracts and overviews are attached to the selected directory nodes and do not count toward `node_limit`. Explicit `include_abstract=true|false` overrides the legacy behavior implied by `output`. Tags are included for filtered responses; for an unfiltered response, request `include_tags=true` (CLI: `-f tags`).**Python HTTP SDK**@@ -196,7 +200,11 @@ console.log(tree);**Go SDK**```go-entries, err := client.Tree(ctx, "viking://resources/", nil)+entries, err := client.Tree(ctx, "viking://resources/", &openviking.TreeOptions{+ DirectoriesOnly: true,+ IncludeAbstract: openviking.Bool(true),+ IncludeOverview: openviking.Bool(true),+})if err != nil {return err}@@ -219,7 +227,8 @@ curl -X GET "http://localhost:1933/api/v1/fs/tree?uri=viking://resources/" \**CLI**```bash-openviking tree viking://resources/my-project/+openviking tree viking://resources/my-project/ \+ --directories-only --include-abstract --include-overview```As with `ls`, the HTTP `result` remains a node array and `has_more` is returned at the top level. When `has_more=true`, the CLI appends a pagination hint to the tree output.diff --git a/docs/zh/api/03-filesystem.md b/docs/zh/api/03-filesystem.mdindex 599187509..dfd7100ec 100644--- a/docs/zh/api/03-filesystem.md+++ b/docs/zh/api/03-filesystem.md@@ -190,8 +190,12 @@ HTTP 响应中的 `result` 保持为条目数组。`has_more=true` 表示在应|------|------|------|--------|------|| uri | str | 是 | - | Viking URI || output | str | 否 | HTTP:`agent`;SDK:`original` | 输出格式:`agent` 或 `original` |-| abs_limit | int | 否 | HTTP:256;SDK:128 | `agent` 输出中的摘要长度限制 |+| abs_limit | int | 否 | HTTP:256;SDK:128 | 返回的摘要最大长度 |+| include_abstract | bool | 否 | 未设置 | 是否返回目录 L0 摘要。未设置时沿用旧 `output` 语义(`agent` 返回,`original` 不返回) |+| include_overview | bool | 否 | 未设置 | 是否返回目录 L1 概览。未设置时不返回 |+| overview_limit | int | 否 | 4000 | 返回的概览最大长度 || show_all_hidden | bool | 否 | False | 像 `-a` 一样包含隐藏文件 |+| directories_only | bool | 否 | False | 仅返回目录节点 || node_limit | int | 否 | 1000 | 最大返回节点数 || offset | int | 否 | 0 | 跳过的可见节点数 || limit | int | 否 | None | `node_limit` 的别名 |@@ -199,7 +203,7 @@ HTTP 响应中的 `result` 保持为条目数组。`has_more=true` 表示在应| extra_fields | list[str] | 否 | None | 额外返回的字段:`locked`、`id`、`count` || tags | string[] | 否 | 未设置 | 仅保留同时匹配全部 `k=v` 检索标签的节点 |-`tags` 使用 AND 语义,并在 `offset` 和 `limit` 前应用。带 tags 过滤的响应会返回 `tags`;未过滤时需传 `include_tags=true` 才返回它们,否则会省略 tags 以避免额外的向量库读取。+目录过滤和 `tags` 均在 `offset`、`limit` 前应用。L0/L1 内容只附加到分页选中的目录节点,不占用 `node_limit`。显式传入 `include_abstract=true|false` 会覆盖 `output` 隐含的旧行为。带 tags 过滤的响应会返回 `tags`;未过滤时需传 `include_tags=true` 才返回它们。**Python HTTP SDK**@@ -230,7 +234,10 @@ console.log(tree);```goentries, err := client.Tree(ctx, "viking://resources/", &openviking.TreeOptions{- Tags: []string{"team=search", "env=prod"},+ Tags: []string{"team=search", "env=prod"},+ DirectoriesOnly: true,+ IncludeAbstract: openviking.Bool(true),+ IncludeOverview: openviking.Bool(true),})if err != nil {return err@@ -265,6 +272,10 @@ openviking tree viking://resources/my-project/ --fields path,type,tags# 与 ls、glob 一样支持 --simple 和列选择组合openviking tree viking://resources/my-project/ --simple --fields path,tags++# 仅返回目录,并附加 L0/L1 内容+openviking tree viking://resources/my-project/ \+ --directories-only --include-abstract --include-overview```与 `ls` 一致,HTTP 响应中的 `result` 保持为节点数组,`has_more` 位于响应顶层。CLI 检测到 `has_more=true` 时会在树输出末尾显示后续节点提示。diff --git a/openviking/pyagfs/async_client.py b/openviking/pyagfs/async_client.pyindex 0e7cb6399..ebfa1d563 100644--- a/openviking/pyagfs/async_client.py+++ b/openviking/pyagfs/async_client.py@@ -304,6 +304,7 @@ class AsyncAGFSClient:offset: int = 0,sort_by: str | None = None,sort_order: str = "asc",+ directories_only: bool = False,fs_ctx: Dict[str, str] | None = None,) -> list[Dict[str, Any]]:"""Return a sorted range from a recursive directory traversal."""@@ -312,6 +313,8 @@ class AsyncAGFSClient:"node_limit": node_limit,"level_limit": level_limit,}+ if directories_only:+ kwargs["directories_only"] = Trueif offset:kwargs["offset"] = offsetif sort_by is not None:diff --git a/openviking/pyagfs/protocols.py b/openviking/pyagfs/protocols.pyindex 3920c3945..020151cb8 100644--- a/openviking/pyagfs/protocols.py+++ b/openviking/pyagfs/protocols.py@@ -104,6 +104,7 @@ class AGFSSyncClientProtocol(Protocol):offset: int = 0,sort_by: str | None = None,sort_order: str = "asc",+ directories_only: bool = False,) -> list[Dict[str, Any]]:"""Return a sorted range from a directory tree."""diff --git a/openviking/server/routers/filesystem.py b/openviking/server/routers/filesystem.pyindex 773235b81..d469f7150 100644--- a/openviking/server/routers/filesystem.py+++ b/openviking/server/routers/filesystem.py@@ -125,8 +125,14 @@ async def ls(async def tree(uri: str = Query(..., description="Viking URI"),output: str = Query("agent", description="Output format: original or agent"),- abs_limit: int = Query(256, description="Abstract limit (only for agent output)"),+ abs_limit: int = Query(256, description="Maximum returned abstract length"),+ include_abstract: Optional[bool] = Query(+ None, description="Include directory L0 abstracts; defaults to the output format"+ ),+ include_overview: Optional[bool] = Query(None, description="Include directory L1 overviews"),+ overview_limit: int = Query(4000, ge=1, description="Maximum overview length"),show_all_hidden: bool = Query(False, description="List all hidden files, like -a"),+ directories_only: bool = Query(False, description="Only include directory entries"),node_limit: int = Query(1000, description="Maximum number of nodes to list"),offset: int = Query(0, ge=0, description="Number of visible nodes to skip"),limit: Optional[int] = Query(None, ge=1, description="Alias for node_limit"),@@ -149,7 +155,11 @@ async def tree(ctx=_ctx,output=output,abs_limit=abs_limit,+ include_abstract=include_abstract,+ include_overview=include_overview,+ overview_limit=overview_limit,show_all_hidden=show_all_hidden,+ directories_only=directories_only,node_limit=actual_node_limit,level_limit=level_limit,offset=offset,diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.pyindex 1b9580e2b..368332281 100644--- a/openviking/service/fs_service.py+++ b/openviking/service/fs_service.py@@ -954,6 +954,10 @@ class FSService:tags: Optional[List[str]] = None,include_tags: bool = False,offset: int = 0,+ directories_only: bool = False,+ include_abstract: Optional[bool] = None,+ include_overview: Optional[bool] = None,+ overview_limit: int = 4000,) -> ListingPage:"""Get directory tree."""viking_fs = self._ensure_initialized()@@ -965,7 +969,11 @@ class FSService:ctx=ctx,output="original" if tags else output,abs_limit=abs_limit,+ include_abstract=None if tags else include_abstract,+ include_overview=False if tags else include_overview is True,+ overview_limit=overview_limit,show_all_hidden=show_all_hidden,+ directories_only=directories_only,node_limit=page_limit,level_limit=level_limit,extra_fields=None if tags else extra_fields,@@ -981,7 +989,12 @@ class FSService:offset,node_limit,)- if output != "original" or extra_fields:+ if (+ output != "original"+ or extra_fields+ or include_abstract is True+ or include_overview is True+ ):return ListingPage(entries=await viking_fs._finalize_listing_entries(page.entries,@@ -990,6 +1003,9 @@ class FSService:extra_fields,True,ctx=ctx,+ include_abstract=include_abstract,+ include_overview=include_overview is True,+ overview_limit=overview_limit,),has_more=page.has_more,)diff --git a/openviking/storage/viking_fs/_access.py b/openviking/storage/viking_fs/_access.pyindex 86606428a..efee53ada 100644--- a/openviking/storage/viking_fs/_access.py+++ b/openviking/storage/viking_fs/_access.py@@ -548,6 +548,7 @@ class _AccessMixin:sort_by: Optional[str] = None,sort_order: str = "asc",ctx: Optional[RequestContext] = None,+ directories_only: bool = False,):"""Yield one visible tree page after namespace and ACL filtering."""real_ctx = self._ctx_or_default(ctx)@@ -583,6 +584,7 @@ class _AccessMixin:offset=raw_offset,sort_by=sort_by,sort_order=sort_order,+ directories_only=directories_only,)if not raw_entries:returndiff --git a/openviking/storage/viking_fs/_ops.py b/openviking/storage/viking_fs/_ops.pyindex 656c662c4..7911878fc 100644--- a/openviking/storage/viking_fs/_ops.py+++ b/openviking/storage/viking_fs/_ops.py@@ -7,7 +7,7 @@ import mathimport uuidfrom dataclasses import replacefrom datetime import datetime, timezone-from typing import Any, Dict, List, Optional, Union+from typing import Any, Awaitable, Callable, Dict, List, Optional, Unionfrom openviking.core.context import ContextLevelfrom openviking.core.namespace import (@@ -1585,20 +1585,47 @@ class _OpsMixin:abs_limit: int,ctx: Optional[RequestContext] = None,) -> None:- """Batch fetch abstracts for entries using a fixed-size worker pool.+ """Batch fetch abstracts for directory entries."""+ await self._batch_fetch_directory_summaries(+ entries,+ field="abstract",+ limit=abs_limit,+ reader=self._read_abstract_for_known_dir,+ fallback="[.abstract.md is not ready]",+ ctx=ctx,+ )- Non-directory entries receive an empty abstract immediately.- Directory entries are processed concurrently via a worker pool,- using _read_abstract_for_known_dir to skip redundant stat() calls.+ async def _batch_fetch_overviews(+ self,+ entries: List[Dict[str, Any]],+ overview_limit: int,+ ctx: Optional[RequestContext] = None,+ ) -> None:+ """Batch fetch overviews for directory entries."""+ await self._batch_fetch_directory_summaries(+ entries,+ field="overview",+ limit=overview_limit,+ reader=self.overview,+ fallback="[.overview.md is not ready]",+ ctx=ctx,+ )- Args:- entries: List of entries to fetch abstracts for- abs_limit: Maximum length for abstract truncation- """+ async def _batch_fetch_directory_summaries(+ self,+ entries: List[Dict[str, Any]],+ *,+ field: str,+ limit: int,+ reader: Callable[..., Awaitable[str]],+ fallback: str,+ ctx: Optional[RequestContext] = None,+ ) -> None:+ """Load one summary field for directories with a fixed-size worker pool."""dir_jobs = []for index, entry in enumerate(entries):if not entry.get("isDir", False):- entry["abstract"] = ""+ entry[field] = ""continuedir_jobs.append((index, entry))@@ -1621,18 +1648,18 @@ class _OpsMixin:cursor += 1try:- abstract = await self._read_abstract_for_known_dir(entry["uri"], ctx=ctx)+ summary = await reader(entry["uri"], ctx=ctx)except Exception:- abstract = "[.abstract.md is not ready]"+ summary = fallback- results[index] = abstract+ results[index] = summaryawait asyncio.gather(*(worker() for _ in range(worker_count)))- for index, abstract in results.items():- if len(abstract) > abs_limit:- abstract = abstract[: abs_limit - 3] + "..."- entries[index]["abstract"] = abstract+ for index, summary in results.items():+ if len(summary) > limit:+ summary = "." * limit if limit <= 3 else summary[: limit - 3] + "..."+ entries[index][field] = summaryasync def _finalize_listing_entries(self,@@ -1642,6 +1669,9 @@ class _OpsMixin:extra_fields: Optional[List[str]],recursive: bool,ctx: Optional[RequestContext] = None,+ include_abstract: Optional[bool] = None,+ include_overview: bool = False,+ overview_limit: int = 4000,) -> List[Dict[str, Any]]:"""Format and enrich entries after visible-page selection.@@ -1656,9 +1686,15 @@ class _OpsMixin:Returns:Entries in the requested output format."""+ load_abstract = output == "agent" if include_abstract is None else include_abstractif output == "original":if extra_fields:await self._augment_entries_extra_fields(entries, extra_fields, ctx=ctx)+ summary_entries = [entry for entry in entries if entry.get("access") != "denied"]+ if load_abstract:+ await self._batch_fetch_abstracts(summary_entries, abs_limit, ctx=ctx)+ if include_overview:+ await self._batch_fetch_overviews(summary_entries, overview_limit, ctx=ctx)return entriesif output != "agent":raise ValueError(f"Invalid output format: {output}")@@ -1701,11 +1737,11 @@ class _OpsMixin:item["tags"] = entry["tags"]result.append(item)- await self._batch_fetch_abstracts(- [entry for entry in result if entry.get("access") != "denied"],- abs_limit,- ctx=ctx,- )+ visible_entries = [entry for entry in result if entry.get("access") != "denied"]+ if load_abstract:+ await self._batch_fetch_abstracts(visible_entries, abs_limit, ctx=ctx)+ if include_overview:+ await self._batch_fetch_overviews(visible_entries, overview_limit, ctx=ctx)return resultasync def tree(@@ -1721,6 +1757,10 @@ class _OpsMixin:offset: int = 0,sort_by: Optional[str] = None,sort_order: str = "asc",+ directories_only: bool = False,+ include_abstract: Optional[bool] = None,+ include_overview: bool = False,+ overview_limit: int = 4000,) -> List[Dict[str, Any]]:"""Recursively list all contents (includes rel_path).@@ -1744,34 +1784,30 @@ class _OpsMixin:raise ValueError("offset must be non-negative")await self._ensure_access(uri, ctx)extra_fields = extra_fields or []- if output == "original":- entries = await self._tree_original(- uri,- show_all_hidden,- node_limit,- level_limit,- offset=offset,- sort_by=sort_by,- sort_order=sort_order,- ctx=ctx,- )- elif output == "agent":- entries = await self._tree_agent(- uri,- abs_limit,- show_all_hidden,- node_limit,- level_limit,- offset=offset,- sort_by=sort_by,- sort_order=sort_order,- ctx=ctx,- )- else:+ if output not in {"original", "agent"}: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+ entries = await self._tree_original(+ uri,+ show_all_hidden=show_all_hidden,+ directories_only=directories_only,+ node_limit=node_limit,+ level_limit=level_limit,+ offset=offset,+ sort_by=sort_by,+ sort_order=sort_order,+ ctx=ctx,+ )+ return await self._finalize_listing_entries(+ entries,+ output,+ abs_limit,+ extra_fields,+ True,+ ctx=ctx,+ include_abstract=include_abstract,+ include_overview=include_overview,+ overview_limit=overview_limit,+ )async def _tree_original(self,@@ -1783,12 +1819,14 @@ class _OpsMixin:sort_by: Optional[str] = None,sort_order: str = "asc",ctx: Optional[RequestContext] = None,+ directories_only: bool = False,) -> List[Dict[str, Any]]:"""Recursively list all contents (original format)."""result = []async for entry, entry_uri in self._iter_visible_tree_entries(uri,show_all_hidden=show_all_hidden,+ directories_only=directories_only,node_limit=node_limit,level_limit=level_limit,offset=offset,@@ -1823,38 +1861,6 @@ class _OpsMixin:result.append(new_entry)return result- async def _tree_agent(- self,- uri: str,- abs_limit: int,- show_all_hidden: bool = False,- node_limit: Optional[int] = 1000,- level_limit: Optional[int] = 3,- offset: int = 0,- sort_by: Optional[str] = None,- sort_order: str = "asc",- ctx: Optional[RequestContext] = None,- ) -> List[Dict[str, Any]]:- """Recursively list all contents (agent format with abstracts)."""- entries = await self._tree_original(- uri,- show_all_hidden,- node_limit,- level_limit,- offset=offset,- sort_by=sort_by,- sort_order=sort_order,- ctx=ctx,- )- return await self._finalize_listing_entries(- entries,- "agent",- abs_limit,- None,- True,- ctx=ctx,- )-# ========== Vector Sync Helper Methods ==========async def _collect_uris(diff --git a/sdk/go/client_test.go b/sdk/go/client_test.goindex 44f24f25b..15f9b7e7c 100644--- a/sdk/go/client_test.go+++ b/sdk/go/client_test.go@@ -266,6 +266,18 @@ func TestListAndTreeSendQueryOptions(t *testing.T) {if got := r.URL.Query()["tags"]; !reflect.DeepEqual(got, []string{"env=prod"}) {t.Fatalf("tags = %#v", got)}+ if got := r.URL.Query().Get("include_abstract"); got != "false" {+ t.Fatalf("include_abstract = %q", got)+ }+ if got := r.URL.Query().Get("include_overview"); got != "true" {+ t.Fatalf("include_overview = %q", got)+ }+ if got := r.URL.Query().Get("overview_limit"); got != "512" {+ t.Fatalf("overview_limit = %q", got)+ }+ if got := r.URL.Query().Get("directories_only"); got != "true" {+ t.Fatalf("directories_only = %q", got)+ }} else {if got := r.URL.Query().Get("level_limit"); got != "3" {t.Fatalf("level_limit = %q, want 3", got)@@ -276,6 +288,15 @@ func TestListAndTreeSendQueryOptions(t *testing.T) {if _, ok := r.URL.Query()["limit"]; ok {t.Fatal("default tree request should omit limit")}+ if _, ok := r.URL.Query()["include_abstract"]; ok {+ t.Fatal("default tree request should omit include_abstract")+ }+ if _, ok := r.URL.Query()["include_overview"]; ok {+ t.Fatal("default tree request should omit include_overview")+ }+ if got := r.URL.Query().Get("overview_limit"); got != "4000" {+ t.Fatalf("overview_limit = %q", got)+ }}treeCalls++default:@@ -296,11 +317,15 @@ func TestListAndTreeSendQueryOptions(t *testing.T) {t.Fatal(err)}if _, err := client.Tree(context.Background(), "viking://resources/docs", &TreeOptions{- NodeLimit: 200,- LevelLimit: Int(0),- Offset: 6,- Limit: 7,- Tags: []string{"env=prod"},+ NodeLimit: 200,+ LevelLimit: Int(0),+ Offset: 6,+ Limit: 7,+ Tags: []string{"env=prod"},+ IncludeAbstract: Bool(false),+ IncludeOverview: Bool(true),+ OverviewLimit: 512,+ DirectoriesOnly: true,}); err != nil {t.Fatal(err)}diff --git a/sdk/go/filesystem.go b/sdk/go/filesystem.goindex 2c708591a..96ba8dd28 100644--- a/sdk/go/filesystem.go+++ b/sdk/go/filesystem.go@@ -68,6 +68,10 @@ func (c *Client) Tree(ctx context.Context, uri string, opts *TreeOptions) ([]mapif absLimit == 0 {absLimit = 128}+ overviewLimit := opts.OverviewLimit+ if overviewLimit == 0 {+ overviewLimit = 4000+ }nodeLimit := opts.NodeLimitif nodeLimit == 0 {nodeLimit = 1000@@ -80,7 +84,17 @@ func (c *Client) Tree(ctx context.Context, uri string, opts *TreeOptions) ([]mapquery.Set("uri", NormalizeURI(uri))query.Set("output", output)queryInt(query, "abs_limit", absLimit)+ if opts.IncludeAbstract != nil {+ queryBool(query, "include_abstract", *opts.IncludeAbstract)+ }+ if opts.IncludeOverview != nil {+ queryBool(query, "include_overview", *opts.IncludeOverview)+ }+ queryInt(query, "overview_limit", overviewLimit)queryBool(query, "show_all_hidden", opts.ShowAllHidden)+ if opts.DirectoriesOnly {+ query.Set("directories_only", "true")+ }queryInt(query, "node_limit", nodeLimit)queryInt(query, "level_limit", levelLimit)if opts.Offset != 0 {diff --git a/sdk/go/types.go b/sdk/go/types.goindex 22ef80ff7..1ee7b7858 100644--- a/sdk/go/types.go+++ b/sdk/go/types.go@@ -200,15 +200,19 @@ type ListOptions struct {// TreeOptions controls Tree.type TreeOptions struct {- Output string- AbsLimit int- ShowAllHidden bool- NodeLimit int- LevelLimit *int- Offset int- Limit int- Tags []string- IncludeTags bool+ Output string+ AbsLimit int+ IncludeAbstract *bool+ IncludeOverview *bool+ OverviewLimit int+ ShowAllHidden bool+ DirectoriesOnly bool+ NodeLimit int+ LevelLimit *int+ Offset int+ Limit int+ Tags []string+ IncludeTags bool}// RemoveOptions controls Remove.diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.tsindex 0455f2400..495d415b8 100644--- a/sdk/typescript/src/client.ts+++ b/sdk/typescript/src/client.ts@@ -512,7 +512,11 @@ export class OpenVikingClient {uri: normalizeURI(uri),output: options.output ?? "original",abs_limit: options.absLimit ?? 128,+ include_abstract: options.includeAbstract,+ include_overview: options.includeOverview,+ overview_limit: options.overviewLimit ?? 4000,show_all_hidden: options.showAllHidden ?? false,+ directories_only: options.directoriesOnly || undefined,node_limit: options.nodeLimit ?? 1000,level_limit: options.levelLimit ?? 3,offset: options.offset,diff --git a/sdk/typescript/src/types.ts b/sdk/typescript/src/types.tsindex 837b2a916..c6579d8e1 100644--- a/sdk/typescript/src/types.ts+++ b/sdk/typescript/src/types.ts@@ -228,7 +228,11 @@ export interface ListOptions {export interface TreeOptions {output?: string;absLimit?: number;+ includeAbstract?: boolean;+ includeOverview?: boolean;+ overviewLimit?: number;showAllHidden?: boolean;+ directoriesOnly?: boolean;nodeLimit?: number;levelLimit?: number;offset?: number;diff --git a/sdk/typescript/tests/client.test.ts b/sdk/typescript/tests/client.test.tsindex 7181214a9..b88d85e68 100644--- a/sdk/typescript/tests/client.test.ts+++ b/sdk/typescript/tests/client.test.ts@@ -587,6 +587,10 @@ describe("OpenVikingClient", () => {levelLimit: 2,offset: 6,limit: 7,+ directoriesOnly: true,+ includeAbstract: false,+ includeOverview: true,+ overviewLimit: 512,});await client.tree("viking://resources/docs", { levelLimit: 0 });await client.tree("viking://resources/docs");@@ -605,6 +609,13 @@ describe("OpenVikingClient", () => {);expect(treeLimits).toEqual(["2", "0", "3"]);expect(treeUrls[0]!.searchParams.get("offset")).toBe("6");+ expect(treeUrls[0]!.searchParams.get("directories_only")).toBe("true");+ expect(treeUrls[0]!.searchParams.get("include_abstract")).toBe("false");+ expect(treeUrls[0]!.searchParams.get("include_overview")).toBe("true");+ expect(treeUrls[0]!.searchParams.get("overview_limit")).toBe("512");+ expect(treeUrls[2]!.searchParams.has("include_abstract")).toBe(false);+ expect(treeUrls[2]!.searchParams.has("include_overview")).toBe(false);+ expect(treeUrls[2]!.searchParams.get("overview_limit")).toBe("4000");expect(treeUrls[0]!.searchParams.get("limit")).toBe("7");expect(treeUrls[1]!.searchParams.has("offset")).toBe(false);expect(treeUrls[1]!.searchParams.has("limit")).toBe(false);diff --git a/tests/pyagfs/test_async_client_fs_ctx.py b/tests/pyagfs/test_async_client_fs_ctx.pyindex 01816d053..e1fa97273 100644--- a/tests/pyagfs/test_async_client_fs_ctx.py+++ b/tests/pyagfs/test_async_client_fs_ctx.py@@ -14,6 +14,7 @@ class _RecordingClient:def __init__(self) -> None:self.calls: list[tuple[str, str, dict[str, str] | None]] = []self.list_options: dict[str, Any] = {}+ self.tree_options: dict[str, Any] = {}def write(self, path: str, data: bytes, *, ctx: dict[str, str] | None = None) -> str:"""Record write ctx and return a stable fake backend id."""@@ -37,6 +38,18 @@ class _RecordingClient:self.list_options = optionsreturn []+ def tree_directory(+ self,+ path: str,+ *,+ ctx: dict[str, str] | None = None,+ **options: Any,+ ) -> list[dict[str, Any]]:+ """Record tree options and return an empty result."""+ self.calls.append(("tree_directory", path, ctx))+ self.tree_options = options+ return []+@pytest.mark.asyncioasync def test_async_client_derives_account_ctx_from_local_agfs_path() -> None:@@ -74,6 +87,19 @@ async def test_async_client_uses_system_ctx_for_non_local_agfs_path() -> None:assert client.calls == [("read", "/queue/semantic/dequeue", {"account_id": "_system"})]+async def test_async_client_passes_directories_only_to_tree_directory() -> None:+ client = _RecordingClient()+ agfs = AsyncAGFSClient(client)++ await agfs.tree_directory("/local/acct-1/data", directories_only=True)++ assert client.calls == [+ ("tree_directory", "/local/acct-1/data", {"account_id": "acct-1"})+ ]+ assert client.tree_options["directories_only"] is True++@pytest.mark.asyncioasync def test_async_client_preserves_explicit_fs_ctx() -> None:client = _RecordingClient()diff --git a/tests/service/test_fs_service.py b/tests/service/test_fs_service.pyindex 2f3e77a7c..473a58f6e 100644--- a/tests/service/test_fs_service.py+++ b/tests/service/test_fs_service.py@@ -14,6 +14,7 @@ from openviking.server.identity import RequestContext, Rolefrom openviking.service.fs_service import FSService, ListingPagefrom openviking.storage.abstract_overview import body_for_previewfrom openviking.storage.errors import LockAcquisitionError+from openviking.storage.viking_fs import VikingFSfrom openviking_cli.exceptions import InvalidArgumentErrorfrom openviking_cli.session.user_id import UserIdentifier@@ -792,13 +793,30 @@ async def test_ls_tag_filter_keeps_zero_node_limit_unbounded_for_entry_and_simpl@pytest.mark.asyncio-async def test_tree_projects_directory_tags_from_abstract_and_overview_records(request_context):+async def test_tree_projects_directory_tags_before_pagination_and_summaries(+ request_context, monkeypatch+):directory = {"uri": "viking://resources/docs", "isDir": True}- viking_fs = SimpleNamespace(tree=AsyncMock(return_value=[directory]))+ entries = [+ {"uri": "viking://resources/unmatched", "isDir": True},+ {"uri": "viking://resources/skipped", "isDir": True},+ directory,+ ]+ viking_fs = VikingFS(agfs=SimpleNamespace())+ monkeypatch.setattr(viking_fs, "tree", AsyncMock(return_value=entries))+ abstract = AsyncMock(return_value="L0 summary")+ overview = AsyncMock(return_value="L1 overview")+ monkeypatch.setattr(viking_fs, "_read_abstract_for_known_dir", abstract)+ monkeypatch.setattr(viking_fs, "overview", overview)class FakeVikingDB:async def filter(self, **_kwargs):return [+ {+ "uri": "viking://resources/skipped",+ "level": 0,+ "search_tags": ["team=search", "env=prod"],+ },{"uri": "viking://resources/docs", "level": 0, "search_tags": ["team=search"]},{"uri": "viking://resources/docs",@@ -813,19 +831,30 @@ async def test_tree_projects_directory_tags_from_abstract_and_overview_records(r"viking://resources",ctx=request_context,tags=["team=search", "env=prod"],+ node_limit=1,+ offset=1,+ include_abstract=True,+ include_overview=True,)assert result == ListingPage(entries=[{- "uri": "viking://resources/docs",- "isDir": True,+ **directory,"tags": ["team=search", "env=prod"],+ "abstract": "L0 summary",+ "overview": "L1 overview",}],has_more=False,)- assert viking_fs.tree.await_args.kwargs["node_limit"] == 1000+ # Intermediate pages must not load summaries before tag filtering selects the final page.+ fetch_options = viking_fs.tree.await_args.kwargs+ assert fetch_options["output"] == "original"+ assert fetch_options["include_abstract"] is None+ assert fetch_options["include_overview"] is False+ abstract.assert_awaited_once_with(directory["uri"], ctx=request_context)+ overview.assert_awaited_once_with(directory["uri"], ctx=request_context)@pytest.mark.asynciodiff --git a/tests/storage/test_viking_fs_tree.py b/tests/storage/test_viking_fs_tree.pyindex 63407cd32..812ee833d 100644--- a/tests/storage/test_viking_fs_tree.py+++ b/tests/storage/test_viking_fs_tree.py@@ -3,6 +3,7 @@from datetime import datetime, timezonefrom types import SimpleNamespace+from unittest.mock import AsyncMockimport pytest@@ -162,7 +163,6 @@ def patch_tree_env(*,is_accessible=True,uri_to_path="/local/test_account/resources",- batch_fetch=None,):"""Install the standard monkeypatch set for tree traversal tests.@@ -181,18 +181,6 @@ def patch_tree_env(monkeypatch.setattr(fs, "_uri_to_path", lambda _uri, **_kwargs: uri_to_path)monkeypatch.setattr(fs, "_ctx_or_default", lambda _ctx=None: _default_ctx())patch_visibility(monkeypatch, fs, is_accessible=is_accessible)- if batch_fetch is not None:- monkeypatch.setattr(fs, "_batch_fetch_abstracts", batch_fetch)---async def default_batch_fetch(entries, abs_limit, **_kwargs):- """Shared abstract enrichment fake: dirs get a mock abstract (truncated to- abs_limit), files get an empty abstract."""- for entry in entries:- abstract = "mock abstract" if entry.get("isDir") else ""- if len(abstract) > abs_limit:- abstract = abstract[: abs_limit - 3] + "..."- entry["abstract"] = abstract# ── _is_name_visible_at_path / _ancestor_is_filtered tests ──@@ -440,6 +428,47 @@ async def test_iter_visible_tree_entries_offset_and_node_limit_after_acl(monkeypassert visible_count == 3, "only skipped and returned entries should be ACL checked"+async def test_iter_visible_tree_entries_pushes_directory_filter_to_backend(monkeypatch, fs):+ entries = [+ make_entry(+ f"/local/test_account/resources/{name}",+ name,+ is_dir=is_dir,+ )+ for name, is_dir in [+ ("file-a.md", False),+ ("dir-a", True),+ ("file-b.md", False),+ ("dir-b", True),+ ("dir-c", True),+ ]+ ]+ captured = {}++ async def fake_tree_directory(_path, **kwargs):+ captured["directories_only"] = kwargs.get("directories_only")+ directories = [entry for entry in entries if entry["info"]["isDir"]]+ offset = kwargs.get("offset", 0)+ limit = kwargs.get("node_limit")+ return directories[offset : offset + limit]++ patch_tree_env(monkeypatch, fs, fake_tree_directory)++ results = []+ async for entry, _entry_uri in fs._iter_visible_tree_entries(+ "viking://resources",+ directories_only=True,+ offset=1,+ node_limit=2,+ ctx=_default_ctx(),+ ):+ results.append(entry)++ assert [entry["info"]["name"] for entry in results] == ["dir-b", "dir-c"]+ assert captured["directories_only"] is True++@pytest.mark.asyncioasync def test_iter_visible_tree_entries_reads_next_page_when_filtering_is_sparse(monkeypatch, fs):"""PY-ITER-004: sparse visible results advance the RagFS offset."""@@ -513,7 +542,7 @@ async def test_tree_original_structure(monkeypatch, fs):]patch_tree_env(monkeypatch, fs, entries)- result = await fs._tree_original("viking://resources", ctx=_default_ctx())+ result = await fs.tree("viking://resources", output="original", ctx=_default_ctx())assert len(result) == 1e = result[0]@@ -524,6 +553,8 @@ async def test_tree_original_structure(monkeypatch, fs):assert e["isDir"] is Falseassert e["rel_path"] == "a"assert e["uri"] == "viking://resources/a"+ assert "abstract" not in e+ assert "overview" not in e@pytest.mark.asyncio@@ -594,6 +625,7 @@ async def test_tree_original_dfs_order(monkeypatch, fs):),]patch_tree_env(monkeypatch, fs, entries)+async def acl_enabled(_account_id):return True@@ -620,57 +652,58 @@ async def test_tree_original_dfs_order(monkeypatch, fs):assert len(result) == 3-# ── _tree_agent tests ──+# ── tree agent output tests ──@pytest.mark.asyncioasync def test_tree_agent_structure(monkeypatch, fs):- """PY-AGENT-001: Agent output structure."""+ """Agent defaults and explicit summary controls preserve the listing contract."""entries = [- make_entry("/local/test_account/resources/a", "a", size=100, mode=0o644, is_dir=False),- make_entry("/local/test_account/resources/sub", "sub", is_dir=True),+ make_entry("/local/test_account/resources/a", "a", size=100, is_dir=False),+ make_entry("/local/test_account/resources/sub", "sub", size=999, is_dir=True),]- patch_tree_env(monkeypatch, fs, entries, batch_fetch=default_batch_fetch)-- result = await fs._tree_agent("viking://resources", abs_limit=256, ctx=_default_ctx())-- assert len(result) == 2- assert set(result[0].keys()) == {"uri", "size", "isDir", "modTime", "rel_path", "abstract"}- assert "name" not in result[0]---async def test_tree_agent_dir_size_zero(monkeypatch, fs):- """PY-AGENT-002: Directory size is always 0."""- entries = [make_entry("/local/test_account/resources/sub", "sub", size=999, is_dir=True)]- patch_tree_env(monkeypatch, fs, entries, batch_fetch=default_batch_fetch)-- result = await fs._tree_agent("viking://resources", abs_limit=256, ctx=_default_ctx())- assert result[0]["size"] == 0---async def test_tree_agent_non_dir_abstract_empty(monkeypatch, fs):- """PY-AGENT-004: Non-directory entries have empty abstract."""- entries = [- make_entry("/local/test_account/resources/a", "a", size=100, mode=0o644, is_dir=False)+ patch_tree_env(monkeypatch, fs, entries)+ abstract = AsyncMock(return_value="L0 summary")+ overview = AsyncMock(return_value="L1 overview")+ monkeypatch.setattr(fs, "_read_abstract_for_known_dir", abstract)+ monkeypatch.setattr(fs, "overview", overview)++ result = await fs.tree("viking://resources", output="agent", ctx=_default_ctx())++ assert result == [+ {+ "uri": "viking://resources/a",+ "size": 100,+ "isDir": False,+ "modTime": "2026-01-01T00:00:00.000Z",+ "rel_path": "a",+ "abstract": "",+ },+ {+ "uri": "viking://resources/sub",+ "size": 0,+ "isDir": True,+ "modTime": "2026-01-01T00:00:00.000Z",+ "rel_path": "sub",+ "abstract": "L0 summary",+ },]- patch_tree_env(monkeypatch, fs, entries, batch_fetch=default_batch_fetch)-- result = await fs._tree_agent("viking://resources", abs_limit=256, ctx=_default_ctx())- assert result[0]["abstract"] == ""-+ abstract.assert_awaited_once_with("viking://resources/sub", ctx=_default_ctx())+ overview.assert_not_awaited()+ abstract.reset_mock()-async def test_tree_agent_modtime_is_raw_utc_iso(monkeypatch, fs):- """PY-AGENT-003: modTime is returned as a raw UTC timestamp."""- entries = [- make_entry("/local/test_account/resources/a", "a", size=100, mode=0o644, is_dir=False)- ]- patch_tree_env(monkeypatch, fs, entries, batch_fetch=default_batch_fetch)+ result = await fs.tree(+ "viking://resources",+ output="agent",+ include_abstract=False,+ include_overview=True,+ ctx=_default_ctx(),+ )- result = await fs._tree_agent("viking://resources", abs_limit=256, ctx=_default_ctx())- assert result[0]["modTime"] == "2026-01-01T00:00:00.000Z"+ assert all("abstract" not in entry for entry in result)+ assert [entry["overview"] for entry in result] == ["", "L1 overview"]+ abstract.assert_not_awaited()+ overview.assert_awaited_once_with("viking://resources/sub", ctx=_default_ctx())@pytest.mark.asyncio@@ -685,11 +718,12 @@ async def test_tree_agent_normalizes_modtime_to_utc(monkeypatch, fs):is_dir=False,)]- patch_tree_env(monkeypatch, fs, entries, batch_fetch=default_batch_fetch)+ patch_tree_env(monkeypatch, fs, entries)monkeypatch.setattr(viking_fs_module, "datetime", _FixedDatetime)- result = await fs._tree_agent(+ result = await fs.tree("viking://resources",+ output="agent",abs_limit=256,ctx=_default_ctx(),)@@ -722,8 +756,8 @@ async def test_ls_agent_modtime_is_raw_utc_iso(monkeypatch, fs):monkeypatch.setattr(fs, "_ls_entries", fake_ls_entries)monkeypatch.setattr(fs, "_path_to_uri", _std_path_to_uri)monkeypatch.setattr(fs, "_is_accessible", lambda _uri, _ctx: True)- monkeypatch.setattr(fs, "_batch_fetch_abstracts", default_batch_fetch)monkeypatch.setattr(viking_fs_module, "datetime", _FixedDatetime)+async def acl_enabled(_account_id):return True@@ -760,75 +794,62 @@ async def test_ls_agent_modtime_is_raw_utc_iso(monkeypatch, fs):@pytest.mark.asyncio-async def test_tree_agent_abs_limit_truncation(monkeypatch, fs):- """PY-AGENT-005: abstract is truncated when exceeding abs_limit."""- entries = [make_entry("/local/test_account/resources/sub", "sub", is_dir=True)]-- async def fake_batch_fetch(entries_arg, abs_limit, **_kwargs):- for entry in entries_arg:- abstract = "x" * (abs_limit + 10) if entry.get("isDir") else ""- if len(abstract) > abs_limit:- abstract = abstract[: abs_limit - 3] + "..."- entry["abstract"] = abstract-- patch_tree_env(monkeypatch, fs, entries, batch_fetch=fake_batch_fetch)-- result = await fs._tree_agent("viking://resources", abs_limit=10, ctx=_default_ctx())- assert len(result[0]["abstract"]) <= 10- assert result[0]["abstract"].endswith("...")---async def test_tree_agent_batch_fetch_input_order(monkeypatch, fs):- """PY-AGENT-006: _batch_fetch_abstracts receives entries in correct order."""- captured_entries = None-+async def test_tree_filters_and_paginates_before_summary_reads(monkeypatch, fs):+ """Only selected directories consume node slots and summary reads."""entries = [- make_entry("/local/test_account/resources/a", "a", size=100, mode=0o644, is_dir=False),- make_entry(- "/local/test_account/resources/b",- "b",- size=200,- mode=0o644,- mod_time="2026-01-02T00:00:00Z",- is_dir=False,- ),+ make_entry(f"/local/test_account/resources/{name}", is_dir=is_dir)+ for name, is_dir in [+ ("file-a.md", False),+ ("dir-a", True),+ ("dir-a/.abstract.md", False),+ ("dir-a/.overview.md", False),+ ("file-b.md", False),+ ("dir-b", True),+ ("dir-c", True),+ ("dir-d", True),+ ]]- async def fake_batch_fetch(entries_arg, _abs_limit, **_kwargs):- nonlocal captured_entries- captured_entries = list(entries_arg)- for entry in entries_arg:- entry["abstract"] = ""-- patch_tree_env(monkeypatch, fs, entries, batch_fetch=fake_batch_fetch)-- await fs._tree_agent("viking://resources", abs_limit=256, ctx=_default_ctx())- assert len(captured_entries) == 2- assert captured_entries[0]["uri"] == "viking://resources/a"- assert captured_entries[1]["uri"] == "viking://resources/b"+ async def fake_tree_directory(path, **kwargs):+ filtered = entries+ if kwargs.get("directories_only"):+ filtered = [entry for entry in entries if entry["info"]["isDir"]]+ offset = kwargs.get("offset", 0)+ limit = kwargs.get("node_limit")+ page = filtered[offset : offset + limit if limit is not None else None]+ return _with_query_relative_paths(page, path)+ patch_tree_env(monkeypatch, fs, fake_tree_directory)+ abstract = AsyncMock(return_value="L0 summary")+ overview = AsyncMock(return_value="L1 overview")+ monkeypatch.setattr(fs, "_read_abstract_for_known_dir", abstract)+ monkeypatch.setattr(fs, "overview", overview)-async def test_tree_agent_node_limit_before_enrichment(monkeypatch, fs):- """PY-AGENT-007: node_limit applied before abstract enrichment."""- enriched_count = 0+ result = await fs.tree(+ "viking://resources",+ output="original",+ directories_only=True,+ show_all_hidden=True,+ offset=1,+ node_limit=2,+ include_abstract=True,+ include_overview=True,+ abs_limit=5,+ overview_limit=7,+ ctx=_default_ctx(),+ )- entries = [- make_entry(f"/local/test_account/resources/{name}", name, is_dir=False)- for name in ["a", "b", "c", "d", "e"]+ assert [entry["uri"] for entry in result] == [+ "viking://resources/dir-b",+ "viking://resources/dir-c",]-- async def fake_batch_fetch(entries_arg, _abs_limit, **_kwargs):- nonlocal enriched_count- enriched_count = len(entries_arg)- for entry in entries_arg:- entry["abstract"] = ""-- patch_tree_env(monkeypatch, fs, entries, batch_fetch=fake_batch_fetch)-- result = await fs._tree_agent(- "viking://resources", node_limit=2, abs_limit=256, ctx=_default_ctx()- )- assert len(result) == 2- assert enriched_count == 2+ assert all(entry["isDir"] for entry in result)+ assert [(entry["abstract"], entry["overview"]) for entry in result] == [+ ("L0...", "L1 o..."),+ ("L0...", "L1 o..."),+ ]+ for reader in (abstract, overview):+ assert sorted(call.args[0] for call in reader.await_args_list) == [+ "viking://resources/dir-b",+ "viking://resources/dir-c",+ ]