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: CLI optmization for counting (#1980)
MaojiaShengc2345b9e6a40
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex 57e7a86ef..4e98379c3 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -303,13 +303,12 @@ impl HttpClient {Ok(())}- pub async fn rm(&self, uri: &str, recursive: bool) -> Result<()> {+ pub async fn rm(&self, uri: &str, recursive: bool) -> Result<serde_json::Value> {let params = vec![("uri".to_string(), uri.to_string()),("recursive".to_string(), recursive.to_string()),];- let _: serde_json::Value = self.delete("/api/v1/fs", ¶ms).await?;- Ok(())+ self.delete("/api/v1/fs", ¶ms).await}pub async fn mv(&self, from_uri: &str, to_uri: &str) -> Result<()> {@@ -337,6 +336,7 @@ impl HttpClient {since: Option<String>,until: Option<String>,time_field: Option<String>,+ level: Option<String>,) -> Result<serde_json::Value> {let body = serde_json::json!({"query": query,@@ -346,6 +346,7 @@ impl HttpClient {"since": since,"until": until,"time_field": time_field,+ "level": level,});self.post("/api/v1/search/find", &body).await}@@ -360,6 +361,7 @@ impl HttpClient {since: Option<String>,until: Option<String>,time_field: Option<String>,+ level: Option<String>,) -> Result<serde_json::Value> {let body = serde_json::json!({"query": query,@@ -370,6 +372,7 @@ impl HttpClient {"since": since,"until": until,"time_field": time_field,+ "level": level,});self.post("/api/v1/search/search", &body).await}diff --git a/crates/ov_cli/src/commands/filesystem.rs b/crates/ov_cli/src/commands/filesystem.rsindex 956b3bce0..daa0c8f03 100644--- a/crates/ov_cli/src/commands/filesystem.rs+++ b/crates/ov_cli/src/commands/filesystem.rs@@ -73,8 +73,15 @@ pub async fn rm(_output_format: OutputFormat,_compact: bool,) -> Result<()> {- client.rm(uri, recursive).await?;- println!("Removed: {}", uri);+ let result = client.rm(uri, recursive).await?;++ // Try to extract estimated_deleted_count if available+ if let Some(count) = result.get("estimated_deleted_count").and_then(|v| v.as_u64()) {+ println!("Removed: {} ({} items)", uri, count);+ } else {+ println!("Removed: {}", uri);+ }+Ok(())}diff --git a/crates/ov_cli/src/commands/search.rs b/crates/ov_cli/src/commands/search.rsindex 0c5c286aa..05d07297a 100644--- a/crates/ov_cli/src/commands/search.rs+++ b/crates/ov_cli/src/commands/search.rs@@ -11,6 +11,7 @@ pub async fn find(since: Option<&str>,until: Option<&str>,time_field: Option<&str>,+ level: Option<&str>,output_format: OutputFormat,compact: bool,) -> Result<()> {@@ -23,6 +24,7 @@ pub async fn find(since.map(|s| s.to_string()),until.map(|s| s.to_string()),time_field.map(|s| s.to_string()),+ level.map(|s| s.to_string()),).await?;output_success(&result, output_format, compact);@@ -39,6 +41,7 @@ pub async fn search(since: Option<&str>,until: Option<&str>,time_field: Option<&str>,+ level: Option<&str>,output_format: OutputFormat,compact: bool,) -> Result<()> {@@ -52,6 +55,7 @@ pub async fn search(since.map(|s| s.to_string()),until.map(|s| s.to_string()),time_field.map(|s| s.to_string()),+ level.map(|s| s.to_string()),).await?;output_success(&result, output_format, compact);diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rsindex 831928b1f..f9670d226 100644--- a/crates/ov_cli/src/handlers.rs+++ b/crates/ov_cli/src/handlers.rs@@ -949,6 +949,7 @@ pub async fn handle_find(threshold: Option<f64>,after: Option<String>,before: Option<String>,+ level: Option<String>,ctx: CliContext,) -> Result<()> {let mut params = vec![format!("--uri={}", uri), format!("-n {}", node_limit)];@@ -956,6 +957,7 @@ pub async fn handle_find(params.push(format!("--threshold {}", t));}append_time_filter_params(&mut params, after.as_deref(), before.as_deref());+ append_level_filter_params(&mut params, level.as_deref());params.push(format!("\"{}\"", query));print_command_echo("ov find", ¶ms.join(" "), ctx.config.echo_command);let client = ctx.get_client();@@ -968,6 +970,7 @@ pub async fn handle_find(after.as_deref(),before.as_deref(),None,+ level.as_deref(),ctx.output_format,ctx.compact,)@@ -982,6 +985,7 @@ pub async fn handle_search(threshold: Option<f64>,after: Option<String>,before: Option<String>,+ level: Option<String>,ctx: CliContext,) -> Result<()> {let mut params = vec![format!("--uri={}", uri), format!("-n {}", node_limit)];@@ -992,6 +996,7 @@ pub async fn handle_search(params.push(format!("--threshold {}", t));}append_time_filter_params(&mut params, after.as_deref(), before.as_deref());+ append_level_filter_params(&mut params, level.as_deref());params.push(format!("\"{}\"", query));print_command_echo("ov search", ¶ms.join(" "), ctx.config.echo_command);let client = ctx.get_client();@@ -1005,6 +1010,7 @@ pub async fn handle_search(after.as_deref(),before.as_deref(),None,+ level.as_deref(),ctx.output_format,ctx.compact,)@@ -1024,6 +1030,15 @@ pub fn append_time_filter_params(}}+pub fn append_level_filter_params(+ params: &mut Vec<String>,+ level: Option<&str>,+) {+ if let Some(value) = level {+ params.push(format!("--level {}", value));+ }+}+/// Print command with specified parameters for debuggingpub fn print_command_echo(command: &str, params: &str, echo_enabled: bool) {if echo_enabled {diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex 170da19f7..64302da15 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -378,6 +378,9 @@ enum Commands {/// Only include results on or before this time (e.g. 24h, 2026-03-15, ISO-8601)#[arg(long = "before")]before: Option<String>,+ /// Only include results with specific level(s) (e.g. 0, 1, 2 or 0,1,2)+ #[arg(short = 'L', long = "level")]+ level: Option<String>,},/// [Experimental][Data] Run context-aware retrievalSearch {@@ -406,6 +409,9 @@ enum Commands {/// Only include results on or before this time (e.g. 24h, 2026-03-15, ISO-8601)#[arg(long = "before")]before: Option<String>,+ /// Only include results with specific level(s) (e.g. 0, 1, 2 or 0,1,2)+ #[arg(short = 'L', long = "level")]+ level: Option<String>,},/// [Data] Run content pattern searchGrep {@@ -1246,7 +1252,8 @@ async fn main() {threshold,after,before,- } => handlers::handle_find(query, uri, node_limit, threshold, after, before, ctx).await,+ level,+ } => handlers::handle_find(query, uri, node_limit, threshold, after, before, level, ctx).await,Commands::Search {query,uri,@@ -1255,9 +1262,10 @@ async fn main() {threshold,after,before,+ level,} => {handlers::handle_search(- query, uri, session_id, node_limit, threshold, after, before, ctx,+ query, uri, session_id, node_limit, threshold, after, before, level, ctx,).await}diff --git a/docs/en/api/03-filesystem.md b/docs/en/api/03-filesystem.mdindex f4bf64ef1..1c6e8f171 100644--- a/docs/en/api/03-filesystem.md+++ b/docs/en/api/03-filesystem.md@@ -421,7 +421,7 @@ openviking tree viking://resources/my-project/### stat()-Get file or directory status information.+Get file or directory status information. For directories, returns the count of items under the directory.**Parameters**@@ -435,6 +435,11 @@ Get file or directory status information.info = client.stat("viking://resources/docs/api.md")print(f"Size: {info['size']}")print(f"Is directory: {info['isDir']}")++# For directories, returns item count+dir_info = client.stat("viking://resources/docs")+if dir_info.get('isDir'):+ print(f"Item count: {dir_info.get('count')}")```**HTTP API**@@ -452,9 +457,10 @@ curl -X GET "http://localhost:1933/api/v1/fs/stat?uri=viking://resources/docs/ap```bashopenviking stat viking://resources/my-project/docs/api.md+openviking stat viking://resources/my-project/docs```-**Response**+**Response (File)**```json{@@ -472,8 +478,29 @@ openviking stat viking://resources/my-project/docs/api.md}```+**Response (Directory)**++```json+{+ "status": "ok",+ "result": {+ "name": "docs",+ "size": 4096,+ "mode": 16877,+ "modTime": "2024-01-01T00:00:00Z",+ "isDir": true,+ "isLocked": false,+ "uri": "viking://resources/docs",+ "count": 42+ },+ "time": 0.1+}+```+The `isLocked` field reports whether the path is currently held by a path lock — either the path itself has a valid `.path.ovlock`, or any ancestor directory holds a SUBTREE lock. Returns `false` when the LockManager is unavailable or the lookup fails, so callers can avoid attempting a write only to observe `ResourceBusyError`.+The `count` field (directories only) contains the estimated number of items (files and subdirectories) under this directory (from vector index).+---### mkdir()@@ -533,7 +560,7 @@ openviking mkdir viking://resources/new-project/ --description "API docs directo### rm()-Remove file or directory.+Remove file or directory. When removing directories recursively, returns the estimated number of items deleted.`rm` is idempotent: removing a valid URI that does not exist still succeeds.Invalid URI formats, unsupported schemes, and non-public scopes return `INVALID_URI`.@@ -552,7 +579,9 @@ Invalid URI formats, unsupported schemes, and non-public scopes return `INVALID_client.rm("viking://resources/docs/old.md")# Remove directory recursively-client.rm("viking://resources/old-project/", recursive=True)+result = client.rm("viking://resources/old-project/", recursive=True)+if 'estimated_deleted_count' in result:+ print(f"Deleted {result['estimated_deleted_count']} items")```**HTTP API**@@ -577,7 +606,7 @@ curl -X DELETE "http://localhost:1933/api/v1/fs?uri=viking://resources/old-projeopenviking rm viking://resources/old.md [--recursive]```-**Response**+**Response (Single file)**```json{@@ -589,6 +618,21 @@ openviking rm viking://resources/old.md [--recursive]}```+**Response (Recursive delete)**++```json+{+ "status": "ok",+ "result": {+ "uri": "viking://resources/old-project/",+ "estimated_deleted_count": 42+ },+ "time": 0.1+}+```++The `estimated_deleted_count` field (for recursive deletes) contains the estimated number of items (files and directories) deleted (from vector index). The CLI will display this information in output.+---### mv()diff --git a/docs/en/api/06-retrieval.md b/docs/en/api/06-retrieval.mdindex fb8218eb1..7a79b42ab 100644--- a/docs/en/api/06-retrieval.md+++ b/docs/en/api/06-retrieval.md@@ -63,6 +63,7 @@ The `find()` method performs pure vector similarity search for simple query scen| since | str | No | None | Lower time bound, accepts `2h` or ISO 8601 / `YYYY-MM-DD`. Timezone-less values are interpreted as UTC. CLI `--after` maps to this field || until | str | No | None | Upper time bound, accepts `30m` or ISO 8601 / `YYYY-MM-DD`. Timezone-less values are interpreted as UTC. CLI `--before` maps to this field || time_field | "updated_at" \| "created_at" | No | "updated_at" | Metadata time field used by `since` / `until` |+| level | str | No | None | Limit results to specific level(s), e.g., `0`, `1`, `2`, or `0,1,2`. CLI `--level`/`-L` maps to this field || include_provenance | bool | No | False | Include provenance/query-plan details in serialized result || telemetry | bool \| object | No | False | Attach telemetry data to response |@@ -195,6 +196,12 @@ openviking find "invoice" --after 7d# With limitopenviking find "how to authenticate users" --limit 20++# Limit to specific level(s) (L0 only)+openviking find "how to authenticate users" --level 0++# Limit to specific level(s) (L1 and L2) using short option+openviking find "how to authenticate users" -L 1,2```**Response Example**@@ -274,6 +281,7 @@ The `search()` method adds session context understanding and intent analysis cap| since | str | No | None | Lower time bound, accepts `2h` or ISO 8601 / `YYYY-MM-DD`. Timezone-less values are interpreted as UTC. CLI `--after` maps to this field || until | str | No | None | Upper time bound, accepts `30m` or ISO 8601 / `YYYY-MM-DD`. Timezone-less values are interpreted as UTC. CLI `--before` maps to this field || time_field | "updated_at" \| "created_at" | No | "updated_at" | Metadata time field used by `since` / `until` |+| level | str | No | None | Limit results to specific level(s), e.g., `0`, `1`, `2`, or `0,1,2`. CLI `--level`/`-L` maps to this field || include_provenance | bool | No | False | Include provenance/query-plan details in serialized result || telemetry | bool \| object | No | False | Attach telemetry data to response |@@ -363,6 +371,12 @@ openviking search "watch vs scheduled" --after 2026-03-15 --before 2026-03-20# Search without session (still performs intent analysis)openviking search "how to implement OAuth 2.0 authorization code flow"++# Limit to specific level(s) (L0 only)+openviking search "best practices" --level 0++# Limit to specific level(s) (L1 and L2) using short option+openviking search "how to implement OAuth" -L 1,2```**Response Example**diff --git a/docs/zh/api/03-filesystem.md b/docs/zh/api/03-filesystem.mdindex e3b9a969e..d53b21916 100644--- a/docs/zh/api/03-filesystem.md+++ b/docs/zh/api/03-filesystem.md@@ -421,7 +421,7 @@ openviking tree viking://resources/my-project/### stat()-获取文件或目录的状态信息。+获取文件或目录的状态信息。对于目录,会返回目录下的项目计数。**参数**@@ -435,6 +435,11 @@ openviking tree viking://resources/my-project/info = client.stat("viking://resources/docs/api.md")print(f"Size: {info['size']}")print(f"Is directory: {info['isDir']}")++# 对于目录,会返回项目计数+dir_info = client.stat("viking://resources/docs")+if dir_info.get('isDir'):+ print(f"Item count: {dir_info.get('count')}")```**HTTP API**@@ -452,9 +457,10 @@ curl -X GET "http://localhost:1933/api/v1/fs/stat?uri=viking://resources/docs/ap```bashopenviking stat viking://resources/my-project/docs/api.md+openviking stat viking://resources/my-project/docs```-**响应**+**响应(文件)**```json{@@ -472,8 +478,29 @@ openviking stat viking://resources/my-project/docs/api.md}```+**响应(目录)**++```json+{+ "status": "ok",+ "result": {+ "name": "docs",+ "size": 4096,+ "mode": 16877,+ "modTime": "2024-01-01T00:00:00Z",+ "isDir": true,+ "isLocked": false,+ "uri": "viking://resources/docs",+ "count": 42+ },+ "time": 0.1+}+```+`isLocked` 字段反映路径当前是否被 path lock 持有:路径自身存在有效的 `.path.ovlock`,或者任一祖先目录持有 SUBTREE 锁。当 LockManager 不可用或查询失败时返回 `false`,调用方可据此避免先写入再观察到 `ResourceBusyError`。+`count` 字段(仅目录)包含该目录下的项目(文件和子目录)估计数量(来自向量索引)。+---### mkdir()@@ -533,7 +560,7 @@ openviking mkdir viking://resources/new-project/ --description "接口文档目### rm()-删除文件或目录。+删除文件或目录。递归删除目录时会返回删除的项目估计数量。`rm` 是幂等操作:删除一个合法但不存在的 URI 仍会成功。URI 格式非法、scheme 不支持或使用非公开作用域时返回 `INVALID_URI`。@@ -552,7 +579,9 @@ URI 格式非法、scheme 不支持或使用非公开作用域时返回 `INVALIDclient.rm("viking://resources/docs/old.md")# 递归删除目录-client.rm("viking://resources/old-project/", recursive=True)+result = client.rm("viking://resources/old-project/", recursive=True)+if 'estimated_deleted_count' in result:+ print(f"Deleted {result['estimated_deleted_count']} items")```**HTTP API**@@ -577,7 +606,7 @@ curl -X DELETE "http://localhost:1933/api/v1/fs?uri=viking://resources/old-projeopenviking rm viking://resources/old.md [--recursive]```-**响应**+**响应(单个文件)**```json{@@ -589,6 +618,21 @@ openviking rm viking://resources/old.md [--recursive]}```+**响应(递归删除)**++```json+{+ "status": "ok",+ "result": {+ "uri": "viking://resources/old-project/",+ "estimated_deleted_count": 42+ },+ "time": 0.1+}+```++`estimated_deleted_count` 字段(递归删除时)包含删除的项目(文件和目录)估计数量(来自向量索引)。CLI 会在输出中显示此信息。+---### mv()diff --git a/docs/zh/api/06-retrieval.md b/docs/zh/api/06-retrieval.mdindex aae22ba4b..ca2806dc9 100644--- a/docs/zh/api/06-retrieval.md+++ b/docs/zh/api/06-retrieval.md@@ -63,6 +63,7 @@ OpenViking 提供多种检索方法,包括简单的向量相似度搜索、带| since | str | 否 | None | 时间下界,支持 `2h` 或 ISO 8601 / `YYYY-MM-DD`。不带时区的值按 UTC 解释。CLI `--after` 会映射到这个字段 || until | str | 否 | None | 时间上界,支持 `30m` 或 ISO 8601 / `YYYY-MM-DD`。不带时区的值按 UTC 解释。CLI `--before` 会映射到这个字段 || time_field | "updated_at" \| "created_at" | 否 | "updated_at" | since/until 使用的元数据时间字段 |+| level | str | 否 | None | 限定结果的层级范围,例如 `0`、`1`、`2` 或 `0,1,2`。CLI `--level`/`-L` 会映射到这个字段 || include_provenance | bool | 否 | False | 在序列化结果中附带 provenance / query-plan 细节 || telemetry | bool \| object | 否 | False | 在响应中附带遥测数据 |@@ -195,6 +196,12 @@ openviking find "invoice" --after 7d# 带限制数量openviking find "how to authenticate users" --limit 20++# 限定层级范围 (仅 L0)+openviking find "how to authenticate users" --level 0++# 限定层级范围 (L1 和 L2),使用短选项+openviking find "how to authenticate users" -L 1,2```**响应示例**@@ -274,6 +281,7 @@ openviking find "how to authenticate users" --limit 20| since | str | 否 | None | 时间下界,支持 `2h` 或 ISO 8601 / `YYYY-MM-DD`。不带时区的值按 UTC 解释。CLI `--after` 会映射到这个字段 || until | str | 否 | None | 时间上界,支持 `30m` 或 ISO 8601 / `YYYY-MM-DD`。不带时区的值按 UTC 解释。CLI `--before` 会映射到这个字段 || time_field | "updated_at" \| "created_at" | 否 | "updated_at" | since/until 使用的元数据时间字段 |+| level | str | 否 | None | 限定结果的层级范围,例如 `0`、`1`、`2` 或 `0,1,2`。CLI `--level`/`-L` 会映射到这个字段 || include_provenance | bool | 否 | False | 在序列化结果中附带 provenance / query-plan 细节 || telemetry | bool \| object | 否 | False | 在响应中附带遥测数据 |@@ -363,6 +371,12 @@ openviking search "watch vs scheduled" --after 2026-03-15 --before 2026-03-20# 不带会话的搜索(仍进行意图分析)openviking search "how to implement OAuth 2.0 authorization code flow"++# 限定层级范围(仅 L0)+openviking search "best practices" --level 0++# 限定层级范围(L1 和 L2),使用短选项+openviking search "how to implement OAuth" -L 1,2```**响应示例**diff --git a/openviking/server/routers/filesystem.py b/openviking/server/routers/filesystem.pyindex 13530ce5f..69f2a8bd4 100644--- a/openviking/server/routers/filesystem.py+++ b/openviking/server/routers/filesystem.py@@ -160,7 +160,7 @@ async def rm(# Resolve path variablesuri = resolve_path_variables(uri)try:- await service.fs.rm(uri, ctx=_ctx, recursive=recursive)+ result = await service.fs.rm(uri, ctx=_ctx, recursive=recursive)except AGFSNotFoundError:raise NotFoundError(uri, "file")except AGFSClientError as e:@@ -173,7 +173,11 @@ async def rm(if mapped is not None:raise mapped from excraise- return Response(status="ok", result={"uri": uri})+ # Build response with uri and estimated_deleted_count+ response_result = {"uri": uri}+ if isinstance(result, dict) and "estimated_deleted_count" in result:+ response_result["estimated_deleted_count"] = result["estimated_deleted_count"]+ return Response(status="ok", result=response_result)class MvRequest(BaseModel):diff --git a/openviking/server/routers/search.py b/openviking/server/routers/search.pyindex d1128c110..b6036dbfb 100644--- a/openviking/server/routers/search.py+++ b/openviking/server/routers/search.py@@ -17,7 +17,7 @@ from openviking.server.identity import RequestContextfrom openviking.server.models import Responsefrom openviking.server.telemetry import run_operationfrom openviking.telemetry import TelemetryRequest-from openviking.utils.search_filters import merge_time_filter+from openviking.utils.search_filters import merge_time_filter, merge_level_filterfrom openviking_cli.exceptions import InvalidArgumentError, NotFoundError@@ -47,14 +47,16 @@ def _resolve_search_filter(since: Optional[str],until: Optional[str],time_field: Optional[TimeField],+ level: Optional[Union[int, str, List[int]]] = None,) -> Optional[Dict[str, Any]]:try:- return merge_time_filter(+ filter_with_time = merge_time_filter(request_filter,since=since,until=until,time_field=time_field,)+ return merge_level_filter(filter_with_time, level=level)except ValueError as exc:raise InvalidArgumentError(str(exc)) from exc@@ -80,6 +82,7 @@ class FindRequest(BaseModel):since: Optional[str] = Noneuntil: Optional[str] = Nonetime_field: Optional[TimeField] = None+ level: Optional[Union[int, str, List[int]]] = Nonetelemetry: TelemetryRequest = False@@ -98,6 +101,7 @@ class SearchRequest(BaseModel):since: Optional[str] = Noneuntil: Optional[str] = Nonetime_field: Optional[TimeField] = None+ level: Optional[Union[int, str, List[int]]] = Nonetelemetry: TelemetryRequest = False@@ -133,6 +137,7 @@ async def find(request.since,request.until,request.time_field,+ request.level,)resolved_target_uri = _resolve_uri_or_uris(request.target_uri)execution = await run_operation(@@ -171,6 +176,7 @@ async def search(request.since,request.until,request.time_field,+ request.level,)resolved_target_uri = _resolve_uri_or_uris(request.target_uri)diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.pyindex 5cc8fe6de..64a9d8355 100644--- a/openviking/service/fs_service.py+++ b/openviking/service/fs_service.py@@ -157,11 +157,11 @@ class FSService:directory_uri = VikingURI(abstract_uri).parent.urireturn directory_uri, abstract_uri- async def rm(self, uri: str, ctx: RequestContext, recursive: bool = False) -> None:+ async def rm(self, uri: str, ctx: RequestContext, recursive: bool = False) -> Optional[Dict[str, Any]]:"""Remove resource."""uri = validate_viking_uri(uri)viking_fs = self._ensure_initialized()- await viking_fs.rm(uri, recursive=recursive, ctx=ctx)+ return await viking_fs.rm(uri, recursive=recursive, ctx=ctx)async def mv(self, from_uri: str, to_uri: str, ctx: RequestContext) -> None:"""Move resource."""diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.pyindex 9bf623e89..49cfa0cc4 100644--- a/openviking/storage/viking_fs.py+++ b/openviking/storage/viking_fs.py@@ -31,6 +31,7 @@ from openviking.core.namespace import (from openviking.core.namespace import (is_accessible as namespace_is_accessible,)+from openviking.storage.expr import PathScopefrom openviking.pyagfs.exceptions import (AGFSClientError,AGFSDirectoryNotEmptyError,@@ -432,6 +433,10 @@ class VikingFS:Acquires a path lock, deletes VectorDB records, then FS files.Raises ResourceBusyError when the target is locked by an ongoingoperation (e.g. semantic processing).++ Returns:+ Dict with 'estimated_deleted_count' indicating the estimated number+ of nodes deleted from vector index."""from openviking.storage.errors import LockAcquisitionError, ResourceBusyErrorfrom openviking.storage.transaction import LockContext, get_lock_manager@@ -440,6 +445,23 @@ class VikingFS:path = self._uri_to_path(uri, ctx=ctx)target_uri = self._path_to_uri(path, ctx=ctx)+ async def _estimate_deleted_count(+ target_path: str, real_ctx: RequestContext+ ) -> int:+ """Estimate number of nodes to be deleted using vector index."""+ vector_store = self._get_vector_store()+ if not vector_store:+ return 0+ try:+ target_canonical_uri = canonicalize_uri(+ self._path_to_uri(target_path, ctx=real_ctx), real_ctx+ )+ filter_expr = PathScope("uri", target_canonical_uri, depth=-1)+ return await vector_store.count(filter=filter_expr, ctx=real_ctx)+ except Exception as e:+ logger.warning(f"[VikingFS] Failed to count nodes before delete: {e}")+ return 0+# Check existence and determine lock strategytry:stat = self.agfs.stat(path)@@ -453,9 +475,11 @@ class VikingFS:# Path does not exist: clean up any orphan index records and returnuris_to_delete = await self._collect_uris(path, recursive, ctx=ctx)uris_to_delete.append(target_uri)+ real_ctx = self._ctx_or_default(ctx)+ estimated_count = await _estimate_deleted_count(path, real_ctx)await self._delete_from_vector_store(uris_to_delete, ctx=ctx)logger.info(f"[VikingFS] rm target not found, cleaned orphan index: {uri}")- return {}+ return {"estimated_deleted_count": estimated_count}if is_dir:if not recursive:@@ -479,6 +503,8 @@ class VikingFS:):uris_to_delete = await self._collect_uris(path, recursive, ctx=ctx)uris_to_delete.append(target_uri)+ real_ctx = self._ctx_or_default(ctx)+ estimated_count = await _estimate_deleted_count(path, real_ctx)await self._delete_from_vector_store(uris_to_delete, ctx=ctx)try:result = self.agfs.rm(path, recursive=recursive)@@ -493,6 +519,11 @@ class VikingFS:f"Directory not empty: {uri}. Use recursive=True to delete non-empty directories.")raise+ # Add estimated_deleted_count to the result+ if isinstance(result, dict):+ result["estimated_deleted_count"] = estimated_count+ else:+ result = {"estimated_deleted_count": estimated_count}return resultexcept LockAcquisitionError:raise ResourceBusyError(f"Resource is being processed: {uri}")@@ -945,19 +976,35 @@ class VikingFS:"""File/directory information.- example: {'name': 'resources', 'size': 128, 'mode': 2147484141, 'modTime': '2026-02-10T21:26:02.934376379+08:00', 'isDir': True, 'isLocked': False, 'meta': {'Name': 'localfs', 'Type': 'local', 'Content': {'local_path': '...'}}}+ 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:isLocked (bool): Whether the path is currently held by a path lock(either the path itself or any ancestor directory). ReturnsFalse when the LockManager is not initialized or the lookupfails.+ count (int): For directories, the number of nodes in the vector index+ under this directory (including subdirectories). For files, this+ field is not included."""self._ensure_access(uri, ctx)path = self._uri_to_path(uri, ctx=ctx)result = self.agfs.stat(path)if isinstance(result, dict):result["isLocked"] = self._is_path_locked(path)+ # Add count for directories if vector store available+ if result.get("isDir", False):+ try:+ vector_store = self._get_vector_store()+ if vector_store:+ real_ctx = self._ctx_or_default(ctx)+ target_canonical_uri = canonicalize_uri(+ self._path_to_uri(path, ctx=real_ctx), real_ctx+ )+ filter_expr = PathScope("uri", target_canonical_uri, depth=-1)+ result["count"] = await vector_store.count(filter=filter_expr, ctx=real_ctx)+ except Exception as e:+ logger.warning(f"[VikingFS] Failed to count nodes for directory stat: {e}")return resultdef _is_path_locked(self, path: str) -> bool:diff --git a/openviking/utils/search_filters.py b/openviking/utils/search_filters.pyindex 677e0ce95..1a80d314d 100644--- a/openviking/utils/search_filters.py+++ b/openviking/utils/search_filters.py@@ -5,7 +5,7 @@ from __future__ import annotationsimport refrom datetime import datetime, time, timedelta, timezone-from typing import Any, Dict, Literal, Optional+from typing import Any, Dict, List, Literal, Optional, Unionfrom openviking.utils.time_utils import format_iso8601, parse_iso_datetime@@ -44,6 +44,73 @@ def merge_time_filter(return {"op": "and", "conds": [existing_filter, time_filter]}+def merge_level_filter(+ existing_filter: Optional[Dict[str, Any]],+ level: Optional[Union[int, str, List[int]]] = None,+) -> Optional[Dict[str, Any]]:+ """Merge level filter into an existing metadata filter tree."""+ levels = _resolve_levels(level)+ if not levels:+ return existing_filter++ level_filter: Dict[str, Any] = {"op": "must", "field": "level", "conds": levels}++ if not existing_filter:+ return level_filter+ # Preserve any caller-supplied metadata predicates by AND-ing the level filter+ # into the existing filter tree instead of replacing it.+ return {"op": "and", "conds": [existing_filter, level_filter]}+++def _resolve_levels(+ level: Optional[Union[int, str, List[int], List[str]]]+) -> List[int]:+ """Resolve level parameter into a list of integers."""+ if level is None:+ return []++ if isinstance(level, int):+ return [level]++ if isinstance(level, list):+ result = []+ for item in level:+ if isinstance(item, int):+ result.append(item)+ elif isinstance(item, str):+ try:+ result.append(int(item.strip()))+ except ValueError:+ continue+ return result++ if isinstance(level, str):+ level_str = level.strip()+ if not level_str:+ return []++ # Support comma-separated values+ if "," in level_str:+ parts = level_str.split(",")+ result = []+ for part in parts:+ part = part.strip()+ if part:+ try:+ result.append(int(part))+ except ValueError:+ continue+ return result++ # Single value+ try:+ return [int(level_str)]+ except ValueError:+ return []++ return []++def normalize_time_field(time_field: Optional[str]) -> str:normalized = (time_field or "updated_at").strip() or "updated_at"if normalized not in VALID_TIME_FIELDS:diff --git a/tests/unit/test_search_filters.py b/tests/unit/test_search_filters.pyindex 32fd239b0..999a817b8 100644--- a/tests/unit/test_search_filters.py+++ b/tests/unit/test_search_filters.py@@ -5,7 +5,7 @@ from datetime import datetime, timezoneimport pytest-from openviking.utils.search_filters import merge_time_filter+from openviking.utils.search_filters import merge_time_filter, merge_level_filterfrom openviking.utils.time_utils import parse_iso_datetime@@ -119,3 +119,70 @@ def test_merge_time_filter_date_only_uses_now_timezone():assert result["gte"].endswith("Z")assert result["lte"].endswith("Z")+++def test_merge_level_filter_with_single_level():+ result = merge_level_filter(None, level=0)+ assert result == {"op": "must", "field": "level", "conds": [0]}+++def test_merge_level_filter_with_multiple_levels():+ result = merge_level_filter(None, level=[0, 1])+ assert result == {"op": "must", "field": "level", "conds": [0, 1]}+++def test_merge_level_filter_with_comma_separated_string():+ result = merge_level_filter(None, level="0,1,2")+ assert result == {"op": "must", "field": "level", "conds": [0, 1, 2]}+++def test_merge_level_filter_with_single_string():+ result = merge_level_filter(None, level="0")+ assert result == {"op": "must", "field": "level", "conds": [0]}+++def test_merge_level_filter_merges_with_existing_filter():+ existing_filter = {"op": "must", "field": "kind", "conds": ["email"]}++ result = merge_level_filter(existing_filter, level=2)++ assert result == {+ "op": "and",+ "conds": [+ existing_filter,+ {"op": "must", "field": "level", "conds": [2]},+ ],+ }+++def test_merge_level_filter_with_none_returns_existing():+ existing_filter = {"op": "must", "field": "kind", "conds": ["email"]}+ result = merge_level_filter(existing_filter, level=None)+ assert result == existing_filter+++def test_merge_level_filter_with_empty_string_returns_existing():+ existing_filter = {"op": "must", "field": "kind", "conds": ["email"]}+ result = merge_level_filter(existing_filter, level="")+ assert result == existing_filter+++def test_merge_level_filter_with_empty_list_returns_existing():+ existing_filter = {"op": "must", "field": "kind", "conds": ["email"]}+ result = merge_level_filter(existing_filter, level=[])+ assert result == existing_filter+++def test_merge_level_filter_with_mixed_types_list():+ result = merge_level_filter(None, level=[0, "1", 2])+ assert result == {"op": "must", "field": "level", "conds": [0, 1, 2]}+++def test_merge_level_filter_with_spaces_in_comma_string():+ result = merge_level_filter(None, level="0, 1, 2")+ assert result == {"op": "must", "field": "level", "conds": [0, 1, 2]}+++def test_merge_level_filter_skips_invalid_values():+ result = merge_level_filter(None, level="0,invalid,2")+ assert result == {"op": "must", "field": "level", "conds": [0, 2]}