use serde_json::json;
use super::*;
fn index_entry(id: &str, root_path: &str) -> Value {
json!({ "id": id, "root_path": root_path, "size_bytes": 0 })
}
#[test]
fn pick_index_prefers_exact_match() {
let tmp = std::env::temp_dir();
let root = tmp.to_str().expect("utf8 temp dir");
let indexes = vec![
index_entry("other", "/nonexistent/elsewhere"),
index_entry("mine", root),
];
assert_eq!(pick_index(&indexes, &tmp).as_deref(), Some("mine"));
}
#[test]
fn pick_index_falls_back_to_longest_ancestor() {
let base = std::env::temp_dir();
let nested = base.join("tcode-pick-index-nested");
std::fs::create_dir_all(&nested).expect("mkdir nested");
let shallow = base.to_str().expect("utf8");
let deep = nested.to_str().expect("utf8");
let with_exact = vec![index_entry("ancestor", shallow), index_entry("exact", deep)];
assert_eq!(pick_index(&with_exact, &nested).as_deref(), Some("exact"));
let ancestor_only = vec![index_entry("ancestor", shallow)];
assert_eq!(
pick_index(&ancestor_only, &nested).as_deref(),
Some("ancestor")
);
let _ = std::fs::remove_dir_all(&nested);
}
#[test]
fn pick_index_returns_none_when_uncovered() {
let indexes = vec![index_entry("elsewhere", "/nonexistent/elsewhere")];
assert_eq!(
pick_index(&indexes, Path::new("/nonexistent/project")),
None
);
}
#[test]
fn mcp_text_extracts_content() {
let result = json!({ "content": [{ "type": "text", "text": "{\"indexes\":[]}" }] });
assert_eq!(mcp_text(&result).as_deref(), Some("{\"indexes\":[]}"));
let empty = json!({ "isError": false });
assert_eq!(mcp_text(&empty), None);
}
#[test]
fn is_mcp_error_detects_error_flag() {
assert!(is_mcp_error(&json!({ "isError": true, "content": [] })));
assert!(!is_mcp_error(&json!({ "isError": false })));
assert!(!is_mcp_error(&json!({ "content": [] })));
}
#[test]
fn is_stage_not_ready_detects_meta_code() {
let meta = json!({
"isError": true,
"content": [{ "type": "text", "text": "requires Stage 2 (embeddings), not yet ready" }],
"_meta": { "error_code": "STAGE_NOT_READY" }
});
assert!(is_stage_not_ready(&meta));
let other_code = json!({
"isError": true,
"_meta": { "error_code": "INDEX_NOT_FOUND" }
});
assert!(!is_stage_not_ready(&other_code));
let no_meta = json!({
"isError": true,
"content": [{ "type": "text", "text": "no index covers this project" }]
});
assert!(!is_stage_not_ready(&no_meta));
}
#[test]
fn should_lexical_fallback_only_for_stage_not_ready() {
let not_ready = json!({ "isError": true, "_meta": { "error_code": "STAGE_NOT_READY" } });
assert!(should_lexical_fallback("semantic", ¬_ready));
assert!(should_lexical_fallback("symbol", ¬_ready));
assert!(!should_lexical_fallback("grep", ¬_ready));
let other = json!({ "isError": true, "content": [{ "type": "text", "text": "boom" }] });
assert!(!should_lexical_fallback("semantic", &other));
}
#[test]
fn lexical_params_matches_search_lexical_schema() {
let params = lexical_params("trusty-tools", "apply_archive_downrank", 8);
assert_eq!(params["index_id"], "trusty-tools");
assert_eq!(params["query"], "apply_archive_downrank");
assert_eq!(params["top_k"], 8);
}
#[test]
fn build_call_routes_each_mode() {
let (tool, params) = build_call("semantic", "how does auth work", 5, Some("idx")).expect("ok");
assert_eq!(tool, "search_semantic");
assert_eq!(params["index_id"], "idx");
assert_eq!(params["query"], "how does auth work");
assert_eq!(params["top_k"], 5);
let (tool, params) = build_call("symbol", "validate_token", 5, Some("idx")).expect("ok");
assert_eq!(tool, "search_kg");
assert_eq!(params["query"], "validate_token");
let (tool, params) = build_call("grep", "TODO", 7, None).expect("ok");
assert_eq!(tool, "grep");
assert_eq!(params["pattern"], "TODO");
assert_eq!(params["max_results"], 7);
assert!(params.get("index_id").is_none());
}
#[test]
fn build_call_semantic_without_index_is_fallback() {
let err = build_call("semantic", "q", 5, None).expect_err("needs index");
assert!(err.contains("grep"), "must steer to local tools: {err}");
}
#[test]
fn schema_advertises_mode_and_query() {
let tool = TrustySearchTool::new(std::env::temp_dir());
let schema = tool.schema();
assert_eq!(schema["function"]["name"], SEARCH_CODE_TOOL_NAME);
let params = &schema["function"]["parameters"];
let required: Vec<&str> = params["required"]
.as_array()
.expect("required array")
.iter()
.filter_map(Value::as_str)
.collect();
assert_eq!(required, vec!["query"]);
assert_eq!(params["properties"]["mode"]["default"], "semantic");
assert_eq!(params["additionalProperties"], json!(false));
}
#[tokio::test]
async fn execute_fail_open_when_binary_absent() {
let tool = TrustySearchTool::new(std::env::temp_dir())
.with_binary("trusty-search-definitely-not-installed-xyzzy");
let result = tool.execute(json!({ "query": "how does auth work" })).await;
assert!(!result.is_error(), "must not surface as a tool error");
assert!(
result.content().contains("grep"),
"must steer to local tools: {}",
result.content()
);
}
#[tokio::test]
async fn execute_rejects_malformed_args_recoverably() {
let tool = TrustySearchTool::new(std::env::temp_dir())
.with_binary("trusty-search-definitely-not-installed-xyzzy");
let result = tool.execute(json!({ "mode": "semantic" })).await; assert!(result.is_error());
assert!(!result.is_fatal());
}