Skip to content

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

fix: fix the difference of python CLI and rust CLI (#188)

MaojiaSheng8af2b03496e8
diff --git a/crates/ov_cli/src/commands/content.rs b/crates/ov_cli/src/commands/content.rs
index f275efaea..7c51f6de9 100644
--- a/crates/ov_cli/src/commands/content.rs
+++ b/crates/ov_cli/src/commands/content.rs
@@ -6,6 +6,7 @@ pub async fn read(
client: &HttpClient,
uri: &str,
_output_format: OutputFormat,
+ _compact: bool,
) -> Result<()> {
let content = client.read(uri).await?;
println!("{}", content);
@@ -16,6 +17,7 @@ pub async fn abstract_content(
client: &HttpClient,
uri: &str,
_output_format: OutputFormat,
+ _compact: bool,
) -> Result<()> {
let content = client.abstract_content(uri).await?;
println!("{}", content);
@@ -26,6 +28,7 @@ pub async fn overview(
client: &HttpClient,
uri: &str,
_output_format: OutputFormat,
+ _compact: bool,
) -> Result<()> {
let content = client.overview(uri).await?;
println!("{}", content);
diff --git a/crates/ov_cli/src/commands/filesystem.rs b/crates/ov_cli/src/commands/filesystem.rs
index 05a769cb9..0034c1a0e 100644
--- a/crates/ov_cli/src/commands/filesystem.rs
+++ b/crates/ov_cli/src/commands/filesystem.rs
@@ -8,9 +8,10 @@ pub async fn ls(
simple: bool,
recursive: bool,
output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let result = client.ls(uri, simple, recursive).await?;
- output_success(&result, output_format, false);
+ output_success(&result, output_format, compact);
Ok(())
}
@@ -18,9 +19,10 @@ pub async fn tree(
client: &HttpClient,
uri: &str,
output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let result = client.tree(uri).await?;
- output_success(&result, output_format, false);
+ output_success(&result, output_format, compact);
Ok(())
}
@@ -28,6 +30,7 @@ pub async fn mkdir(
client: &HttpClient,
uri: &str,
_output_format: OutputFormat,
+ _compact: bool,
) -> Result<()> {
client.mkdir(uri).await?;
println!("Directory created: {}", uri);
@@ -39,6 +42,7 @@ pub async fn rm(
uri: &str,
recursive: bool,
_output_format: OutputFormat,
+ _compact: bool,
) -> Result<()> {
client.rm(uri, recursive).await?;
println!("Removed: {}", uri);
@@ -50,6 +54,7 @@ pub async fn mv(
from_uri: &str,
to_uri: &str,
_output_format: OutputFormat,
+ _compact: bool,
) -> Result<()> {
client.mv(from_uri, to_uri).await?;
println!("Moved: {} -> {}", from_uri, to_uri);
@@ -60,8 +65,9 @@ pub async fn stat(
client: &HttpClient,
uri: &str,
output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let result = client.stat(uri).await?;
- output_success(&result, output_format, false);
+ output_success(&result, output_format, compact);
Ok(())
}
diff --git a/crates/ov_cli/src/commands/observer.rs b/crates/ov_cli/src/commands/observer.rs
index 2863b5090..3b68c2082 100644
--- a/crates/ov_cli/src/commands/observer.rs
+++ b/crates/ov_cli/src/commands/observer.rs
@@ -5,35 +5,39 @@ use crate::output::{output_success, OutputFormat};
pub async fn queue(
client: &HttpClient,
output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let response: serde_json::Value = client.get("/api/v1/observer/queue", &[]).await?;
- output_success(&response, output_format, false);
+ output_success(&response, output_format, compact);
Ok(())
}
pub async fn vikingdb(
client: &HttpClient,
output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let response: serde_json::Value = client.get("/api/v1/observer/vikingdb", &[]).await?;
- output_success(&response, output_format, false);
+ output_success(&response, output_format, compact);
Ok(())
}
pub async fn vlm(
client: &HttpClient,
output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let response: serde_json::Value = client.get("/api/v1/observer/vlm", &[]).await?;
- output_success(&response, output_format, false);
+ output_success(&response, output_format, compact);
Ok(())
}
pub async fn system(
client: &HttpClient,
output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let response: serde_json::Value = client.get("/api/v1/observer/system", &[]).await?;
- output_success(&response, output_format, false);
+ output_success(&response, output_format, compact);
Ok(())
}
diff --git a/crates/ov_cli/src/commands/pack.rs b/crates/ov_cli/src/commands/pack.rs
index 68db4c27a..7f6e4dcfa 100644
--- a/crates/ov_cli/src/commands/pack.rs
+++ b/crates/ov_cli/src/commands/pack.rs
@@ -7,9 +7,10 @@ pub async fn export(
uri: &str,
to: &str,
format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let result = client.export_ovpack(uri, to).await?;
- output_success(&result, format, false);
+ output_success(&result, format, compact);
Ok(())
}
@@ -20,11 +21,12 @@ pub async fn import(
force: bool,
no_vectorize: bool,
format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let vectorize = !no_vectorize;
let result = client
.import_ovpack(file_path, target, force, vectorize)
.await?;
- output_success(&result, format, false);
+ output_success(&result, format, compact);
Ok(())
}
diff --git a/crates/ov_cli/src/commands/relations.rs b/crates/ov_cli/src/commands/relations.rs
index c988d1675..357755e62 100644
--- a/crates/ov_cli/src/commands/relations.rs
+++ b/crates/ov_cli/src/commands/relations.rs
@@ -6,9 +6,10 @@ pub async fn list_relations(
client: &HttpClient,
uri: &str,
format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let result = client.relations(uri).await?;
- output_success(&result, format, false);
+ output_success(&result, format, compact);
Ok(())
}
@@ -18,6 +19,7 @@ pub async fn link(
to_uris: &Vec<String>,
reason: &str,
format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let result = client.link(from_uri, to_uris, reason).await?;
// If the server returns null/empty, show a confirmation summary
@@ -27,9 +29,9 @@ pub async fn link(
"to": to_uris,
"reason": reason,
});
- output_success(&summary, format, false);
+ output_success(&summary, format, compact);
} else {
- output_success(&result, format, false);
+ output_success(&result, format, compact);
}
Ok(())
}
@@ -39,6 +41,7 @@ pub async fn unlink(
from_uri: &str,
to_uri: &str,
format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let result = client.unlink(from_uri, to_uri).await?;
if result.is_null() {
@@ -46,9 +49,9 @@ pub async fn unlink(
"from": from_uri,
"to": to_uri,
});
- output_success(&summary, format, false);
+ output_success(&summary, format, compact);
} else {
- output_success(&result, format, false);
+ output_success(&result, format, compact);
}
Ok(())
}
diff --git a/crates/ov_cli/src/commands/resources.rs b/crates/ov_cli/src/commands/resources.rs
index 221b4fcd5..2ecf5f524 100644
--- a/crates/ov_cli/src/commands/resources.rs
+++ b/crates/ov_cli/src/commands/resources.rs
@@ -11,11 +11,12 @@ pub async fn add_resource(
wait: bool,
timeout: Option<f64>,
format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let result = client
.add_resource(path, to, &reason, &instruction, wait, timeout)
.await?;
- output_success(&result, format, false);
+ output_success(&result, format, compact);
Ok(())
}
@@ -25,8 +26,9 @@ pub async fn add_skill(
wait: bool,
timeout: Option<f64>,
format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let result = client.add_skill(data, wait, timeout).await?;
- output_success(&result, format, false);
+ output_success(&result, format, compact);
Ok(())
}
diff --git a/crates/ov_cli/src/commands/search.rs b/crates/ov_cli/src/commands/search.rs
index 218265268..45a4d00b7 100644
--- a/crates/ov_cli/src/commands/search.rs
+++ b/crates/ov_cli/src/commands/search.rs
@@ -9,9 +9,10 @@ pub async fn find(
limit: i32,
threshold: Option<f64>,
output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let result = client.find(query.to_string(), uri.to_string(), limit, threshold).await?;
- output_success(&result, output_format, false);
+ output_success(&result, output_format, compact);
Ok(())
}
@@ -23,9 +24,10 @@ pub async fn search(
limit: i32,
threshold: Option<f64>,
output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let result = client.search(query.to_string(), uri.to_string(), session_id, limit, threshold).await?;
- output_success(&result, output_format, false);
+ output_success(&result, output_format, compact);
Ok(())
}
@@ -35,9 +37,10 @@ pub async fn grep(
pattern: &str,
ignore_case: bool,
output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let result = client.grep(uri, pattern, ignore_case).await?;
- output_success(&result, output_format, false);
+ output_success(&result, output_format, compact);
Ok(())
}
@@ -46,8 +49,9 @@ pub async fn glob(
pattern: &str,
uri: &str,
output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let result = client.glob(pattern, uri).await?;
- output_success(&result, output_format, false);
+ output_success(&result, output_format, compact);
Ok(())
}
diff --git a/crates/ov_cli/src/commands/session.rs b/crates/ov_cli/src/commands/session.rs
index 617e1829d..a46efa435 100644
--- a/crates/ov_cli/src/commands/session.rs
+++ b/crates/ov_cli/src/commands/session.rs
@@ -6,18 +6,20 @@ use serde_json::json;
pub async fn new_session(
client: &HttpClient,
output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let response: serde_json::Value = client.post("/api/v1/sessions", &json!({})).await?;
- output_success(&response, output_format, false);
+ output_success(&response, output_format, compact);
Ok(())
}
pub async fn list_sessions(
client: &HttpClient,
output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let response: serde_json::Value = client.get("/api/v1/sessions", &[]).await?;
- output_success(&response, output_format, false);
+ output_success(&response, output_format, compact);
Ok(())
}
@@ -25,10 +27,11 @@ pub async fn get_session(
client: &HttpClient,
session_id: &str,
output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let path = format!("/api/v1/sessions/{}", url_encode(session_id));
let response: serde_json::Value = client.get(&path, &[]).await?;
- output_success(&response, output_format, false);
+ output_success(&response, output_format, compact);
Ok(())
}
@@ -36,6 +39,7 @@ pub async fn delete_session(
client: &HttpClient,
session_id: &str,
output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let path = format!("/api/v1/sessions/{}", url_encode(session_id));
let response: serde_json::Value = client.delete(&path, &[]).await?;
@@ -47,7 +51,7 @@ pub async fn delete_session(
response
};
- output_success(&result, output_format, false);
+ output_success(&result, output_format, compact);
Ok(())
}
@@ -57,6 +61,7 @@ pub async fn add_message(
role: &str,
content: &str,
output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let path = format!("/api/v1/sessions/{}/messages", url_encode(session_id));
let body = json!({
@@ -65,7 +70,7 @@ pub async fn add_message(
});
let response: serde_json::Value = client.post(&path, &body).await?;
- output_success(&response, output_format, false);
+ output_success(&response, output_format, compact);
Ok(())
}
@@ -73,10 +78,11 @@ pub async fn commit_session(
client: &HttpClient,
session_id: &str,
output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let path = format!("/api/v1/sessions/{}/commit", url_encode(session_id));
let response: serde_json::Value = client.post(&path, &json!({})).await?;
- output_success(&response, output_format, false);
+ output_success(&response, output_format, compact);
Ok(())
}
diff --git a/crates/ov_cli/src/commands/system.rs b/crates/ov_cli/src/commands/system.rs
index 1e662422a..6f4b74c5c 100644
--- a/crates/ov_cli/src/commands/system.rs
+++ b/crates/ov_cli/src/commands/system.rs
@@ -7,6 +7,7 @@ pub async fn wait(
client: &HttpClient,
timeout: Option<f64>,
output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let path = if let Some(t) = timeout {
format!("/api/v1/system/wait?timeout={}", t)
@@ -15,34 +16,36 @@ pub async fn wait(
};
let response: serde_json::Value = client.post(&path, &json!({})).await?;
- output_success(&response, output_format, false);
+ output_success(&response, output_format, compact);
Ok(())
}
pub async fn status(
client: &HttpClient,
output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let response: serde_json::Value = client.get("/api/v1/system/status", &[]).await?;
- output_success(&response, output_format, false);
+ output_success(&response, output_format, compact);
Ok(())
}
pub async fn health(
client: &HttpClient,
output_format: OutputFormat,
+ compact: bool,
) -> Result<()> {
let response: serde_json::Value = client.get("/health", &[]).await?;
// For health check, if it's a simple status, just print it
if let Some(status) = response.get("status").and_then(|v| v.as_str()) {
if matches!(output_format, OutputFormat::Json) {
- output_success(&response, output_format, false);
+ output_success(&response, output_format, compact);
} else {
println!("{}", status);
}
} else {
- output_success(&response, output_format, false);
+ output_success(&response, output_format, compact);
}
Ok(())
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 6e9f99a22..0d2ac0ceb 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -14,14 +14,16 @@ use output::OutputFormat;
pub struct CliContext {
pub config: Config,
pub output_format: OutputFormat,
+ pub compact: bool,
}
impl CliContext {
- pub fn new(output_format: OutputFormat) -> Result<Self> {
+ pub fn new(output_format: OutputFormat, compact: bool) -> Result<Self> {
let config = Config::load()?;
Ok(Self {
config,
output_format,
+ compact,
})
}
@@ -40,9 +42,9 @@ struct Cli {
#[arg(short, long, value_enum, default_value = "table", global = true)]
output: OutputFormat,
- /// Output compact JSON with {ok, result} wrapper (for scripts)
- #[arg(long, global = true)]
- json: bool,
+ /// Compact representation, defaults to true - compacts JSON output or uses simplified representation for Table output
+ #[arg(short, long, global = true, default_value = "true")]
+ compact: bool,
#[command(subcommand)]
command: Commands,
@@ -328,14 +330,10 @@ enum ConfigCommands {
async fn main() {
let cli = Cli::parse();
- // --json flag overrides output format
- let output_format = if cli.json {
- OutputFormat::Json
- } else {
- cli.output
- };
+ let output_format = cli.output;
+ let compact = cli.compact;
- let ctx = match CliContext::new(output_format) {
+ let ctx = match CliContext::new(output_format, compact) {
Ok(ctx) => ctx,
Err(e) => {
eprintln!("Error: {}", e);
@@ -425,7 +423,7 @@ async fn handle_add_resource(
) -> Result<()> {
let client = ctx.get_client();
commands::resources::add_resource(
- &client, &path, to, reason, instruction, wait, timeout, ctx.output_format
+ &client, &path, to, reason, instruction, wait, timeout, ctx.output_format, ctx.compact
).await
}
@@ -437,13 +435,13 @@ async fn handle_add_skill(
) -> Result<()> {
let client = ctx.get_client();
commands::resources::add_skill(
- &client, &data, wait, timeout, ctx.output_format
+ &client, &data, wait, timeout, ctx.output_format, ctx.compact
).await
}
async fn handle_relations(uri: String, ctx: CliContext) -> Result<()> {
let client = ctx.get_client();
- commands::relations::list_relations(&client, &uri, ctx.output_format
+ commands::relations::list_relations(&client, &uri, ctx.output_format, ctx.compact
).await
}
@@ -455,7 +453,7 @@ async fn handle_link(
) -> Result<()> {
let client = ctx.get_client();
commands::relations::link(
- &client, &from_uri, &to_uris, &reason, ctx.output_format
+ &client, &from_uri, &to_uris, &reason, ctx.output_format, ctx.compact
).await
}
@@ -466,13 +464,13 @@ async fn handle_unlink(
) -> Result<()> {
let client = ctx.get_client();
commands::relations::unlink(
- &client, &from_uri, &to_uri, ctx.output_format
+ &client, &from_uri, &to_uri, ctx.output_format, ctx.compact
).await
}
async fn handle_export(uri: String, to: String, ctx: CliContext) -> Result<()> {
let client = ctx.get_client();
- commands::pack::export(&client, &uri, &to, ctx.output_format
+ commands::pack::export(&client, &uri, &to, ctx.output_format, ctx.compact
).await
}
@@ -485,7 +483,7 @@ async fn handle_import(
) -> Result<()> {
let client = ctx.get_client();
commands::pack::import(
- &client, &file_path, &target_uri, force, no_vectorize, ctx.output_format
+ &client, &file_path, &target_uri, force, no_vectorize, ctx.output_format, ctx.compact
).await
}
@@ -493,13 +491,13 @@ async fn handle_system(cmd: SystemCommands, ctx: CliContext) -> Result<()> {
let client = ctx.get_client();
match cmd {
SystemCommands::Wait { timeout } => {
- commands::system::wait(&client, timeout, ctx.output_format).await
+ commands::system::wait(&client, timeout, ctx.output_format, ctx.compact).await
}
SystemCommands::Status => {
- commands::system::status(&client, ctx.output_format).await
+ commands::system::status(&client, ctx.output_format, ctx.compact).await
}
SystemCommands::Health => {
- commands::system::health(&client, ctx.output_format).await
+ commands::system::health(&client, ctx.output_format, ctx.compact).await
}
}
}
@@ -508,16 +506,16 @@ async fn handle_observer(cmd: ObserverCommands, ctx: CliContext) -> Result<()> {
let client = ctx.get_client();
match cmd {
ObserverCommands::Queue => {
- commands::observer::queue(&client, ctx.output_format).await
+ commands::observer::queue(&client, ctx.output_format, ctx.compact).await
}
ObserverCommands::Vikingdb => {
- commands::observer::vikingdb(&client, ctx.output_format).await
+ commands::observer::vikingdb(&client, ctx.output_format, ctx.compact).await
}
ObserverCommands::Vlm => {
- commands::observer::vlm(&client, ctx.output_format).await
+ commands::observer::vlm(&client, ctx.output_format, ctx.compact).await
}
ObserverCommands::System => {
- commands::observer::system(&client, ctx.output_format).await
+ commands::observer::system(&client, ctx.output_format, ctx.compact).await
}
}
}
@@ -526,26 +524,26 @@ async fn handle_session(cmd: SessionCommands, ctx: CliContext) -> Result<()> {
let client = ctx.get_client();
match cmd {
SessionCommands::New => {
- commands::session::new_session(&client, ctx.output_format).await
+ commands::session::new_session(&client, ctx.output_format, ctx.compact).await
}
SessionCommands::List => {
- commands::session::list_sessions(&client, ctx.output_format).await
+ commands::session::list_sessions(&client, ctx.output_format, ctx.compact).await
}
SessionCommands::Get { session_id } => {
- commands::session::get_session(&client, &session_id, ctx.output_format
+ commands::session::get_session(&client, &session_id, ctx.output_format, ctx.compact
).await
}
SessionCommands::Delete { session_id } => {
- commands::session::delete_session(&client, &session_id, ctx.output_format
+ commands::session::delete_session(&client, &session_id, ctx.output_format, ctx.compact
).await
}
SessionCommands::AddMessage { session_id, role, content } => {
commands::session::add_message(
- &client, &session_id, &role, &content, ctx.output_format
+ &client, &session_id, &role, &content, ctx.output_format, ctx.compact
).await
}
SessionCommands::Commit { session_id } => {
- commands::session::commit_session(&client, &session_id, ctx.output_format
+ commands::session::commit_session(&client, &session_id, ctx.output_format, ctx.compact
).await
}
}
@@ -578,17 +576,17 @@ async fn handle_config(cmd: ConfigCommands, _ctx: CliContext) -> Result<()> {
async fn handle_read(uri: String, ctx: CliContext) -> Result<()> {
let client = ctx.get_client();
- commands::content::read(&client, &uri, ctx.output_format).await
+ commands::content::read(&client, &uri, ctx.output_format, ctx.compact).await
}
async fn handle_abstract(uri: String, ctx: CliContext) -> Result<()> {
let client = ctx.get_client();
- commands::content::abstract_content(&client, &uri, ctx.output_format).await
+ commands::content::abstract_content(&client, &uri, ctx.output_format, ctx.compact).await
}
async fn handle_overview(uri: String, ctx: CliContext) -> Result<()> {
let client = ctx.get_client();
- commands::content::overview(&client, &uri, ctx.output_format).await
+ commands::content::overview(&client, &uri, ctx.output_format, ctx.compact).await
}
async fn handle_find(
@@ -599,7 +597,7 @@ async fn handle_find(
ctx: CliContext,
) -> Result<()> {
let client = ctx.get_client();
- commands::search::find(&client, &query, &uri, limit, threshold, ctx.output_format).await
+ commands::search::find(&client, &query, &uri, limit, threshold, ctx.output_format, ctx.compact).await
}
async fn handle_search(
@@ -611,45 +609,45 @@ async fn handle_search(
ctx: CliContext,
) -> Result<()> {
let client = ctx.get_client();
- commands::search::search(&client, &query, &uri, session_id, limit, threshold, ctx.output_format).await
+ commands::search::search(&client, &query, &uri, session_id, limit, threshold, ctx.output_format, ctx.compact).await
}
async fn handle_ls(uri: String, simple: bool, recursive: bool, ctx: CliContext) -> Result<()> {
let client = ctx.get_client();
- commands::filesystem::ls(&client, &uri, simple, recursive, ctx.output_format).await
+ commands::filesystem::ls(&client, &uri, simple, recursive, ctx.output_format, ctx.compact).await
}
async fn handle_tree(uri: String, ctx: CliContext) -> Result<()> {
let client = ctx.get_client();
- commands::filesystem::tree(&client, &uri, ctx.output_format).await
+ commands::filesystem::tree(&client, &uri, ctx.output_format, ctx.compact).await
}
async fn handle_mkdir(uri: String, ctx: CliContext) -> Result<()> {
let client = ctx.get_client();
- commands::filesystem::mkdir(&client, &uri, ctx.output_format).await
+ commands::filesystem::mkdir(&client, &uri, ctx.output_format, ctx.compact).await
}
async fn handle_rm(uri: String, recursive: bool, ctx: CliContext) -> Result<()> {
let client = ctx.get_client();
- commands::filesystem::rm(&client, &uri, recursive, ctx.output_format).await
+ commands::filesystem::rm(&client, &uri, recursive, ctx.output_format, ctx.compact).await
}
async fn handle_mv(from_uri: String, to_uri: String, ctx: CliContext) -> Result<()> {
let client = ctx.get_client();
- commands::filesystem::mv(&client, &from_uri, &to_uri, ctx.output_format).await
+ commands::filesystem::mv(&client, &from_uri, &to_uri, ctx.output_format, ctx.compact).await
}
async fn handle_stat(uri: String, ctx: CliContext) -> Result<()> {
let client = ctx.get_client();
- commands::filesystem::stat(&client, &uri, ctx.output_format).await
+ commands::filesystem::stat(&client, &uri, ctx.output_format, ctx.compact).await
}
async fn handle_grep(uri: String, pattern: String, ignore_case: bool, ctx: CliContext) -> Result<()> {
let client = ctx.get_client();
- commands::search::grep(&client, &uri, &pattern, ignore_case, ctx.output_format).await
+ commands::search::grep(&client, &uri, &pattern, ignore_case, ctx.output_format, ctx.compact).await
}
async fn handle_glob(pattern: String, uri: String, ctx: CliContext) -> Result<()> {
let client = ctx.get_client();
- commands::search::glob(&client, &pattern, &uri, ctx.output_format).await
+ commands::search::glob(&client, &pattern, &uri, ctx.output_format, ctx.compact).await
}
diff --git a/crates/ov_cli/src/output.rs b/crates/ov_cli/src/output.rs
index 86724e34c..c6db0f430 100644
--- a/crates/ov_cli/src/output.rs
+++ b/crates/ov_cli/src/output.rs
@@ -2,6 +2,8 @@ use serde::Serialize;
use serde_json::json;
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
+const MAX_COL_WIDTH: usize = 256;
+
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum OutputFormat {
Table,
@@ -17,17 +19,24 @@ impl From<&str> for OutputFormat {
}
}
-pub fn output_success<T: Serialize>(result: T, format: OutputFormat, json_output: bool) {
- if json_output || matches!(format, OutputFormat::Json) {
- println!("{}", json!({ "ok": true, "result": result }));
+pub fn output_success<T: Serialize>(result: T, format: OutputFormat, compact: bool) {
+ if matches!(format, OutputFormat::Json) {
+ if compact {
+ println!("{}", json!({ "ok": true, "result": result }));
+ } else {
+ println!(
+ "{}",
+ serde_json::to_string_pretty(&result).unwrap_or_default()
+ );
+ }
} else {
- print_table(result);
+ print_table(result, compact);
}
}
#[allow(dead_code)]
-pub fn output_error(code: &str, message: &str, format: OutputFormat, json_output: bool) {
- if json_output || matches!(format, OutputFormat::Json) {
+pub fn output_error(code: &str, message: &str, format: OutputFormat, compact: bool) {
+ if matches!(format, OutputFormat::Json) && compact {
eprintln!(
"{}",
json!({
@@ -43,26 +52,33 @@ pub fn output_error(code: &str, message: &str, format: OutputFormat, json_output
}
}
-fn print_table<T: Serialize>(result: T) {
+fn print_table<T: Serialize>(result: T, compact: bool) {
// Convert to json Value for processing
let value = match serde_json::to_value(&result) {
Ok(v) => v,
Err(_) => {
- println!("{}", serde_json::to_string_pretty(&result).unwrap_or_default());
+ if compact {
+ println!("{}", serde_json::to_string(&result).unwrap_or_default());
+ } else {
+ println!(
+ "{}",
+ serde_json::to_string_pretty(&result).unwrap_or_default()
+ );
+ }
return;
}
};
-
+
// Handle string result
if let Some(s) = value.as_str() {
println!("{}", s);
return;
}
-
+
// Handle array of objects
if let Some(items) = value.as_array() {
if !items.is_empty() {
- if let Some(table) = format_array_to_table(items) {
+ if let Some(table) = format_array_to_table(items, compact) {
println!("{}", table);
return;
}
@@ -71,41 +87,275 @@ fn print_table<T: Serialize>(result: T) {
return;
}
}
-
+
// Handle object
if let Some(obj) = value.as_object() {
if !obj.is_empty() {
- // Calculate max key width
- let max_key_width = obj.keys()
- .map(|k| k.width())
- .max()
- .unwrap_or(0)
- .min(120);
-
- let mut output = String::new();
- for (k, v) in obj {
- let is_uri = k == "uri";
- let formatted_value = format_value(v);
- let (content, _) = truncate_string(&formatted_value, is_uri, 120);
- let padded_key = pad_cell(k, max_key_width, false);
- output.push_str(&format!("{} {}\n", padded_key, content));
+ // Rule 5: ComponentStatus (name + is_healthy + status)
+ if obj.contains_key("name")
+ && obj.contains_key("is_healthy")
+ && obj.contains_key("status")
+ {
+ let health = if obj["is_healthy"].as_bool().unwrap_or(false) {
+ "healthy"
+ } else {
+ "unhealthy"
+ };
+ let name = obj["name"].as_str().unwrap_or("");
+ let status = obj["status"].as_str().unwrap_or("");
+ println!("[{}] ({})\n{}", name, health, status);
+ return;
+ }
+
+ // Rule 6: SystemStatus (is_healthy + components)
+ if obj.contains_key("components") && obj.contains_key("is_healthy") {
+ let mut lines: Vec<String> = Vec::new();
+ if let Some(components) = obj["components"].as_object() {
+ for (_key, comp) in components {
+ // Try to render each component as table
+ let comp_table = value_to_table(comp, compact);
+ if let Some(table) = comp_table {
+ lines.push(table);
+ lines.push("".to_string());
+ }
+ }
+ }
+ let health = if obj["is_healthy"].as_bool().unwrap_or(false) {
+ "healthy"
+ } else {
+ "unhealthy"
+ };
+ lines.push(format!("[system] ({})", health));
+ if let Some(errors) = obj.get("errors") {
+ if let Some(err_list) = errors.as_array() {
+ let error_strs: Vec<&str> =
+ err_list.iter().filter_map(|e| e.as_str()).collect();
+ if !error_strs.is_empty() {
+ lines.push(format!("Errors: {}", error_strs.join(", ")));
+ }
+ }
+ }
+ println!("{}", lines.join("\n"));
+ return;
+ }
+
+ // Extract list fields
+ let mut dict_lists: Vec<(String, &Vec<serde_json::Value>)> = Vec::new();
+ let mut prim_lists: Vec<(String, &Vec<serde_json::Value>)> = Vec::new();
+
+ for (key, val) in obj {
+ if let Some(arr) = val.as_array() {
+ if !arr.is_empty() {
+ if arr.iter().all(|item| item.is_object()) {
+ dict_lists.push((key.clone(), arr));
+ } else if arr
+ .iter()
+ .all(|item| item.is_string() || item.is_number() || item.is_boolean())
+ {
+ prim_lists.push((key.clone(), arr));
+ }
+ }
+ }
+ }
+
+ // Rule 3a: single list[primitive] -> one item per line
+ if dict_lists.is_empty() && prim_lists.len() == 1 {
+ let (key, items) = &prim_lists[0];
+ let col = if key.ends_with("es") {
+ key.strip_suffix("es").unwrap_or(key)
+ } else if key.ends_with('s') {
+ key.strip_suffix('s').unwrap_or(key)
+ } else {
+ key
+ };
+ let mut rows: Vec<serde_json::Value> = Vec::new();
+ for item in *items {
+ let mut row = serde_json::Map::new();
+ row.insert(col.to_string(), item.clone());
+ rows.push(serde_json::Value::Object(row));
+ }
+ if let Some(table) = format_array_to_table(&rows, compact) {
+ println!("{}", table);
+ return;
+ }
+ }
+
+ // Rule 3b: single list[dict] -> render directly
+ if dict_lists.len() == 1 && prim_lists.is_empty() {
+ let (_key, items) = &dict_lists[0];
+ if let Some(table) = format_array_to_table(items, compact) {
+ println!("{}", table);
+ return;
+ }
+ }
+
+ // Rule 2: multiple list[dict] -> flatten with type column
+ if !dict_lists.is_empty() {
+ let mut merged: Vec<serde_json::Value> = Vec::new();
+ for (key, items) in &dict_lists {
+ let type_name = if key.ends_with("es") {
+ key.strip_suffix("es").unwrap_or(key)
+ } else if key.ends_with('s') {
+ key.strip_suffix('s').unwrap_or(key)
+ } else {
+ key
+ };
+ for item in *items {
+ if let Some(mut obj) = item.as_object().cloned() {
+ obj.insert(
+ "type".to_string(),
+ serde_json::Value::String(type_name.to_string()),
+ );
+ merged.push(serde_json::Value::Object(obj));
+ }
+ }
+ }
+ if !merged.is_empty() {
+ if let Some(table) = format_array_to_table(&merged, compact) {
+ println!("{}", table);
+ return;
+ }
+ }
+ }
+
+ // Rule 4: plain dict (no expandable lists) -> single-row horizontal table
+ if dict_lists.is_empty() && prim_lists.is_empty() {
+ // Calculate max key width
+ let max_key_width = obj
+ .keys()
+ .map(|k| k.width())
+ .max()
+ .unwrap_or(0)
+ .min(MAX_COL_WIDTH);
+
+ let mut output = String::new();
+ for (k, v) in obj {
+ let is_uri = k == "uri";
+ let formatted_value = format_value(v);
+ let (content, _) = truncate_string(&formatted_value, is_uri, MAX_COL_WIDTH);
+ let padded_key = pad_cell(k, max_key_width, false);
+ output.push_str(&format!("{} {}\n", padded_key, content));
+ }
+ println!("{}", output);
+ return;
}
- println!("{}", output);
- return;
}
}
-
+
// Default: JSON output
- println!("{}", serde_json::to_string_pretty(&result).unwrap_or_default());
+ if compact {
+ println!("{}", serde_json::to_string(&result).unwrap_or_default());
+ } else {
+ println!(
+ "{}",
+ serde_json::to_string_pretty(&result).unwrap_or_default()
+ );
+ }
+}
+
+fn value_to_table(value: &serde_json::Value, compact: bool) -> Option<String> {
+ // Rule 1: list[dict] -> multi-row table
+ if let Some(items) = value.as_array() {
+ if !items.is_empty() && items.iter().all(|i| i.is_object()) {
+ return format_array_to_table(items, compact);
+ }
+ }
+
+ if let Some(obj) = value.as_object() {
+ // ComponentStatus (name + is_healthy + status)
+ if obj.contains_key("name") && obj.contains_key("is_healthy") && obj.contains_key("status")
+ {
+ let health = if obj["is_healthy"].as_bool().unwrap_or(false) {
+ "healthy"
+ } else {
+ "unhealthy"
+ };
+ let name = obj["name"].as_str().unwrap_or("");
+ let status = obj["status"].as_str().unwrap_or("");
+ return Some(format!("[{}] ({})\n{}", name, health, status));
+ }
+
+ // Extract list fields
+ let mut dict_lists: Vec<(String, &Vec<serde_json::Value>)> = Vec::new();
+ let mut prim_lists: Vec<(String, &Vec<serde_json::Value>)> = Vec::new();
+
+ for (key, val) in obj {
+ if let Some(arr) = val.as_array() {
+ if !arr.is_empty() {
+ if arr.iter().all(|item| item.is_object()) {
+ dict_lists.push((key.clone(), arr));
+ } else if arr
+ .iter()
+ .all(|item| item.is_string() || item.is_number() || item.is_boolean())
+ {
+ prim_lists.push((key.clone(), arr));
+ }
+ }
+ }
+ }
+
+ // Rule 3a: single list[primitive] -> one item per line
+ if dict_lists.is_empty() && prim_lists.len() == 1 {
+ let (key, items) = &prim_lists[0];
+ let col = if key.ends_with("es") {
+ key.strip_suffix("es").unwrap_or(key)
+ } else if key.ends_with('s') {
+ key.strip_suffix('s').unwrap_or(key)
+ } else {
+ key
+ };
+ let mut rows: Vec<serde_json::Value> = Vec::new();
+ for item in *items {
+ let mut row = serde_json::Map::new();
+ row.insert(col.to_string(), item.clone());
+ rows.push(serde_json::Value::Object(row));
+ }
+ return format_array_to_table(&rows, compact);
+ }
+
+ // Rule 3b: single list[dict] -> render directly
+ if dict_lists.len() == 1 && prim_lists.is_empty() {
+ let (_key, items) = &dict_lists[0];
+ return format_array_to_table(items, compact);
+ }
+
+ // Rule 2: multiple list[dict] -> flatten with type column
+ if !dict_lists.is_empty() {
+ let mut merged: Vec<serde_json::Value> = Vec::new();
+ for (key, items) in &dict_lists {
+ let type_name = if key.ends_with("es") {
+ key.strip_suffix("es").unwrap_or(key)
+ } else if key.ends_with('s') {
+ key.strip_suffix('s').unwrap_or(key)
+ } else {
+ key
+ };
+ for item in *items {
+ if let Some(mut obj) = item.as_object().cloned() {
+ obj.insert(
+ "type".to_string(),
+ serde_json::Value::String(type_name.to_string()),
+ );
+ merged.push(serde_json::Value::Object(obj));
+ }
+ }
+ }
+ if !merged.is_empty() {
+ return format_array_to_table(&merged, compact);
+ }
+ }
+ }
+
+ None
}
struct ColumnInfo {
- max_width: usize, // Max width for alignment (capped at 120)
- is_numeric: bool, // True if all values in column are numeric
- is_uri_column: bool, // True if column name is "uri"
+ max_width: usize, // Max width for alignment (capped at 120)
+ is_numeric: bool, // True if all values in column are numeric
+ is_uri_column: bool, // True if column name is "uri"
}
-fn format_array_to_table(items: &Vec<serde_json::Value>) -> Option<String> {
+fn format_array_to_table(items: &Vec<serde_json::Value>, compact: bool) -> Option<String> {
if items.is_empty() {
return None;
}
@@ -115,7 +365,7 @@ fn format_array_to_table(items: &Vec<serde_json::Value>) -> Option<String> {
// Handle list of primitives
let mut output = String::new();
for item in items {
- let (content, _) = truncate_string(&format_value(item), false, 120);
+ let (content, _) = truncate_string(&format_value(item), false, MAX_COL_WIDTH);
output.push_str(&format!("{}\n", content));
}
return Some(output);
@@ -139,6 +389,33 @@ fn format_array_to_table(items: &Vec<serde_json::Value>) -> Option<String> {
return None;
}
+ // Filter out empty columns when compact is true
+ let filtered_keys: Vec<String> = if compact {
+ keys.iter()
+ .filter(|key| {
+ items.iter().any(|item| {
+ if let Some(obj) = item.as_object() {
+ if let Some(value) = obj.get(*key) {
+ return !value.is_null()
+ && value != ""
+ && !(value.is_array() && value.as_array().unwrap().is_empty());
+ }
+ }
+ false
+ })
+ })
+ .cloned()
+ .collect()
+ } else {
+ keys.clone()
+ };
+
+ if filtered_keys.is_empty() {
+ return None;
+ }
+
+ let keys = filtered_keys;
+
// First pass: analyze columns
let mut column_info: Vec<ColumnInfo> = Vec::new();
@@ -153,8 +430,7 @@ fn format_array_to_table(items: &Vec<serde_json::Value>) -> Option<String> {
let formatted = format_value(value);
let display_width = formatted.width();
- // Update max_width (capped at 120 for alignment calculation)
- max_width = max_width.max(display_width.min(120));
+ max_width = max_width.max(display_width.min(MAX_COL_WIDTH));
// Check if numeric
if is_numeric && !is_numeric_value(value) {
@@ -175,7 +451,8 @@ fn format_array_to_table(items: &Vec<serde_json::Value>) -> Option<String> {
let mut output = String::new();
// Header row
- let header_cells: Vec<String> = keys.iter()
+ let header_cells: Vec<String> = keys
+ .iter()
.enumerate()
.map(|(i, k)| pad_cell(k, column_info[i].max_width, false))
.collect();
@@ -185,19 +462,15 @@ fn format_array_to_table(items: &Vec<serde_json::Value>) -> Option<String> {
// Data rows
for item in items {
if let Some(obj) = item.as_object() {
- let row_cells: Vec<String> = keys.iter()
+ let row_cells: Vec<String> = keys
+ .iter()
.enumerate()
.map(|(i, k)| {
let info = &column_info[i];
- let value = obj.get(k)
- .map(|v| format_value(v))
- .unwrap_or_default();
+ let value = obj.get(k).map(|v| format_value(v)).unwrap_or_default();
- let (content, skip_padding) = truncate_string(
- &value,
- info.is_uri_column,
- info.max_width
- );
+ let (content, skip_padding) =
+ truncate_string(&value, info.is_uri_column, info.max_width);
if skip_padding {
// Long URI, output as-is without padding
@@ -251,21 +524,24 @@ fn is_numeric_value(v: &serde_json::Value) -> bool {
}
fn truncate_string(s: &str, is_uri: bool, max_width: usize) -> (String, bool) {
- const MAX_LEN: usize = 120;
let display_width = s.width();
- // URI columns: don't truncate if exceeds threshold
- if is_uri && display_width > max_width {
- return (s.to_string(), true); // true = skip padding
+ // URI columns: never truncate
+ if is_uri {
+ if display_width > max_width {
+ return (s.to_string(), true); // true = skip padding
+ } else {
+ return (s.to_string(), false);
+ }
}
// Normal truncation - truncate by display width
- if display_width > MAX_LEN {
+ if display_width > MAX_COL_WIDTH {
let mut current_width = 0;
let mut truncated = String::new();
for ch in s.chars() {
let ch_width = ch.width().unwrap_or(0);
- if current_width + ch_width > MAX_LEN - 3 {
+ if current_width + ch_width > MAX_COL_WIDTH - 3 {
break;
}
current_width += ch_width;
@@ -294,7 +570,7 @@ mod tests {
// This should not panic and should produce aligned output
// We can't easily capture stdout, but at least verify it doesn't crash
- print_table(obj);
+ print_table(obj, true);
}
#[test]
@@ -305,12 +581,12 @@ mod tests {
"uri": "viking://resources/very/long/path/that/exceeds/normal/width/limits/and/should/not/be/truncated/because/it/is/a/uri"
});
- print_table(obj);
+ print_table(obj, true);
}
#[test]
fn test_empty_object() {
let obj = json!({});
- print_table(obj);
+ print_table(obj, true);
}
}
diff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.md
index 3d8b49d8e..7b1b9c330 100644
--- a/docs/en/api/01-overview.md
+++ b/docs/en/api/01-overview.md
@@ -104,13 +104,11 @@ openviking [global options] <command> [arguments] [command options]
| Option | Description |
|--------|-------------|
| `--output`, `-o` | Output format: `table` (default), `json` |
-| `--json` | Compact JSON with `{ok, result}` wrapper (for scripts) |
| `--version` | Show CLI version |
Example:
```bash
-openviking --json ls viking://resources/
openviking -o json ls viking://resources/
```
diff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.md
index 29bec07f7..1cbdbcf95 100644
--- a/docs/zh/api/01-overview.md
+++ b/docs/zh/api/01-overview.md
@@ -104,13 +104,11 @@ openviking [全局选项] <command> [参数] [命令选项]
| 选项 | 说明 |
|------|------|
| `--output`, `-o` | 输出格式:`table`(默认)、`json` |
-| `--json` | 紧凑 JSON + `{ok, result}` 包装(用于脚本) |
| `--version` | 显示 CLI 版本 |
示例:
```bash
-openviking --json ls viking://resources/
openviking -o json ls viking://resources/
```
@@ -208,17 +206,18 @@ openviking -o json ls viking://resources/
}
```
-### 脚本模式(`--json`)
+### 紧凑模式(`--compact`, `-c`)
-紧凑 JSON + 状态包装,适用于脚本。覆盖 `--output`:
+- 当 `--output=json` 时:紧凑 JSON 格式 + `{ok, result}` 包装,适用于脚本
+- 当 `--output=table` 时:对表格输出采取精简表示(如去除空列等)
-**成功**
+**JSON 输出 - 成功**
```json
{"ok": true, "result": ...}
```
-**错误**
+**JSON 输出 - 错误**
```json
{"ok": false, "error": {"code": "NOT_FOUND", "message": "Resource not found", "details": {}}}
diff --git a/openviking/retrieve/hierarchical_retriever.py b/openviking/retrieve/hierarchical_retriever.py
index 4f9ff2353..ab97b8a50 100644
--- a/openviking/retrieve/hierarchical_retriever.py
+++ b/openviking/retrieve/hierarchical_retriever.py
@@ -323,7 +323,7 @@ class HierarchicalRetriever:
if passes_threshold(final_score) and uri not in visited:
r["_final_score"] = final_score
collected.append(r)
- logger.info(
+ logger.debug(
f"[RecursiveSearch] Added URI: {uri} to candidates with score: {final_score}"
)
if r.get("is_leaf"):
@@ -331,7 +331,7 @@ class HierarchicalRetriever:
continue
heapq.heappush(dir_queue, (-final_score, uri))
else:
- logger.info(
+ logger.debug(
f"[RecursiveSearch] URI {uri} score {final_score} did not pass threshold {effective_threshold}"
)
diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.py
index b451eec9a..3f3f173ef 100644
--- a/openviking/storage/viking_fs.py
+++ b/openviking/storage/viking_fs.py
@@ -179,11 +179,17 @@ class VikingFS:
"""Content search by pattern or keywords."""
path = self._uri_to_path(uri)
result = self.agfs.grep(path, pattern, True, case_insensitive)
- # Change file to uri
if result.get("matches", None) is None:
result["matches"] = []
+ new_matches = []
for match in result.get("matches", []):
- match["uri"] = self._path_to_uri(match.pop("file"))
+ new_match = {
+ "line": match.get("line"),
+ "uri": self._path_to_uri(match.get("file")),
+ "content": match.get("content"),
+ }
+ new_matches.append(new_match)
+ result["matches"] = new_matches
return result
async def stat(self, uri: str) -> Dict[str, Any]:
diff --git a/openviking_cli/cli/context.py b/openviking_cli/cli/context.py
index ec8ff7b44..e3fcae80e 100644
--- a/openviking_cli/cli/context.py
+++ b/openviking_cli/cli/context.py
@@ -19,7 +19,7 @@ class CliConfigError(ValueError):
class CLIContext:
"""Shared state for one CLI invocation."""
- json_output: bool = False
+ compact: bool = True
output_format: str = "table"
_client: Optional["SyncHTTPClient"] = field(default=None, init=False, repr=False)
diff --git a/openviking_cli/cli/main.py b/openviking_cli/cli/main.py
index 9e35370f5..fca32abcc 100644
--- a/openviking_cli/cli/main.py
+++ b/openviking_cli/cli/main.py
@@ -33,8 +33,11 @@ def _version_callback(value: bool) -> None:
@app.callback()
def main(
ctx: typer.Context,
- json_output: bool = typer.Option(
- False, "--json", help="Compact JSON with {ok, result} wrapper (for scripts)"
+ compact: bool = typer.Option(
+ True,
+ "--compact",
+ "-c",
+ help="Compact representation, defaults to true - compacts JSON output or uses simplified representation for Table output",
),
output_format: Optional[str] = typer.Option(
None, "--output", "-o", help="Output format: table (default), json"
@@ -60,7 +63,7 @@ def main(
if output_format is None:
output_format = "table"
- ctx.obj = CLIContext(json_output=json_output, output_format=output_format)
+ ctx.obj = CLIContext(compact=compact, output_format=output_format)
register_commands(app)
diff --git a/openviking_cli/cli/output.py b/openviking_cli/cli/output.py
index 0c5e4ff26..91260f9a1 100644
--- a/openviking_cli/cli/output.py
+++ b/openviking_cli/cli/output.py
@@ -35,20 +35,37 @@ def _truncate(val: Any) -> Any:
return s[: _MAX_COL_WIDTH - 3] + "..." if len(s) > _MAX_COL_WIDTH else val
-def _format_list_table(rows: List[Dict[str, Any]]) -> Optional[str]:
- """Render a list of dict rows as a table with truncation."""
+def _format_list_table(rows: List[Dict[str, Any]], compact: bool = True) -> Optional[str]:
+ """Render a list of dict rows as a table with truncation, skipping empty columns when compact=True."""
if not rows:
return None
- headers: List[str] = []
+
+ all_headers: List[str] = []
for row in rows:
for key in row.keys():
key_str = str(key)
- if key_str not in headers:
- headers.append(key_str)
- if not headers:
+ if key_str not in all_headers:
+ all_headers.append(key_str)
+
+ if not all_headers:
+ return None
+
+ non_empty_headers = []
+ for header in all_headers:
+ has_value = False
+ for row in rows:
+ val = row.get(header)
+ if val:
+ if val is not None and val != "" and not (isinstance(val, list) and len(val) == 0):
+ has_value = True
+ break
+ if has_value or not compact:
+ non_empty_headers.append(header)
+ if not non_empty_headers:
return None
- values = [[_truncate(row.get(h, "")) for h in headers] for row in rows]
- return tabulate(values, headers=headers, tablefmt="plain")
+
+ values = [[_truncate(row.get(h, "")) for h in non_empty_headers] for row in rows]
+ return tabulate(values, headers=non_empty_headers, tablefmt="plain")
def _is_primitive_list(v: Any) -> bool:
@@ -59,11 +76,11 @@ def _is_dict_list(v: Any) -> bool:
return isinstance(v, list) and v and all(isinstance(r, dict) for r in v)
-def _to_table(data: Any) -> Optional[str]:
+def _to_table(data: Any, compact: bool = True) -> Optional[str]:
"""Try to render data as a table. Returns None if not possible."""
# Rule 1: list[dict] -> multi-row table
if isinstance(data, list) and data and all(isinstance(r, dict) for r in data):
- return _format_list_table(data)
+ return _format_list_table(data, compact)
if not isinstance(data, dict):
return None
@@ -77,7 +94,7 @@ def _to_table(data: Any) -> Optional[str]:
if "components" in data and "is_healthy" in data:
lines: List[str] = []
for comp in data["components"].values():
- table = _to_table(comp)
+ table = _to_table(comp, compact)
if table:
lines.append(table)
lines.append("")
@@ -95,11 +112,11 @@ def _to_table(data: Any) -> Optional[str]:
if not dict_lists and len(prim_lists) == 1:
key, items = next(iter(prim_lists.items()))
col = key.rstrip("es") if key.endswith("es") else key.rstrip("s")
- return _format_list_table([{col: item} for item in items])
+ return _format_list_table([{col: item} for item in items], compact)
# Rule 3b: single list[dict] -> render directly
if len(dict_lists) == 1 and not prim_lists:
- return _format_list_table(next(iter(dict_lists.values())))
+ return _format_list_table(next(iter(dict_lists.values())), compact)
# Rule 2: multiple list[dict] -> flatten with type column
if dict_lists:
@@ -108,7 +125,7 @@ def _to_table(data: Any) -> Optional[str]:
for item in items:
merged.append({"type": key.rstrip("s"), **item})
if merged:
- return _format_list_table(merged)
+ return _format_list_table(merged, compact)
# Rule 4: plain dict (no expandable lists) -> single-row horizontal table
if not dict_lists and not prim_lists:
@@ -123,7 +140,7 @@ def output_success(ctx: CLIContext, result: Any) -> None:
"""Print successful command result."""
serializable = _to_serializable(result)
- if ctx.json_output:
+ if ctx.output_format == "json" and ctx.compact:
typer.echo(json.dumps({"ok": True, "result": serializable}, ensure_ascii=False))
return
if serializable is None:
@@ -133,12 +150,15 @@ def output_success(ctx: CLIContext, result: Any) -> None:
return
if ctx.output_format == "table":
- table = _to_table(serializable)
+ table = _to_table(serializable, ctx.compact)
if table is not None:
typer.echo(table)
return
- typer.echo(json.dumps(serializable, ensure_ascii=False, indent=2))
+ if ctx.compact:
+ typer.echo(json.dumps(serializable, ensure_ascii=False))
+ else:
+ typer.echo(json.dumps(serializable, ensure_ascii=False, indent=2))
def output_error(
@@ -151,7 +171,7 @@ def output_error(
) -> None:
"""Print error in JSON or plain format then exit."""
details = details or {}
- if ctx.json_output:
+ if ctx.output_format == "json" and ctx.compact:
payload = {
"ok": False,
"error": {
diff --git a/openviking_cli/retrieve/types.py b/openviking_cli/retrieve/types.py
index 4c0006531..9d22a8d9a 100644
--- a/openviking_cli/retrieve/types.py
+++ b/openviking_cli/retrieve/types.py
@@ -365,15 +365,15 @@ class FindResult:
def _context_to_dict(self, ctx: MatchedContext) -> Dict[str, Any]:
"""Convert MatchedContext to dict."""
return {
- "uri": ctx.uri,
"context_type": ctx.context_type.value,
+ "uri": ctx.uri,
"is_leaf": ctx.is_leaf,
- "abstract": ctx.abstract,
- "overview": ctx.overview,
- "category": ctx.category,
"score": ctx.score,
+ "category": ctx.category,
"match_reason": ctx.match_reason,
"relations": [{"uri": r.uri, "abstract": r.abstract} for r in ctx.relations],
+ "abstract": ctx.abstract,
+ "overview": ctx.overview,
}
def _query_to_dict(self, q: TypedQuery) -> Dict[str, Any]: