Skip to main content

trusty_code/tools/
trusty_search.rs

1//! `search_code` tool: trusty-search-backed code discovery (PR A).
2//!
3//! Why: local `glob`/`grep`/`list_dir` (#2685) find code by literal text only;
4//! the engineer routinely needs CONCEPTUAL discovery — "where is X", "how does
5//! Y work", "what calls Z" — which literal search cannot answer. trusty-search
6//! already indexes every registered project for semantic (embedding) and
7//! call-graph (KG) retrieval and ships as an MCP binary. This tool makes that
8//! the PRIMARY discovery path for the engineer while the local literal tools
9//! stay as the graceful-degrade FALLBACK: when trusty-search is not installed,
10//! not running, or its index is not ready, the tool returns a SUCCESSFUL
11//! "unavailable — use grep/glob" result rather than an error that would derail
12//! the agent loop (mirrors `recall_session`'s fail-open contract).
13//! What: [`TrustySearchTool`] implements `ToolExecutor`. It lazily spawns
14//! `trusty-search serve` via the SHARED `trusty_common::stdio_mcp_client`
15//! (never a bespoke MCP/HTTP client — common-entry-point principle, mirroring
16//! trusty-agents' `TrustySearchPlugin`), runs the MCP handshake, and resolves
17//! the project's index id from `list_indexes`. A single `search_code` tool with
18//! a `mode` param routes to trusty-search's real lanes: `semantic`
19//! (`search_semantic`), `symbol` (`search_kg`), and `grep` (`grep`). One tool
20//! keeps the advertised schema surface minimal and mirrors trusty-search's own
21//! lane taxonomy. A `STAGE_NOT_READY` on the semantic/symbol lane (the vector
22//! stage is still building on a freshly-indexed repo) transparently retries via
23//! the always-available lexical lane and returns those degraded hits instead of
24//! empty (issue #2783). Any remaining spawn/handshake/timeout/missing-index
25//! condition is fail-open: a non-error `ToolResult` telling the model to use
26//! the local `grep`/`glob` tools instead.
27//! Test: `tests::pick_index_prefers_exact_match`,
28//! `tests::pick_index_falls_back_to_longest_ancestor`,
29//! `tests::execute_fail_open_when_binary_absent`,
30//! `tests::execute_rejects_malformed_args_recoverably`,
31//! `tests::schema_advertises_mode_and_query`, `tests::mcp_text_extracts_content`,
32//! `tests::is_mcp_error_detects_error_flag`,
33//! `tests::is_stage_not_ready_detects_meta_code`,
34//! `tests::should_lexical_fallback_only_for_stage_not_ready`,
35//! `tests::lexical_params_matches_search_lexical_schema`.
36
37use std::path::{Path, PathBuf};
38
39use async_trait::async_trait;
40use serde::Deserialize;
41use serde_json::{Value, json};
42use tokio::sync::{Mutex, OnceCell};
43use tracing::warn;
44use trusty_common::stdio_mcp_client::StdioMcpClient;
45
46use crate::tools::traits::{ToolExecutor, ToolResult};
47
48/// The tool's registered/advertised name.
49pub const SEARCH_CODE_TOOL_NAME: &str = "search_code";
50
51/// Binary spawned in MCP stdio mode (`trusty-search serve`).
52const SEARCH_BINARY: &str = "trusty-search";
53
54/// `clientInfo.name` advertised during the MCP handshake.
55const CLIENT_NAME: &str = "trusty-code";
56
57/// Default `top_k` when the model omits it.
58const DEFAULT_TOP_K: usize = 10;
59
60/// Hard cap on `top_k` regardless of what the model requests.
61const MAX_TOP_K: usize = 25;
62
63/// The fail-open message steering the model back to the local literal tools.
64const FALLBACK_HINT: &str =
65    "trusty-search is unavailable; use the local `grep` and `glob` tools for this query instead.";
66
67/// Parsed `search_code` tool-call arguments.
68#[derive(Debug, Deserialize)]
69struct SearchArgs {
70    query: String,
71    #[serde(default)]
72    mode: Option<String>,
73    #[serde(default)]
74    top_k: Option<usize>,
75}
76
77/// A live trusty-search MCP session plus the resolved project index.
78///
79/// Why: MCP requests are not concurrency-safe (one in-flight request per stdio
80/// pair), so the client sits behind an async `Mutex`. `index_id` is resolved
81/// once at spawn from `list_indexes` because the semantic/KG lanes require it.
82/// What: `index_id` is `None` when no registered index covers the project root
83/// — the search lanes then fail open rather than guess a wrong index.
84/// Test: exercised via `execute_*` and `pick_index_*` in `tests`.
85struct SearchSession {
86    client: Mutex<StdioMcpClient>,
87    index_id: Option<String>,
88}
89
90/// `ToolExecutor` for the `search_code` discovery tool (PR A).
91///
92/// Why: gives the engineer a semantic/call-graph discovery path backed by
93/// trusty-search, scoped to the delegating run's project root.
94/// What: holds the project root (for index resolution + scoping) and lazily
95/// initialises one [`SearchSession`] on first use, caching the (possibly
96/// absent) session in a `OnceCell` so a missing/unreachable daemon is probed at
97/// most once per tool instance.
98/// Test: `tests::execute_fail_open_when_binary_absent`.
99pub struct TrustySearchTool {
100    project: PathBuf,
101    binary: String,
102    session: OnceCell<Option<SearchSession>>,
103}
104
105impl TrustySearchTool {
106    /// Construct a tool scoped to `project`, spawning the real `trusty-search`.
107    ///
108    /// Why: the engineer's registry builds one per delegation, scoped to the
109    /// project working tree.
110    /// What: defers all process spawning to first `execute` — construction is
111    /// cheap and side-effect-free.
112    /// Test: `tests::schema_advertises_mode_and_query`.
113    pub fn new(project: impl Into<PathBuf>) -> Self {
114        Self {
115            project: project.into(),
116            binary: SEARCH_BINARY.to_string(),
117            session: OnceCell::new(),
118        }
119    }
120
121    /// Override the spawned binary name (tests point this at a name that is
122    /// guaranteed absent to exercise the fail-open path deterministically).
123    ///
124    /// Why: the daemon-absent path must be unit-testable without depending on
125    /// whether `trusty-search` happens to be on the dev machine's PATH.
126    /// What: replaces the binary the lazy spawn invokes.
127    /// Test: `tests::execute_fail_open_when_binary_absent`.
128    #[cfg(test)]
129    pub fn with_binary(mut self, binary: impl Into<String>) -> Self {
130        self.binary = binary.into();
131        self
132    }
133
134    /// Lazily spawn + handshake + resolve the index, caching the result.
135    ///
136    /// Why: probing a missing/broken daemon on every call would add per-turn
137    /// latency; caching the `Option` probes at most once.
138    /// What: returns `&None` when spawn or handshake fails (fail-open).
139    /// Test: `tests::execute_fail_open_when_binary_absent`.
140    async fn session(&self) -> &Option<SearchSession> {
141        self.session
142            .get_or_init(|| spawn_session(&self.binary, &self.project))
143            .await
144    }
145}
146
147/// Spawn `trusty-search serve`, run the handshake, and resolve the index id.
148///
149/// Why: isolates the fallible startup so `session` stays a thin cache and the
150/// whole flow degrades to `None` on the first failure.
151/// What: returns `None` if the binary is absent, the handshake fails, or the
152/// process cannot start; otherwise a [`SearchSession`] whose `index_id` may
153/// still be `None` when no index covers the project.
154/// Test: covered opportunistically — a missing binary yields `None`, asserted
155/// via `tests::execute_fail_open_when_binary_absent`.
156async fn spawn_session(binary: &str, project: &Path) -> Option<SearchSession> {
157    let mut client = match StdioMcpClient::spawn(binary, &["serve"], CLIENT_NAME).await {
158        Ok(c) => c,
159        Err(e) => {
160            warn!(error = %e, "search_code: trusty-search spawn failed (fail-open)");
161            return None;
162        }
163    };
164    if let Err(e) = client.initialize().await {
165        warn!(error = %e, "search_code: trusty-search handshake failed (fail-open)");
166        return None;
167    }
168    let index_id = resolve_index_id(&mut client, project).await;
169    Some(SearchSession {
170        client: Mutex::new(client),
171        index_id,
172    })
173}
174
175/// Resolve the project's index id from `list_indexes`.
176///
177/// Why: the semantic/KG lanes require an `index_id`; deriving it from the
178/// project root avoids making the model call `list_indexes` and guess.
179/// What: calls the `list_indexes` MCP tool, parses the `{ "indexes": [...] }`
180/// detail payload, and matches the project root against each index `root_path`
181/// via [`pick_index`]. Returns `None` on any RPC/parse failure or no match.
182/// Test: `tests::pick_index_prefers_exact_match`.
183async fn resolve_index_id(client: &mut StdioMcpClient, project: &Path) -> Option<String> {
184    let result = client.call_tool("list_indexes", json!({})).await.ok()?;
185    let text = mcp_text(&result)?;
186    let body: Value = serde_json::from_str(&text).ok()?;
187    let indexes = body.get("indexes")?.as_array()?;
188    pick_index(indexes, project)
189}
190
191/// Pick the index whose `root_path` best covers `project`.
192///
193/// Why: a worktree/subdirectory of a registered repo should resolve to that
194/// repo's index even when the paths are not byte-identical.
195/// What: prefers an exact canonical match; otherwise the registered index whose
196/// canonical `root_path` is the longest ancestor of `project`. `None` when no
197/// index covers the project.
198/// Test: `tests::pick_index_prefers_exact_match`,
199/// `tests::pick_index_falls_back_to_longest_ancestor`.
200fn pick_index(indexes: &[Value], project: &Path) -> Option<String> {
201    let target = canonicalize_best_effort(project);
202    let mut best: Option<(usize, String)> = None;
203    for entry in indexes {
204        let Some(id) = entry.get("id").and_then(Value::as_str) else {
205            continue;
206        };
207        let Some(root) = entry.get("root_path").and_then(Value::as_str) else {
208            continue;
209        };
210        let root = canonicalize_best_effort(Path::new(root));
211        if root == target {
212            return Some(id.to_string());
213        }
214        if target.starts_with(&root) {
215            let depth = root.components().count();
216            if best.as_ref().is_none_or(|(d, _)| depth > *d) {
217                best = Some((depth, id.to_string()));
218            }
219        }
220    }
221    best.map(|(_, id)| id)
222}
223
224/// Canonicalise `p`, falling back to the path as given when it does not exist.
225///
226/// Why: index roots and the project path may be symlinked (worktrees under
227/// `$HOME`); canonicalising both makes ancestor comparison robust.
228/// What: `std::fs::canonicalize` with a lossless fallback.
229/// Test: exercised via `pick_index_*`.
230fn canonicalize_best_effort(p: &Path) -> PathBuf {
231    std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf())
232}
233
234/// Extract the first text frame from an MCP `tools/call` result.
235///
236/// Why: trusty-search wraps every payload as `content[0].text` (a JSON string).
237/// What: returns that string, or `None` when the frame is missing.
238/// Test: `tests::mcp_text_extracts_content`.
239fn mcp_text(result: &Value) -> Option<String> {
240    result
241        .get("content")
242        .and_then(|c| c.as_array())
243        .and_then(|items| items.first())
244        .and_then(|item| item.get("text"))
245        .and_then(|t| t.as_str())
246        .map(str::to_string)
247}
248
249/// Whether an MCP result carries the in-band `isError` flag (e.g.
250/// `STAGE_NOT_READY` when the semantic/KG lane is not yet built).
251///
252/// Why: trusty-search reports stage-not-ready as `isError: true` content rather
253/// than a JSON-RPC error, so `call_tool` returns `Ok`; we must inspect the flag
254/// to fail open.
255/// What: `true` when `result.isError == true`.
256/// Test: `tests::is_mcp_error_detects_error_flag`.
257fn is_mcp_error(result: &Value) -> bool {
258    result
259        .get("isError")
260        .and_then(Value::as_bool)
261        .unwrap_or(false)
262}
263
264/// Whether an MCP error result specifically signals a not-yet-ready index stage.
265///
266/// Why: on a freshly-indexed large repo the semantic (Stage 2) and KG (Stage 3)
267/// lanes can stay building for many minutes while the lexical lane is already
268/// serving. That transient warm-up window is recoverable via a lexical retry,
269/// unlike a genuinely missing index or a dead daemon — so it must be told apart
270/// from other in-band errors (issue #2783).
271/// What: `true` when trusty-search's structured `_meta.error_code` is
272/// `STAGE_NOT_READY` — the machine-readable contract from issue #138. (The
273/// human-readable text never carries the literal code, so `_meta` is the only
274/// reliable signal.)
275/// Test: `tests::is_stage_not_ready_detects_meta_code`.
276fn is_stage_not_ready(result: &Value) -> bool {
277    result
278        .get("_meta")
279        .and_then(|m| m.get("error_code"))
280        .and_then(Value::as_str)
281        == Some("STAGE_NOT_READY")
282}
283
284/// Whether a not-ready lane error should be retried on the lexical lane.
285///
286/// Why: only the semantic/symbol lanes gate on a warm-up stage; the `grep` lane
287/// is itself lexical, so a `grep` error is never a stage-not-ready condition to
288/// re-route. Isolating the decision keeps `execute` linear and unit-testable
289/// without a live daemon (issue #2783).
290/// What: `true` when the lane errored with STAGE_NOT_READY and `mode` is not
291/// already `grep`.
292/// Test: `tests::should_lexical_fallback_only_for_stage_not_ready`.
293fn should_lexical_fallback(mode: &str, result: &Value) -> bool {
294    mode != "grep" && is_stage_not_ready(result)
295}
296
297/// Build the `search_lexical` MCP arguments for a stage-not-ready retry.
298///
299/// Why: the lexical lane is always available on any indexed project, so it is
300/// the safe degraded path while embeddings finish building (issue #2783).
301/// What: mirrors trusty-search's `search_lexical` schema (`index_id`, `query`,
302/// `top_k`).
303/// Test: `tests::lexical_params_matches_search_lexical_schema`.
304fn lexical_params(index_id: &str, query: &str, top_k: usize) -> Value {
305    json!({ "index_id": index_id, "query": query, "top_k": top_k })
306}
307
308/// Retry a not-ready semantic/symbol query on the lexical lane.
309///
310/// Why: rather than returning empty and pushing the model back to ad-hoc grep
311/// (which a daily-driver probe showed derails discovery onto lookalike
312/// functions), transparently serve the always-available lexical results during
313/// the embedding warm-up window (issue #2783).
314/// What: calls `search_lexical`; returns the result text on success, or `None`
315/// when the call fails or itself errors (so the caller falls through to the
316/// grep/glob hint).
317/// Test: exercised end-to-end where a live daemon is available; the decision and
318/// argument shaping are covered by `should_lexical_fallback_*` /
319/// `lexical_params_*`.
320async fn lexical_fallback(
321    client: &mut StdioMcpClient,
322    index_id: &str,
323    query: &str,
324    top_k: usize,
325) -> Option<String> {
326    let result = client
327        .call_tool("search_lexical", lexical_params(index_id, query, top_k))
328        .await
329        .ok()?;
330    if is_mcp_error(&result) {
331        return None;
332    }
333    mcp_text(&result)
334}
335
336/// Build the MCP arguments for `mode`, returning the tool name + params.
337///
338/// Why: keeps `execute` linear — each mode maps to one trusty-search lane with
339/// its own argument shape (`grep` takes `pattern`/`max_results` and an optional
340/// `index_id`; the semantic/KG lanes take `index_id`/`query`/`top_k`).
341/// What: returns `Err` with a fail-open message when a semantic/KG lane is
342/// requested but no index covers the project.
343/// Test: `tests::execute_fail_open_when_binary_absent` (mode routing is covered
344/// end-to-end where a live daemon is available).
345fn build_call(
346    mode: &str,
347    query: &str,
348    top_k: usize,
349    index_id: Option<&str>,
350) -> Result<(&'static str, Value), String> {
351    match mode {
352        "grep" => {
353            let mut params = json!({ "pattern": query, "max_results": top_k });
354            if let Some(id) = index_id {
355                params["index_id"] = json!(id);
356            }
357            Ok(("grep", params))
358        }
359        "symbol" => {
360            let id = index_id.ok_or_else(|| {
361                format!("no trusty-search index covers this project. {FALLBACK_HINT}")
362            })?;
363            Ok((
364                "search_kg",
365                json!({ "index_id": id, "query": query, "top_k": top_k }),
366            ))
367        }
368        // Default and "semantic".
369        _ => {
370            let id = index_id.ok_or_else(|| {
371                format!("no trusty-search index covers this project. {FALLBACK_HINT}")
372            })?;
373            Ok((
374                "search_semantic",
375                json!({ "index_id": id, "query": query, "top_k": top_k }),
376            ))
377        }
378    }
379}
380
381#[async_trait]
382impl ToolExecutor for TrustySearchTool {
383    fn name(&self) -> &str {
384        SEARCH_CODE_TOOL_NAME
385    }
386
387    /// JSON schema for `search_code`.
388    ///
389    /// Why: the description is a first-class LLM prompt — it tells the model to
390    /// prefer this tool for conceptual discovery and steers each `mode` to the
391    /// right lane, reusing trusty-search's own lane wording.
392    /// Test: `tests::schema_advertises_mode_and_query`.
393    fn schema(&self) -> Value {
394        json!({
395            "type": "function",
396            "function": {
397                "name": SEARCH_CODE_TOOL_NAME,
398                "description": "PRIMARY code-discovery tool, backed by trusty-search's semantic + call-graph index. Use it for CONCEPTUAL queries where you don't already know the exact text: \"where is X\", \"how does Y work\", \"find the code that does <behaviour>\", \"what calls Z\". For exact symbol names, literal strings, or filename/path globs you already know, prefer the local `grep`/`glob` tools. If this tool reports trusty-search is unavailable, silently fall back to `grep`/`glob` — do not retry.",
399                "parameters": {
400                    "type": "object",
401                    "properties": {
402                        "query": {
403                            "type": "string",
404                            "description": "For semantic: a natural-language description of the behaviour/concept. For symbol: a function or type name to expand its callers/callees. For grep: a regex or literal pattern."
405                        },
406                        "mode": {
407                            "type": "string",
408                            "enum": ["semantic", "symbol", "grep"],
409                            "default": "semantic",
410                            "description": "semantic (default): find code by meaning. symbol: explore what calls / is called by a known symbol (call graph). grep: regex/literal search over indexed files."
411                        },
412                        "top_k": {
413                            "type": "integer",
414                            "description": "Maximum results (default 10, max 25)."
415                        }
416                    },
417                    "required": ["query"],
418                    "additionalProperties": false
419                }
420            }
421        })
422    }
423
424    /// Execute a discovery query, fail-open on any unavailability.
425    ///
426    /// Why: an explicit model tool call must never derail the agent loop — a
427    /// missing/unready trusty-search surfaces as a SUCCESSFUL "use grep/glob"
428    /// result, not a tool error the model might retry-loop on.
429    /// Test: `tests::execute_fail_open_when_binary_absent`,
430    /// `tests::execute_rejects_malformed_args_recoverably`.
431    async fn execute(&self, args: Value) -> ToolResult {
432        let parsed: SearchArgs = match serde_json::from_value(args) {
433            Ok(p) => p,
434            Err(e) => {
435                return ToolResult::err(format!(
436                    "search_code arguments did not match the expected shape ({e}). \
437                     'query' (string) is required."
438                ));
439            }
440        };
441        let top_k = parsed.top_k.unwrap_or(DEFAULT_TOP_K).clamp(1, MAX_TOP_K);
442        let mode = parsed.mode.as_deref().unwrap_or("semantic");
443
444        let Some(session) = self.session().await else {
445            return ToolResult::ok(FALLBACK_HINT.to_string());
446        };
447
448        let (tool, params) =
449            match build_call(mode, &parsed.query, top_k, session.index_id.as_deref()) {
450                Ok(call) => call,
451                Err(msg) => return ToolResult::ok(msg),
452            };
453
454        let mut client = session.client.lock().await;
455        let result = match client.call_tool(tool, params).await {
456            Ok(v) => v,
457            Err(e) => {
458                warn!(tool, error = %e, "search_code: trusty-search call failed (fail-open)");
459                return ToolResult::ok(format!("trusty-search call failed. {FALLBACK_HINT}"));
460            }
461        };
462
463        if is_mcp_error(&result) {
464            let detail = mcp_text(&result).unwrap_or_default();
465            // Warm-up window: the semantic/KG stage isn't built yet, but the
466            // lexical lane is always available. Retry transparently and serve
467            // the (degraded) lexical hits rather than empty — so discovery still
468            // works while embeddings finish building (issue #2783).
469            if should_lexical_fallback(mode, &result)
470                && let Some(id) = session.index_id.as_deref()
471                && let Some(text) = lexical_fallback(&mut client, id, &parsed.query, top_k).await
472            {
473                let lane_label = if mode == "symbol" {
474                    "symbol graph"
475                } else {
476                    "semantic"
477                };
478                return ToolResult::ok(format!(
479                    "trusty-search's {lane_label} index is still building; \
480                     showing lexical (exact-match) results instead:\n{text}"
481                ));
482            }
483            warn!(
484                tool,
485                detail, "search_code: trusty-search returned an error (fail-open)"
486            );
487            return ToolResult::ok(format!(
488                "trusty-search could not serve this query (its index may still be building). \
489                 {FALLBACK_HINT}"
490            ));
491        }
492
493        match mcp_text(&result) {
494            Some(text) => ToolResult::ok(format!("trusty-search ({mode}) results:\n{text}")),
495            None => ToolResult::ok(format!(
496                "trusty-search returned no results. {FALLBACK_HINT}"
497            )),
498        }
499    }
500}
501
502#[cfg(test)]
503#[path = "trusty_search_tests.rs"]
504mod tests;