Skip to content

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

feat(cli): support list and context search modes (#5951)

dingbenad4d99de1d95
diff --git a/crates/ov_cli/README.md b/crates/ov_cli/README.md
index ef0ce7006..f82c05bb4 100644
--- a/crates/ov_cli/README.md
+++ b/crates/ov_cli/README.md
@@ -158,6 +158,8 @@ ov cp -r viking://resources/docs viking://resources/docs-backup
- `grep` - Content pattern search.
- `glob` - File glob pattern search.
+`search --mode list` (the default) returns ranked hits. `search --mode context` assembles context using server defaults and prints its text; use `-o json` to retain the complete `entries`, `rendered`, `digest`, and `stats` result. Context mode supports `--events-time-decay-protection`, but rejects `--uri` and `--read-content`; `--level` is ignored by the server. Context-specific options such as `max_tokens` and `detail` are not exposed as CLI flags yet.
+
### Sessions And Memory
- `session new` - Create a session with optional event-memory tags and auto-commit policy.
@@ -272,6 +274,10 @@ ov add-resource ./docs -p "viking://resources/docs/{calendar:today}" --wait
ov find "API authentication" --threshold 0.7 --limit 5
ov find "authentication" --uri viking://resources/project --level 0,1
+# Assemble context with event time decay, or inspect the complete JSON result
+ov search "recent decisions" --mode context --events-time-decay-protection 7d
+ov -o json search "authentication" --mode context
+
# Recursive list
ov ls viking://resources --recursive
diff --git a/crates/ov_cli/README_CN.md b/crates/ov_cli/README_CN.md
index 2375620ff..37c7079e7 100644
--- a/crates/ov_cli/README_CN.md
+++ b/crates/ov_cli/README_CN.md
@@ -158,6 +158,8 @@ ov cp -r viking://resources/docs viking://resources/docs-backup
- `grep` - 内容模式搜索。
- `glob` - 文件 glob 搜索。
+`search --mode list`(默认)返回排序命中列表。`search --mode context` 按服务端默认配置组装上下文并输出文本;使用 `-o json` 可保留完整的 `entries`、`rendered`、`digest` 和 `stats` 结果。context 模式支持 `--events-time-decay-protection`,但拒绝 `--uri` 和 `--read-content`,服务端会忽略 `--level`。CLI 暂未提供 `max_tokens`、`detail` 等 context 专用选项。
+
### Session 与记忆
- `session new` - 创建 session,并可设置事件记忆默认 tags 和自动提交策略。
@@ -271,6 +273,10 @@ ov add-resource ./docs -p "viking://resources/docs/{calendar:today}" --wait
ov find "API authentication" --threshold 0.7 --limit 5
ov find "authentication" --uri viking://resources/project --level 0,1
+# 组装上下文并启用事件时间衰减,或查看完整 JSON 结果
+ov search "recent decisions" --mode context --events-time-decay-protection 7d
+ov -o json search "authentication" --mode context
+
# 递归列目录
ov ls viking://resources --recursive
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index 7cbcb22d6..2ec9b8c60 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -765,6 +765,7 @@ impl HttpClient {
uri: String,
image: Option<String>,
search_type: String,
+ mode: String,
session_id: Option<String>,
node_limit: i32,
threshold: Option<f64>,
@@ -782,6 +783,8 @@ impl HttpClient {
"query": query,
"image_url": image_url,
"search_type": search_type,
+ // Preserve the legacy request shape for servers without context mode.
+ "mode": (mode != "list").then_some(mode),
"target_uri": uri,
"session_id": session_id,
"limit": node_limit,
@@ -2127,18 +2130,84 @@ mod tests {
assert_eq!(body["processing_mode"], "vectors_only");
}
- #[test]
- fn compact_request_body_drops_default_search_type_for_legacy_servers() {
- let mut body = json!({"query": "OAuth token", "search_type": "semantic"});
- super::compact_request_body(&mut body);
- assert!(!body.as_object().unwrap().contains_key("search_type"));
+ #[tokio::test]
+ async fn search_list_request_preserves_legacy_server_compatibility() {
+ let (base_url, request_rx) = spawn_request_capture_server().await;
+ let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None);
+ client
+ .search(
+ "OAuth token".to_string(),
+ String::new(),
+ None,
+ "semantic".to_string(),
+ "list".to_string(),
+ None,
+ 10,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ false,
+ None,
+ )
+ .await
+ .expect("list search should succeed");
+
+ let request = request_rx.await.expect("request should be captured");
+ assert!(request.starts_with("POST /api/v1/search/search "));
+ let (_, body) = request.split_once("\r\n\r\n").expect("request body");
+ assert_eq!(
+ serde_json::from_str::<serde_json::Value>(body).unwrap(),
+ json!({"query": "OAuth token", "target_uri": "", "limit": 10})
+ );
}
- #[test]
- fn compact_request_body_keeps_keywords_search_type() {
- let mut body = json!({"query": "OAuth token", "search_type": "keywords"});
- super::compact_request_body(&mut body);
- assert_eq!(body["search_type"], "keywords");
+ #[tokio::test]
+ async fn search_context_request_preserves_keywords_and_session_options() {
+ let (base_url, request_rx) = spawn_request_capture_server().await;
+ let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None);
+ client
+ .search(
+ "OAuth token".to_string(),
+ String::new(),
+ None,
+ "keywords".to_string(),
+ "context".to_string(),
+ Some("session-1".to_string()),
+ 3,
+ None,
+ None,
+ None,
+ None,
+ None,
+ Some(vec!["memory".to_string()]),
+ Some(vec!["project=openviking".to_string()]),
+ false,
+ Some("7d".to_string()),
+ )
+ .await
+ .expect("context search should succeed");
+
+ let request = request_rx.await.expect("request should be captured");
+ assert!(request.starts_with("POST /api/v1/search/search "));
+ let (_, body) = request.split_once("\r\n\r\n").expect("request body");
+ assert_eq!(
+ serde_json::from_str::<serde_json::Value>(body).unwrap(),
+ json!({
+ "query": "OAuth token",
+ "target_uri": "",
+ "search_type": "keywords",
+ "mode": "context",
+ "session_id": "session-1",
+ "limit": 3,
+ "context_type": ["memory"],
+ "tags": ["project=openviking"],
+ "events_time_decay_protection": "7d"
+ })
+ );
}
#[test]
diff --git a/crates/ov_cli/src/commands/search.rs b/crates/ov_cli/src/commands/search.rs
index 32ea04f3b..3c3e74a19 100644
--- a/crates/ov_cli/src/commands/search.rs
+++ b/crates/ov_cli/src/commands/search.rs
@@ -166,6 +166,7 @@ pub async fn search(
uri: &str,
image: Option<String>,
search_type: &str,
+ mode: &str,
session_id: Option<String>,
node_limit: i32,
threshold: Option<f64>,
@@ -186,6 +187,7 @@ pub async fn search(
uri.to_string(),
image,
search_type.to_string(),
+ mode.to_string(),
session_id,
node_limit,
threshold,
@@ -199,15 +201,91 @@ pub async fn search(
events_time_decay_protection,
)
.await?;
- output_search_results(
- &result,
- output_format,
- compact,
- SearchRenderContext::search(node_limit),
- );
+ if mode == "context" {
+ if let Some(rendered) = render_context_output_for_table(&result, output_format) {
+ for error in rendered.retrieval_errors {
+ eprintln!("Warning: context retrieval failed: {error}");
+ }
+ if !rendered.text.is_empty() {
+ println!("{}", rendered.text);
+ }
+ } else {
+ output_success(&result, output_format, compact);
+ }
+ } else {
+ output_search_results(
+ &result,
+ output_format,
+ compact,
+ SearchRenderContext::search(node_limit),
+ );
+ }
Ok(())
}
+struct ContextTextOutput {
+ text: String,
+ retrieval_errors: Vec<String>,
+}
+
+fn render_context_output_for_table(
+ value: &Value,
+ output_format: OutputFormat,
+) -> Option<ContextTextOutput> {
+ if matches!(output_format, OutputFormat::Json) {
+ return None;
+ }
+
+ let object = value.as_object()?;
+ let result = object
+ .get("result")
+ .and_then(Value::as_object)
+ .unwrap_or(object);
+ let profile = result
+ .get("profile")
+ .filter(|profile| !profile.is_null())
+ .or_else(|| object.get("profile").filter(|profile| !profile.is_null()));
+
+ let retrieval_errors: Vec<String> = result
+ .get("stats")
+ .and_then(|stats| stats.get("retrieval_errors"))
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .filter_map(Value::as_str)
+ .filter(|error| !error.trim().is_empty())
+ .map(str::to_string)
+ .collect();
+
+ let no_relevant = result
+ .get("stats")
+ .and_then(|stats| stats.get("rewrite"))
+ .and_then(Value::as_str)
+ == Some("no_relevant");
+ let text = if no_relevant {
+ None
+ } else {
+ ["digest", "rendered"].into_iter().find_map(|key| {
+ result
+ .get(key)
+ .and_then(Value::as_str)
+ .filter(|text| !text.trim().is_empty())
+ })
+ };
+
+ let mut lines = match text {
+ Some(text) => vec![text.to_string()],
+ None if !retrieval_errors.is_empty() => Vec::new(),
+ None if no_relevant => vec![theme::muted("No relevant context found.").to_string()],
+ None => vec![theme::muted("No context found.").to_string()],
+ };
+ append_profile_lines(profile, &mut lines);
+ Some(ContextTextOutput {
+ text: lines.join("\n"),
+ retrieval_errors,
+ })
+}
+
fn output_search_results(
result: &Value,
output_format: OutputFormat,
@@ -1151,7 +1229,7 @@ mod tests {
}
#[test]
- fn search_result_cards_render_result_object_with_profile() {
+ fn search_output_preserves_content_profile_and_retrieval_failures() {
let results = json!({
"result": [
{
@@ -1169,6 +1247,47 @@ mod tests {
assert!(rendered.contains("viking://user/default/memories/events/.abstract.md"));
assert!(rendered.contains("profile"));
assert!(rendered.contains("vector search: 12ms"));
+
+ let text = format!(
+ "<memory>\n {}\n\nFinal line.\n</memory>",
+ "Full context. ".repeat(100)
+ );
+ let mut context = json!({
+ "rendered": text,
+ "digest": "",
+ "stats": {"rewrite": "off", "retrieval_errors": ["RuntimeError: index unavailable"]},
+ "profile": ["vector search: 12ms"]
+ });
+ let output = render_context_output_for_table(&context, OutputFormat::Table)
+ .expect("context with partial retrieval failure");
+ assert_eq!(
+ strip_ansi(&output.text),
+ format!("{text}\n\nprofile\nvector search: 12ms")
+ );
+ assert_eq!(output.retrieval_errors, ["RuntimeError: index unavailable"]);
+ assert!(render_context_output_for_table(&context, OutputFormat::Json).is_none());
+
+ context["digest"] = json!("Concise context.");
+ context["stats"]["rewrite"] = json!("ok");
+ let output = render_context_output_for_table(&context, OutputFormat::Table)
+ .expect("rewritten context");
+ assert_eq!(
+ strip_ansi(&output.text),
+ "Concise context.\n\nprofile\nvector search: 12ms"
+ );
+ assert_eq!(output.retrieval_errors, ["RuntimeError: index unavailable"]);
+
+ context["rendered"] = json!("");
+ context["digest"] = json!("");
+ context["stats"]["rewrite"] = json!("off");
+ context.as_object_mut().unwrap().remove("profile");
+ let output = render_context_output_for_table(&context, OutputFormat::Table)
+ .expect("total retrieval failure");
+ assert!(
+ output.text.is_empty(),
+ "retrieval failure must not look like no matches"
+ );
+ assert_eq!(output.retrieval_errors, ["RuntimeError: index unavailable"]);
}
#[test]
diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rs
index e56f4679b..73e1202f3 100644
--- a/crates/ov_cli/src/handlers.rs
+++ b/crates/ov_cli/src/handlers.rs
@@ -1543,6 +1543,7 @@ pub async fn handle_search(
uri: String,
image: Option<String>,
search_type: String,
+ mode: String,
session_id: Option<String>,
node_limit: i32,
threshold: Option<f64>,
@@ -1566,10 +1567,14 @@ pub async fn handle_search(
"--image is not supported with --search-type keywords.".to_string(),
));
}
+ validate_search_mode_options(&mode, &uri, read_content)?;
let mut params = vec![format!("--uri={}", uri), format!("-n {}", node_limit)];
if search_type != "semantic" {
params.push(format!("--search-type {}", search_type));
}
+ if mode != "list" {
+ params.push(format!("--mode {}", mode));
+ }
if let Some(ref img) = image {
params.push(format!("--image {}", img));
}
@@ -1610,6 +1615,7 @@ pub async fn handle_search(
&uri,
image,
&search_type,
+ &mode,
session_id,
node_limit,
threshold,
@@ -1627,6 +1633,24 @@ pub async fn handle_search(
.await
}
+fn validate_search_mode_options(mode: &str, uri: &str, read_content: bool) -> Result<()> {
+ if mode == "context" {
+ if !uri.is_empty() {
+ return Err(Error::Client(
+ "--uri is not supported with --mode context. Remove --uri or use --mode list."
+ .to_string(),
+ ));
+ }
+ if read_content {
+ return Err(Error::Client(
+ "--read-content is not supported with --mode context; context assembly already includes content. Remove --read-content or use --mode list."
+ .to_string(),
+ ));
+ }
+ }
+ Ok(())
+}
+
pub fn append_time_filter_params(
params: &mut Vec<String>,
after: Option<&str>,
diff --git a/crates/ov_cli/src/help_ui.rs b/crates/ov_cli/src/help_ui.rs
index 201b2b5a5..493bafd28 100644
--- a/crates/ov_cli/src/help_ui.rs
+++ b/crates/ov_cli/src/help_ui.rs
@@ -525,10 +525,16 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[
CommandHelpSpec {
path: &["search"],
purpose: "Run experimental context-aware retrieval, optionally scoped to a session.",
- examples: &[HelpItem {
- label: "ov search \"what changed last time?\" --session-id abc123",
- description: "Search with session context.",
- }],
+ examples: &[
+ HelpItem {
+ label: "ov search \"what changed last time?\" --session-id abc123",
+ description: "Search with session context.",
+ },
+ HelpItem {
+ label: "ov search \"recent decisions\" --mode context",
+ description: "Assemble context ready to inject into a model.",
+ },
+ ],
next_steps: &[HelpItem {
label: "ov session get-session-context <id>",
description: "Inspect the session context directly.",
@@ -2927,6 +2933,8 @@ mod tests {
assert!(find_help.contains("Maximum final results returned"));
assert!(search_help.contains("Maximum results per search pass."));
assert!(search_help.contains("Search may merge multiple passes"));
+ assert!(search_help.contains("--mode <list|context>"));
+ assert!(search_help.contains("ignored in context mode"));
}
#[test]
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index b63328731..4ccc201ce 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -962,7 +962,16 @@ enum Commands {
help_heading = "Common options"
)]
search_type: String,
- /// Target URI
+ /// Return ranked hits (list) or assembled context (context)
+ #[arg(
+ long,
+ default_value = "list",
+ value_parser = ["list", "context"],
+ value_name = "list|context",
+ help_heading = "Common options"
+ )]
+ mode: String,
+ /// Target URI (list mode only)
#[arg(
short,
long,
@@ -998,7 +1007,7 @@ enum Commands {
help_heading = "Advanced options"
)]
before: Option<String>,
- /// Only include results with specific level(s) (0=abstract, 1=overview, 2=file)
+ /// Filter levels (0=abstract, 1=overview, 2=file); ignored in context mode
#[arg(
short = 'L',
long = "level",
@@ -1018,7 +1027,7 @@ enum Commands {
/// Only include results matching all of these explicit tags
#[arg(long = "tags", value_delimiter = ',')]
tags: Option<Vec<String>>,
- /// Include the full visible content for every matched URI
+ /// Include the full visible content for every matched URI (list mode only)
#[arg(long, help_heading = "Advanced options")]
read_content: bool,
/// Enable event decay with protection duration: 0 (immediate) or Xm/Xh/Xd
@@ -3858,6 +3867,7 @@ async fn main() {
query,
image,
search_type,
+ mode,
uri,
session_id,
node_limit,
@@ -3875,6 +3885,7 @@ async fn main() {
uri,
image,
search_type,
+ mode,
session_id,
node_limit,
threshold,
@@ -4116,12 +4127,23 @@ mod tests {
}
#[test]
- fn cli_parses_search_context_type() {
- let cli = Cli::try_parse_from(["ov", "search", "invoice", "--context-type", "skill"])
- .expect("search context type should parse");
+ fn cli_parses_search_context_mode_and_type() {
+ let cli = Cli::try_parse_from([
+ "ov",
+ "search",
+ "invoice",
+ "--mode",
+ "context",
+ "--context-type",
+ "skill",
+ ])
+ .expect("search context mode and type should parse");
match cli.command {
- Commands::Search { context_type, .. } => {
+ Commands::Search {
+ mode, context_type, ..
+ } => {
+ assert_eq!(mode, "context");
assert_eq!(context_type, Some(vec!["skill".to_string()]));
}
_ => panic!("expected search command"),
@@ -4134,9 +4156,12 @@ mod tests {
.expect("search image should parse");
match cli.command {
- Commands::Search { query, image, .. } => {
+ Commands::Search {
+ query, image, mode, ..
+ } => {
assert_eq!(query.as_deref(), Some("poster"));
assert_eq!(image.as_deref(), Some("viking://x.png"));
+ assert_eq!(mode, "list");
}
_ => panic!("expected search command"),
}
diff --git a/docs/en/api/06-retrieval.md b/docs/en/api/06-retrieval.md
index ed6e2a3ce..26d02521b 100644
--- a/docs/en/api/06-retrieval.md
+++ b/docs/en/api/06-retrieval.md
@@ -396,6 +396,7 @@ Semantic retrieval with optional session-aware query planning.
| query | str | No | "" | Search query string. Required unless `image_url` is provided |
| image_url | str | No | None | Image query as a `data:image/...;base64,...`, `http(s)://`, or `viking://` URI. Requires a multimodal embedding model |
| search_type | `"semantic"` \| `"keywords"` | No | `"semantic"` | Retrieval type. `semantic` uses embeddings and vector recall; `keywords` uses BM25 keyword recall |
+| mode | `"list"` \| `"context"` | No | `"list"` | Return ranked hits or assembled context. CLI `--mode` maps to this field; context-specific parameters are described below |
| target_uri | str \| List[str] | No | "" | Limit search to specific URI prefix |
| session | Session | No | None | Session for context-aware search (SDK) |
| session_id | str | No | None | Session ID for context-aware search (HTTP) |
@@ -570,6 +571,12 @@ fmt.Println(result.Total)
# Search with session ID
ov search "best practices" --session-id abc123
+# Assemble context using the server defaults, with event time decay
+ov search "recent decisions" --mode context --events-time-decay-protection 7d
+
+# Return the complete context result as JSON
+ov -o json search "best practices" --mode context
+
# Limit to a context type
ov search "best practices" --context-type skill
@@ -596,6 +603,8 @@ ov search "how to implement OAuth" -L 1,2
ov search "similar poster" --image ./poster.png --uri "viking://resources/images"
```
+`ov search --mode list` is the default and returns the usual hit list. With `--mode context`, the default terminal output prints the assembled `rendered` text (or a non-empty `digest` when returned); `-o json` preserves the full result, including `entries`, `rendered`, `digest`, and `stats`. The CLI uses server defaults for context-specific options such as `max_tokens`, `detail`, and `rewrite`; it does not expose flags for these options yet. Context mode rejects `--uri` and `--read-content`; the server ignores `--level` because assembly selects content tiers.
+
**Response Example**
```json
diff --git a/docs/zh/api/06-retrieval.md b/docs/zh/api/06-retrieval.md
index 55f4b9ad9..185c0756d 100644
--- a/docs/zh/api/06-retrieval.md
+++ b/docs/zh/api/06-retrieval.md
@@ -396,6 +396,7 @@ ov find "红色海报风格" --image ./poster.png --uri "viking://resources/imag
| query | str | 否 | "" | 搜索查询字符串;未提供 `image_url` 时必填 |
| image_url | str | 否 | None | 图片查询,支持 `data:image/...;base64,...`、`http(s)://` 或 `viking://` URI;需要 multimodal embedding 模型 |
| search_type | `"semantic"` \| `"keywords"` | 否 | `"semantic"` | 检索类型。`semantic` 使用 Embedding 和向量召回;`keywords` 使用 BM25 关键词召回 |
+| mode | `"list"` \| `"context"` | 否 | `"list"` | 返回排序命中列表或组装好的上下文。CLI `--mode` 会映射到这个字段;context 专用参数见下文 |
| target_uri | str \| List[str] | 否 | "" | 限制搜索范围到指定的 URI 前缀 |
| session | Session | 否 | None | 用于上下文感知搜索的会话(SDK)|
| session_id | str | 否 | None | 用于上下文感知搜索的会话 ID(HTTP)|
@@ -570,6 +571,12 @@ fmt.Println(result.Total)
# 带会话 ID 的搜索
ov search "best practices" --session-id abc123
+# 按服务端默认配置组装上下文,并启用事件时间衰减
+ov search "recent decisions" --mode context --events-time-decay-protection 7d
+
+# 以 JSON 返回完整的 context 结果
+ov -o json search "best practices" --mode context
+
# 限定上下文类型
ov search "best practices" --context-type skill
@@ -596,6 +603,8 @@ ov search "how to implement OAuth" -L 1,2
ov search "similar poster" --image ./poster.png --uri "viking://resources/images"
```
+`ov search --mode list` 为默认行为,返回常规命中列表。使用 `--mode context` 时,默认终端输出展示组装后的 `rendered` 文本(返回非空 `digest` 时优先展示摘要);`-o json` 保留完整结果,包括 `entries`、`rendered`、`digest` 和 `stats`。CLI 暂未提供 `max_tokens`、`detail`、`rewrite` 等 context 专用选项,使用服务端默认值。context 模式拒绝 `--uri` 和 `--read-content`;服务端会忽略 `--level`,由组装流程选择内容档位。
+
**响应示例**
```json