Skip to content

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

feat(retriever): add level filter to find with retriever-level filtering, preserving recursive navigation (#1988)

zgy79389ee4745d
diff --git a/Cargo.lock b/Cargo.lock
index 9f8b60a76..d7da5ced8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3261,7 +3261,7 @@ checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e"
[[package]]
name = "ov_cli"
-version = "0.3.14"
+version = "0.0.0"
dependencies = [
"anyhow",
"bytes",
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index 4e98379c3..207641286 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -336,7 +336,7 @@ impl HttpClient {
since: Option<String>,
until: Option<String>,
time_field: Option<String>,
- level: Option<String>,
+ level: Option<Vec<i32>>,
) -> Result<serde_json::Value> {
let body = serde_json::json!({
"query": query,
@@ -361,7 +361,7 @@ impl HttpClient {
since: Option<String>,
until: Option<String>,
time_field: Option<String>,
- level: Option<String>,
+ level: Option<Vec<i32>>,
) -> Result<serde_json::Value> {
let body = serde_json::json!({
"query": query,
diff --git a/crates/ov_cli/src/commands/search.rs b/crates/ov_cli/src/commands/search.rs
index 05d07297a..b247a54f1 100644
--- a/crates/ov_cli/src/commands/search.rs
+++ b/crates/ov_cli/src/commands/search.rs
@@ -11,7 +11,7 @@ pub async fn find(
since: Option<&str>,
until: Option<&str>,
time_field: Option<&str>,
- level: Option<&str>,
+ level: Option<Vec<i32>>,
output_format: OutputFormat,
compact: bool,
) -> Result<()> {
@@ -24,7 +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()),
+ level,
)
.await?;
output_success(&result, output_format, compact);
@@ -41,7 +41,7 @@ pub async fn search(
since: Option<&str>,
until: Option<&str>,
time_field: Option<&str>,
- level: Option<&str>,
+ level: Option<Vec<i32>>,
output_format: OutputFormat,
compact: bool,
) -> Result<()> {
@@ -55,7 +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()),
+ level,
)
.await?;
output_success(&result, output_format, compact);
diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rs
index f9670d226..dfeb1332d 100644
--- a/crates/ov_cli/src/handlers.rs
+++ b/crates/ov_cli/src/handlers.rs
@@ -949,7 +949,7 @@ pub async fn handle_find(
threshold: Option<f64>,
after: Option<String>,
before: Option<String>,
- level: Option<String>,
+ level: Option<Vec<i32>>,
ctx: CliContext,
) -> Result<()> {
let mut params = vec![format!("--uri={}", uri), format!("-n {}", node_limit)];
@@ -957,7 +957,12 @@ 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());
+ if let Some(ref l) = level {
+ params.push(format!(
+ "--level {}",
+ l.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(",")
+ ));
+ }
params.push(format!("\"{}\"", query));
print_command_echo("ov find", &params.join(" "), ctx.config.echo_command);
let client = ctx.get_client();
@@ -970,7 +975,7 @@ pub async fn handle_find(
after.as_deref(),
before.as_deref(),
None,
- level.as_deref(),
+ level,
ctx.output_format,
ctx.compact,
)
@@ -985,7 +990,7 @@ pub async fn handle_search(
threshold: Option<f64>,
after: Option<String>,
before: Option<String>,
- level: Option<String>,
+ level: Option<Vec<i32>>,
ctx: CliContext,
) -> Result<()> {
let mut params = vec![format!("--uri={}", uri), format!("-n {}", node_limit)];
@@ -996,7 +1001,12 @@ 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());
+ if let Some(ref l) = level {
+ params.push(format!(
+ "--level {}",
+ l.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(",")
+ ));
+ }
params.push(format!("\"{}\"", query));
print_command_echo("ov search", &params.join(" "), ctx.config.echo_command);
let client = ctx.get_client();
@@ -1010,7 +1020,7 @@ pub async fn handle_search(
after.as_deref(),
before.as_deref(),
None,
- level.as_deref(),
+ level,
ctx.output_format,
ctx.compact,
)
@@ -1030,15 +1040,6 @@ 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 debugging
pub 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.rs
index 64302da15..fd1227539 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -378,9 +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>,
+ /// Only include results with specific level(s) (0=abstract, 1=overview, 2=file)
+ #[arg(short = 'L', long = "level", value_delimiter = ',')]
+ level: Option<Vec<i32>>,
},
/// [Experimental][Data] Run context-aware retrieval
Search {
@@ -409,9 +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>,
+ /// Only include results with specific level(s) (0=abstract, 1=overview, 2=file)
+ #[arg(short = 'L', long = "level", value_delimiter = ',')]
+ level: Option<Vec<i32>>,
},
/// [Data] Run content pattern search
Grep {
diff --git a/openviking/async_client.py b/openviking/async_client.py
index d0bf84b22..d97a25495 100644
--- a/openviking/async_client.py
+++ b/openviking/async_client.py
@@ -342,6 +342,7 @@ class AsyncOpenViking:
since: Optional[str] = None,
until: Optional[str] = None,
time_field: Optional[str] = None,
+ level: Optional[List[int]] = None,
):
"""
Complex search with session context.
@@ -370,6 +371,7 @@ class AsyncOpenViking:
since=since,
until=until,
time_field=time_field,
+ level=level,
)
async def find(
@@ -383,6 +385,7 @@ class AsyncOpenViking:
since: Optional[str] = None,
until: Optional[str] = None,
time_field: Optional[str] = None,
+ level: Optional[List[int]] = None,
):
"""Semantic search"""
await self._ensure_initialized()
@@ -396,6 +399,7 @@ class AsyncOpenViking:
since=since,
until=until,
time_field=time_field,
+ level=level,
)
# ============= FS methods =============
diff --git a/openviking/client/local.py b/openviking/client/local.py
index f4ee93319..27012a174 100644
--- a/openviking/client/local.py
+++ b/openviking/client/local.py
@@ -298,6 +298,7 @@ class LocalClient(BaseClient):
since: Optional[str] = None,
until: Optional[str] = None,
time_field: Optional[str] = None,
+ level: Optional[List[int]] = None,
) -> Any:
"""Semantic search without session context."""
resolved_filter = _resolve_search_filter(filter, since, until, time_field)
@@ -311,6 +312,7 @@ class LocalClient(BaseClient):
limit=limit,
score_threshold=score_threshold,
filter=resolved_filter,
+ level=level,
),
)
return attach_telemetry_payload(
@@ -330,6 +332,7 @@ class LocalClient(BaseClient):
since: Optional[str] = None,
until: Optional[str] = None,
time_field: Optional[str] = None,
+ level: Optional[List[int]] = None,
) -> Any:
"""Semantic search with optional session context."""
resolved_filter = _resolve_search_filter(filter, since, until, time_field)
@@ -347,6 +350,7 @@ class LocalClient(BaseClient):
limit=limit,
score_threshold=score_threshold,
filter=resolved_filter,
+ level=level,
)
execution = await run_with_telemetry(
diff --git a/openviking/retrieve/hierarchical_retriever.py b/openviking/retrieve/hierarchical_retriever.py
index 99bf684fb..5f7dcb5d8 100644
--- a/openviking/retrieve/hierarchical_retriever.py
+++ b/openviking/retrieve/hierarchical_retriever.py
@@ -98,6 +98,7 @@ class HierarchicalRetriever:
score_threshold: Optional[float] = None,
score_gte: bool = False,
scope_dsl: Optional[Dict[str, Any]] = None,
+ level: Optional[List[int]] = None,
) -> QueryResult:
"""
Execute hierarchical retrieval.
@@ -165,10 +166,10 @@ class HierarchicalRetriever:
for i, r in enumerate(global_results):
uri = r.get("uri", "UNKNOWN_URI")
score = r.get("_score", 0.0)
- level = r.get("level", "UNKNOWN_LEVEL")
+ result_level = r.get("level", "UNKNOWN_LEVEL")
account_id = r.get("account_id", "UNKNOWN_ACCOUNT_ID")
logger.debug(
- f" [{i}] URI: {uri}, score: {score:.4f}, level: {level}, account_id: {account_id}"
+ f" [{i}] URI: {uri}, score: {score:.4f}, level: {result_level}, account_id: {account_id}"
)
# Step 3: Merge starting points
@@ -179,8 +180,11 @@ class HierarchicalRetriever:
mode=mode,
)
- # 从 global_results 中提取 level 2 的文件作为初始候选者
- initial_candidates = [r for r in global_results if r.get("level", 2) == 2]
+ # Add global hits to the result pool only when they match the requested level.
+ if level is not None:
+ initial_candidates = [r for r in global_results if r.get("level", 2) in level]
+ else:
+ initial_candidates = [r for r in global_results if r.get("level", 2) == 2]
initial_candidates = self._prepare_initial_candidates(
query.query,
@@ -203,6 +207,7 @@ class HierarchicalRetriever:
target_dirs=target_dirs,
scope_dsl=scope_dsl,
initial_candidates=initial_candidates,
+ level=level,
)
# Step 6: Convert results
@@ -332,8 +337,8 @@ class HierarchicalRetriever:
global_results: List[Dict[str, Any]],
mode: str = RetrieverMode.THINKING,
) -> List[Dict[str, Any]]:
- """Extract level-2 global hits and preserve rerank scores for them."""
- initial_candidates = [dict(r) for r in global_results if r.get("level", 2) == 2]
+ """Preserve rerank scores for global hits added to the result pool."""
+ initial_candidates = [dict(r) for r in global_results]
if not initial_candidates:
return []
@@ -367,6 +372,7 @@ class HierarchicalRetriever:
target_dirs: Optional[List[str]] = None,
scope_dsl: Optional[Dict[str, Any]] = None,
initial_candidates: Optional[List[Dict[str, Any]]] = None,
+ level: Optional[List[int]] = None,
) -> List[Dict[str, Any]]:
"""
Recursive search with directory priority return and score propagation.
@@ -392,26 +398,28 @@ class HierarchicalRetriever:
dir_queue: List[tuple] = [] # Priority queue: (-score, uri)
visited: set = set()
prev_topk_uris: set = set()
+ prev_pool_size = 0
convergence_rounds = 0
+ stagnant_rounds = 0
- # 添加初始候选者(level 2 文件)
+ # Add initial candidates that match the requested level.
if initial_candidates:
for r in initial_candidates:
uri = r.get("uri", "")
- if uri:
- # 只添加 level 2 的文件
- if r.get("level", 2) == 2:
- score = r.get("_score", 0.0)
- if not passes_threshold(score):
- logger.debug(
- f"[RecursiveSearch] Initial candidate URI {uri} score {score:.4f} did not pass threshold {effective_threshold}"
- )
- continue
- r["_final_score"] = score
- collected_by_uri[uri] = r
+ if not uri:
+ continue
+ if level is None or r.get("level", 2) in level:
+ score = r.get("_score", 0.0)
+ if not passes_threshold(score):
logger.debug(
- f"[RecursiveSearch] Added initial candidate: {uri} (score: {score:.4f})"
+ f"[RecursiveSearch] Initial candidate URI {uri} score {score:.4f} did not pass threshold {effective_threshold}"
)
+ continue
+ r["_final_score"] = score
+ collected_by_uri[uri] = r
+ logger.debug(
+ f"[RecursiveSearch] Added initial candidate: {uri} (score: {score:.4f})"
+ )
alpha = self.score_propagation_alpha
@@ -466,16 +474,17 @@ class HierarchicalRetriever:
continue
telemetry.count("vector.passed", 1)
- # Deduplicate by URI and keep the highest-scored candidate.
- previous = collected_by_uri.get(uri)
- if previous is None or final_score > previous.get("_final_score", 0):
- r["_final_score"] = final_score
- collected_by_uri[uri] = r
- logger.debug(
- "[RecursiveSearch] Updated URI: %s candidate score to %.4f",
- uri,
- final_score,
- )
+ if level is None or r.get("level", 2) in level:
+ # Deduplicate by URI and keep the highest-scored candidate.
+ previous = collected_by_uri.get(uri)
+ if previous is None or final_score > previous.get("_final_score", 0):
+ r["_final_score"] = final_score
+ collected_by_uri[uri] = r
+ logger.debug(
+ "[RecursiveSearch] Updated URI: %s candidate score to %.4f",
+ uri,
+ final_score,
+ )
# Only recurse into directories (L0/L1). L2 files are terminal hits.
if uri not in visited and r.get("level", 2) != 2:
@@ -488,15 +497,23 @@ class HierarchicalRetriever:
reverse=True,
)[:limit]
current_topk_uris = {c.get("uri", "") for c in current_topk}
+ current_pool_size = len(collected_by_uri)
if current_topk_uris == prev_topk_uris and len(current_topk_uris) >= limit:
convergence_rounds += 1
if convergence_rounds >= self.MAX_CONVERGENCE_ROUNDS:
break
+ elif current_pool_size == prev_pool_size:
+ stagnant_rounds += 1
+
+ if stagnant_rounds >= self.MAX_CONVERGENCE_ROUNDS:
+ break
else:
convergence_rounds = 0
+ stagnant_rounds = 0
prev_topk_uris = current_topk_uris
+ prev_pool_size = current_pool_size
collected = sorted(
collected_by_uri.values(),
diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.py
index 564e64078..bc038c2bd 100644
--- a/openviking/server/mcp_endpoint.py
+++ b/openviking/server/mcp_endpoint.py
@@ -17,7 +17,7 @@ from __future__ import annotations
import contextvars
from contextlib import asynccontextmanager
-from typing import Literal, Optional
+from typing import List, Literal, Optional
from mcp.server.fastmcp import FastMCP
from mcp.server.transport_security import TransportSecuritySettings
@@ -176,7 +176,13 @@ mcp = FastMCP(
@mcp.tool()
-async def find(query: str, target_uri: str = "", limit: int = 10, min_score: float = 0.35) -> str:
+async def find(
+ query: str,
+ target_uri: str = "",
+ limit: int = 10,
+ min_score: float = 0.35,
+ level: Optional[List[int]] = None,
+) -> str:
"""Fast semantic retrieval without session context. Returns ranked memories, resources, and skills with URI, abstract, and score."""
service = get_service()
result = await service.search.find(
@@ -185,6 +191,7 @@ async def find(query: str, target_uri: str = "", limit: int = 10, min_score: flo
target_uri=target_uri,
limit=limit,
score_threshold=min_score,
+ level=level,
)
return _format_search_result(result)
@@ -196,6 +203,7 @@ async def search(
session_id: Optional[str] = None,
limit: int = 10,
min_score: float = 0.35,
+ level: Optional[List[int]] = None,
) -> str:
"""Deep semantic retrieval with optional session context and intent analysis. Returns ranked memories, resources, and skills with URI, abstract, and score."""
service = get_service()
@@ -211,6 +219,7 @@ async def search(
session=session,
limit=limit,
score_threshold=min_score,
+ level=level,
)
return _format_search_result(result)
diff --git a/openviking/server/routers/search.py b/openviking/server/routers/search.py
index b6036dbfb..0666ee9c5 100644
--- a/openviking/server/routers/search.py
+++ b/openviking/server/routers/search.py
@@ -17,7 +17,7 @@ from openviking.server.identity import RequestContext
from openviking.server.models import Response
from openviking.server.telemetry import run_operation
from openviking.telemetry import TelemetryRequest
-from openviking.utils.search_filters import merge_time_filter, merge_level_filter
+from openviking.utils.search_filters import _resolve_levels, merge_time_filter
from openviking_cli.exceptions import InvalidArgumentError, NotFoundError
@@ -47,16 +47,14 @@ 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:
- filter_with_time = merge_time_filter(
+ return 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
@@ -78,7 +76,6 @@ class FindRequest(BaseModel):
score_threshold: Optional[float] = None
filter: Optional[Dict[str, Any]] = None
include_provenance: bool = False
-
since: Optional[str] = None
until: Optional[str] = None
time_field: Optional[TimeField] = None
@@ -137,7 +134,6 @@ 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(
@@ -150,6 +146,7 @@ async def find(
limit=actual_limit,
score_threshold=request.score_threshold,
filter=effective_filter,
+ level=_resolve_levels(request.level) or None,
),
)
result = execution.result
@@ -176,7 +173,6 @@ async def search(
request.since,
request.until,
request.time_field,
- request.level,
)
resolved_target_uri = _resolve_uri_or_uris(request.target_uri)
@@ -193,6 +189,7 @@ async def search(
limit=actual_limit,
score_threshold=request.score_threshold,
filter=effective_filter,
+ level=_resolve_levels(request.level) or None,
)
execution = await run_operation(
diff --git a/openviking/service/search_service.py b/openviking/service/search_service.py
index fecac6ecb..f57debb03 100644
--- a/openviking/service/search_service.py
+++ b/openviking/service/search_service.py
@@ -50,6 +50,7 @@ class SearchService:
limit: int = 10,
score_threshold: Optional[float] = None,
filter: Optional[Dict] = None,
+ level: Optional[List[int]] = None,
) -> Any:
"""Complex search with session context.
@@ -60,6 +61,7 @@ class SearchService:
limit: Max results
score_threshold: Score threshold
filter: Metadata filters
+ level: Filter by level (0=abstract, 1=overview, 2=file)
Returns:
FindResult
@@ -80,6 +82,7 @@ class SearchService:
limit=limit,
score_threshold=score_threshold,
filter=filter,
+ level=level,
)
return result
@@ -91,6 +94,7 @@ class SearchService:
limit: int = 10,
score_threshold: Optional[float] = None,
filter: Optional[Dict] = None,
+ level: Optional[List[int]] = None,
) -> Any:
"""Semantic search without session context.
@@ -100,6 +104,7 @@ class SearchService:
limit: Max results
score_threshold: Score threshold
filter: Metadata filters
+ level: Filter by level (0=abstract, 1=overview, 2=file)
Returns:
FindResult
@@ -114,5 +119,6 @@ class SearchService:
limit=limit,
score_threshold=score_threshold,
filter=filter,
+ level=level,
)
return result
diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.py
index f94f5ae1f..3b5c8c21c 100644
--- a/openviking/storage/viking_fs.py
+++ b/openviking/storage/viking_fs.py
@@ -31,7 +31,6 @@ from openviking.core.namespace import (
from openviking.core.namespace import (
is_accessible as namespace_is_accessible,
)
-from openviking.storage.expr import PathScope
from openviking.pyagfs.exceptions import (
AGFSClientError,
AGFSDirectoryNotEmptyError,
@@ -41,6 +40,7 @@ from openviking.pyagfs.exceptions import (
from openviking.resource.watch_storage import is_watch_task_control_uri
from openviking.server.error_mapping import is_not_found_error, map_exception
from openviking.server.identity import RequestContext, Role
+from openviking.storage.expr import PathScope
from openviking.telemetry import get_current_telemetry
from openviking.utils.time_utils import format_simplified, get_current_timestamp, parse_iso_datetime
from openviking_cli.exceptions import (
@@ -450,9 +450,7 @@ 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:
+ 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:
@@ -1329,6 +1327,7 @@ class VikingFS:
score_threshold: Optional[float] = None,
filter: Optional[Dict] = None,
ctx: Optional[RequestContext] = None,
+ level: Optional[List[int]] = None,
):
"""Semantic search.
@@ -1404,6 +1403,7 @@ class VikingFS:
limit=limit,
score_threshold=score_threshold,
scope_dsl=filter,
+ level=level,
)
# Convert QueryResult to FindResult
@@ -1433,6 +1433,7 @@ class VikingFS:
score_threshold: Optional[float] = None,
filter: Optional[Dict] = None,
ctx: Optional[RequestContext] = None,
+ level: Optional[List[int]] = None,
):
"""Complex search with session context.
@@ -1554,6 +1555,7 @@ class VikingFS:
limit=limit,
score_threshold=score_threshold,
scope_dsl=filter,
+ level=level,
)
query_results = await asyncio.gather(*[_execute(tq) for tq in typed_queries])
diff --git a/openviking/sync_client.py b/openviking/sync_client.py
index 77c1c4872..2d57b8817 100644
--- a/openviking/sync_client.py
+++ b/openviking/sync_client.py
@@ -196,6 +196,7 @@ class SyncOpenViking:
since: Optional[str] = None,
until: Optional[str] = None,
time_field: Optional[str] = None,
+ level: Optional[List[int]] = None,
):
"""Execute complex retrieval (intent analysis, hierarchical retrieval)."""
return run_async(
@@ -211,6 +212,7 @@ class SyncOpenViking:
since=since,
until=until,
time_field=time_field,
+ level=level,
)
)
@@ -225,6 +227,7 @@ class SyncOpenViking:
since: Optional[str] = None,
until: Optional[str] = None,
time_field: Optional[str] = None,
+ level: Optional[List[int]] = None,
):
"""Quick retrieval"""
return run_async(
@@ -238,6 +241,7 @@ class SyncOpenViking:
since,
until,
time_field,
+ level,
)
)
diff --git a/tests/server/test_api_search.py b/tests/server/test_api_search.py
index 888da6827..dc1f6b87b 100644
--- a/tests/server/test_api_search.py
+++ b/tests/server/test_api_search.py
@@ -50,6 +50,266 @@ async def test_find_with_target_uri(client_with_resource):
assert resp.json()["status"] == "ok"
+async def test_find_with_level_passes_to_service(client: httpx.AsyncClient, service, monkeypatch):
+ captured = {}
+
+ async def fake_find(*, level=None, **kwargs):
+ captured["level"] = level
+ return {"items": []}
+
+ monkeypatch.setattr(service.search, "find", fake_find)
+
+ resp = await client.post(
+ "/api/v1/search/find",
+ json={"query": "sample", "level": [0, 2]},
+ )
+
+ assert resp.status_code == 200
+ assert resp.json()["status"] == "ok"
+ assert captured["level"] == [0, 2]
+
+
+async def test_find_without_level_passes_none(client: httpx.AsyncClient, service, monkeypatch):
+ captured = {}
+
+ async def fake_find(*, level=None, **kwargs):
+ captured["level"] = level
+ return {"items": []}
+
+ monkeypatch.setattr(service.search, "find", fake_find)
+
+ resp = await client.post(
+ "/api/v1/search/find",
+ json={"query": "sample"},
+ )
+
+ assert resp.status_code == 200
+ assert resp.json()["status"] == "ok"
+ assert captured["level"] is None
+
+
+async def test_find_level_filters_l2_only(client_with_resource):
+ client, uri = client_with_resource
+ resp = await client.post(
+ "/api/v1/search/find",
+ json={"query": "sample document", "limit": 10, "level": [2]},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["status"] == "ok"
+ result = body["result"]
+ for key in ("memories", "resources", "skills"):
+ for item in result.get(key, []):
+ assert item.get("level") == 2
+
+
+async def test_find_level_filters_l0_only(client_with_resource):
+ client, uri = client_with_resource
+ resp = await client.post(
+ "/api/v1/search/find",
+ json={"query": "sample document", "limit": 10, "level": [0]},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["status"] == "ok"
+ result = body["result"]
+ for key in ("memories", "resources", "skills"):
+ for item in result.get(key, []):
+ assert item.get("level") == 0
+
+
+async def test_find_level_filters_mixed_l0_l2(client_with_resource):
+ client, uri = client_with_resource
+ resp = await client.post(
+ "/api/v1/search/find",
+ json={"query": "sample document", "limit": 10, "level": [0, 2]},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["status"] == "ok"
+ result = body["result"]
+ for key in ("memories", "resources", "skills"):
+ for item in result.get(key, []):
+ assert item.get("level") in (0, 2)
+
+
+async def test_find_level_filters_l0_l1(client_with_resource):
+ client, uri = client_with_resource
+ resp = await client.post(
+ "/api/v1/search/find",
+ json={"query": "sample document", "limit": 10, "level": [0, 1]},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["status"] == "ok"
+ result = body["result"]
+ for key in ("memories", "resources", "skills"):
+ for item in result.get(key, []):
+ assert item.get("level") in (0, 1)
+
+
+async def test_find_level_with_no_matching_results(client_with_resource):
+ client, uri = client_with_resource
+ resp = await client.post(
+ "/api/v1/search/find",
+ json={"query": "sample document", "limit": 10, "level": [5]},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["status"] == "ok"
+ result = body["result"]
+ assert result.get("total", 0) == 0
+
+
+async def test_search_with_level_passes_to_service(client: httpx.AsyncClient, service, monkeypatch):
+ captured = {}
+
+ async def fake_search(*, level=None, **kwargs):
+ captured["level"] = level
+ return {"items": []}
+
+ monkeypatch.setattr(service.search, "search", fake_search)
+
+ resp = await client.post(
+ "/api/v1/search/search",
+ json={"query": "sample", "level": [0, 2]},
+ )
+
+ assert resp.status_code == 200
+ assert resp.json()["status"] == "ok"
+ assert captured["level"] == [0, 2]
+
+
+async def test_search_without_level_passes_none(client: httpx.AsyncClient, service, monkeypatch):
+ captured = {}
+
+ async def fake_search(*, level=None, **kwargs):
+ captured["level"] = level
+ return {"items": []}
+
+ monkeypatch.setattr(service.search, "search", fake_search)
+
+ resp = await client.post(
+ "/api/v1/search/search",
+ json={"query": "sample"},
+ )
+
+ assert resp.status_code == 200
+ assert resp.json()["status"] == "ok"
+ assert captured["level"] is None
+
+
+async def test_search_level_filters_l2_only(client_with_resource):
+ client, uri = client_with_resource
+ resp = await client.post(
+ "/api/v1/search/search",
+ json={"query": "sample document", "limit": 10, "level": [2]},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["status"] == "ok"
+ result = body["result"]
+ for key in ("memories", "resources", "skills"):
+ for item in result.get(key, []):
+ assert item.get("level") == 2
+
+
+async def test_search_level_filters_l0_only(client_with_resource):
+ client, uri = client_with_resource
+ resp = await client.post(
+ "/api/v1/search/search",
+ json={"query": "sample document", "limit": 10, "level": [0]},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["status"] == "ok"
+ result = body["result"]
+ for key in ("memories", "resources", "skills"):
+ for item in result.get(key, []):
+ assert item.get("level") == 0
+
+
+async def test_search_level_filters_mixed_l0_l2(client_with_resource):
+ client, uri = client_with_resource
+ resp = await client.post(
+ "/api/v1/search/search",
+ json={"query": "sample document", "limit": 10, "level": [0, 2]},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["status"] == "ok"
+ result = body["result"]
+ for key in ("memories", "resources", "skills"):
+ for item in result.get(key, []):
+ assert item.get("level") in (0, 2)
+
+
+async def test_search_level_filters_l0_l1(client_with_resource):
+ client, uri = client_with_resource
+ resp = await client.post(
+ "/api/v1/search/search",
+ json={"query": "sample document", "limit": 10, "level": [0, 1]},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["status"] == "ok"
+ result = body["result"]
+ for key in ("memories", "resources", "skills"):
+ for item in result.get(key, []):
+ assert item.get("level") in (0, 1)
+
+
+async def test_search_level_with_no_matching_results(client_with_resource):
+ client, uri = client_with_resource
+ resp = await client.post(
+ "/api/v1/search/search",
+ json={"query": "sample document", "limit": 10, "level": [5]},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["status"] == "ok"
+ result = body["result"]
+ assert result.get("total", 0) == 0
+
+
+async def test_find_with_level_string_input(client: httpx.AsyncClient, service, monkeypatch):
+ captured = {}
+
+ async def fake_find(*, level=None, **kwargs):
+ captured["level"] = level
+ return {"items": []}
+
+ monkeypatch.setattr(service.search, "find", fake_find)
+
+ resp = await client.post(
+ "/api/v1/search/find",
+ json={"query": "sample", "level": "0,2"},
+ )
+
+ assert resp.status_code == 200
+ assert resp.json()["status"] == "ok"
+ assert captured["level"] == [0, 2]
+
+
+async def test_find_with_level_int_input(client: httpx.AsyncClient, service, monkeypatch):
+ captured = {}
+
+ async def fake_find(*, level=None, **kwargs):
+ captured["level"] = level
+ return {"items": []}
+
+ monkeypatch.setattr(service.search, "find", fake_find)
+
+ resp = await client.post(
+ "/api/v1/search/find",
+ json={"query": "sample", "level": 2},
+ )
+
+ assert resp.status_code == 200
+ assert resp.json()["status"] == "ok"
+ assert captured["level"] == [2]
+
+
async def test_find_with_inaccessible_target_uri_returns_permission_denied(
client: httpx.AsyncClient, app
):