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//! `tests::parse_search_hits_reads_each_lane_shape` (DOC-39 Slice B).
37
38use std::path::{Path, PathBuf};
39
40use async_trait::async_trait;
41use serde::Deserialize;
42use serde_json::{Value, json};
43use tokio::sync::{Mutex, OnceCell};
44use tracing::warn;
45use trusty_common::stdio_mcp_client::StdioMcpClient;
46
47use crate::events::SearchHit;
48use crate::tools::telemetry::{SearchTelemetry, ToolTelemetry};
49use crate::tools::traits::{ToolExecutor, ToolResult};
50
51/// The tool's registered/advertised name.
52pub const SEARCH_CODE_TOOL_NAME: &str = "search_code";
53
54/// Binary spawned in MCP stdio mode (`trusty-search serve`).
55const SEARCH_BINARY: &str = "trusty-search";
56
57/// `clientInfo.name` advertised during the MCP handshake.
58const CLIENT_NAME: &str = "trusty-code";
59
60/// Default `top_k` when the model omits it.
61const DEFAULT_TOP_K: usize = 10;
62
63/// Hard cap on `top_k` regardless of what the model requests.
64const MAX_TOP_K: usize = 25;
65
66/// The fail-open message steering the model back to the local literal tools.
67const FALLBACK_HINT: &str =
68    "trusty-search is unavailable; use the local `grep` and `glob` tools for this query instead.";
69
70/// Parsed `search_code` tool-call arguments.
71#[derive(Debug, Deserialize)]
72struct SearchArgs {
73    query: String,
74    #[serde(default)]
75    mode: Option<String>,
76    #[serde(default)]
77    top_k: Option<usize>,
78}
79
80/// A live trusty-search MCP session plus the resolved project index.
81///
82/// Why: MCP requests are not concurrency-safe (one in-flight request per stdio
83/// pair), so the client sits behind an async `Mutex`. `index_id` is resolved
84/// once at spawn from `list_indexes` because the semantic/KG lanes require it.
85/// What: `index_id` is `None` when no registered index covers the project root
86/// — the search lanes then fail open rather than guess a wrong index.
87/// Test: exercised via `execute_*` and `pick_index_*` in `tests`.
88struct SearchSession {
89    client: Mutex<StdioMcpClient>,
90    index_id: Option<String>,
91}
92
93/// `ToolExecutor` for the `search_code` discovery tool (PR A).
94///
95/// Why: gives the engineer a semantic/call-graph discovery path backed by
96/// trusty-search, scoped to the delegating run's project root.
97/// What: holds the project root (for index resolution + scoping) and lazily
98/// initialises one [`SearchSession`] on first use, caching the (possibly
99/// absent) session in a `OnceCell` so a missing/unreachable daemon is probed at
100/// most once per tool instance.
101/// Test: `tests::execute_fail_open_when_binary_absent`.
102pub struct TrustySearchTool {
103    project: PathBuf,
104    binary: String,
105    session: OnceCell<Option<SearchSession>>,
106}
107
108impl TrustySearchTool {
109    /// Construct a tool scoped to `project`, spawning the real `trusty-search`.
110    ///
111    /// Why: the engineer's registry builds one per delegation, scoped to the
112    /// project working tree.
113    /// What: defers all process spawning to first `execute` — construction is
114    /// cheap and side-effect-free.
115    /// Test: `tests::schema_advertises_mode_and_query`.
116    pub fn new(project: impl Into<PathBuf>) -> Self {
117        Self {
118            project: project.into(),
119            binary: SEARCH_BINARY.to_string(),
120            session: OnceCell::new(),
121        }
122    }
123
124    /// Override the spawned binary name (tests point this at a name that is
125    /// guaranteed absent to exercise the fail-open path deterministically).
126    ///
127    /// Why: the daemon-absent path must be unit-testable without depending on
128    /// whether `trusty-search` happens to be on the dev machine's PATH.
129    /// What: replaces the binary the lazy spawn invokes.
130    /// Test: `tests::execute_fail_open_when_binary_absent`.
131    #[cfg(test)]
132    pub fn with_binary(mut self, binary: impl Into<String>) -> Self {
133        self.binary = binary.into();
134        self
135    }
136
137    /// Lazily spawn + handshake + resolve the index, caching the result.
138    ///
139    /// Why: probing a missing/broken daemon on every call would add per-turn
140    /// latency; caching the `Option` probes at most once.
141    /// What: returns `&None` when spawn or handshake fails (fail-open).
142    /// Test: `tests::execute_fail_open_when_binary_absent`.
143    async fn session(&self) -> &Option<SearchSession> {
144        self.session
145            .get_or_init(|| spawn_session(&self.binary, &self.project))
146            .await
147    }
148}
149
150/// Spawn `trusty-search serve`, run the handshake, and resolve the index id.
151///
152/// Why: isolates the fallible startup so `session` stays a thin cache and the
153/// whole flow degrades to `None` on the first failure.
154/// What: returns `None` if the binary is absent, the handshake fails, or the
155/// process cannot start; otherwise a [`SearchSession`] whose `index_id` may
156/// still be `None` when no index covers the project.
157/// Test: covered opportunistically — a missing binary yields `None`, asserted
158/// via `tests::execute_fail_open_when_binary_absent`.
159async fn spawn_session(binary: &str, project: &Path) -> Option<SearchSession> {
160    let mut client = match StdioMcpClient::spawn(binary, &["serve"], CLIENT_NAME).await {
161        Ok(c) => c,
162        Err(e) => {
163            warn!(error = %e, "search_code: trusty-search spawn failed (fail-open)");
164            return None;
165        }
166    };
167    if let Err(e) = client.initialize().await {
168        warn!(error = %e, "search_code: trusty-search handshake failed (fail-open)");
169        return None;
170    }
171    let index_id = resolve_index_id(&mut client, project).await;
172    Some(SearchSession {
173        client: Mutex::new(client),
174        index_id,
175    })
176}
177
178/// Resolve the project's index id from `list_indexes`.
179///
180/// Why: the semantic/KG lanes require an `index_id`; deriving it from the
181/// project root avoids making the model call `list_indexes` and guess.
182/// What: calls the `list_indexes` MCP tool, parses the `{ "indexes": [...] }`
183/// detail payload, and matches the project root against each index `root_path`
184/// via [`pick_index`]. Returns `None` on any RPC/parse failure or no match.
185/// Test: `tests::pick_index_prefers_exact_match`.
186async fn resolve_index_id(client: &mut StdioMcpClient, project: &Path) -> Option<String> {
187    let result = client.call_tool("list_indexes", json!({})).await.ok()?;
188    let text = mcp_text(&result)?;
189    let body: Value = serde_json::from_str(&text).ok()?;
190    let indexes = body.get("indexes")?.as_array()?;
191    pick_index(indexes, project)
192}
193
194/// Pick the index whose `root_path` best covers `project`.
195///
196/// Why: a worktree/subdirectory of a registered repo should resolve to that
197/// repo's index even when the paths are not byte-identical.
198/// What: prefers an exact canonical match; otherwise the registered index whose
199/// canonical `root_path` is the longest ancestor of `project`. `None` when no
200/// index covers the project.
201/// Test: `tests::pick_index_prefers_exact_match`,
202/// `tests::pick_index_falls_back_to_longest_ancestor`.
203fn pick_index(indexes: &[Value], project: &Path) -> Option<String> {
204    let target = canonicalize_best_effort(project);
205    let mut best: Option<(usize, String)> = None;
206    for entry in indexes {
207        let Some(id) = entry.get("id").and_then(Value::as_str) else {
208            continue;
209        };
210        let Some(root) = entry.get("root_path").and_then(Value::as_str) else {
211            continue;
212        };
213        let root = canonicalize_best_effort(Path::new(root));
214        if root == target {
215            return Some(id.to_string());
216        }
217        if target.starts_with(&root) {
218            let depth = root.components().count();
219            if best.as_ref().is_none_or(|(d, _)| depth > *d) {
220                best = Some((depth, id.to_string()));
221            }
222        }
223    }
224    best.map(|(_, id)| id)
225}
226
227/// Canonicalise `p`, falling back to the path as given when it does not exist.
228///
229/// Why: index roots and the project path may be symlinked (worktrees under
230/// `$HOME`); canonicalising both makes ancestor comparison robust.
231/// What: `std::fs::canonicalize` with a lossless fallback.
232/// Test: exercised via `pick_index_*`.
233fn canonicalize_best_effort(p: &Path) -> PathBuf {
234    std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf())
235}
236
237/// Extract the first text frame from an MCP `tools/call` result.
238///
239/// Why: trusty-search wraps every payload as `content[0].text` (a JSON string).
240/// What: returns that string, or `None` when the frame is missing.
241/// Test: `tests::mcp_text_extracts_content`.
242fn mcp_text(result: &Value) -> Option<String> {
243    result
244        .get("content")
245        .and_then(|c| c.as_array())
246        .and_then(|items| items.first())
247        .and_then(|item| item.get("text"))
248        .and_then(|t| t.as_str())
249        .map(str::to_string)
250}
251
252/// Whether an MCP result carries the in-band `isError` flag (e.g.
253/// `STAGE_NOT_READY` when the semantic/KG lane is not yet built).
254///
255/// Why: trusty-search reports stage-not-ready as `isError: true` content rather
256/// than a JSON-RPC error, so `call_tool` returns `Ok`; we must inspect the flag
257/// to fail open.
258/// What: `true` when `result.isError == true`.
259/// Test: `tests::is_mcp_error_detects_error_flag`.
260fn is_mcp_error(result: &Value) -> bool {
261    result
262        .get("isError")
263        .and_then(Value::as_bool)
264        .unwrap_or(false)
265}
266
267/// Whether an MCP error result specifically signals a not-yet-ready index stage.
268///
269/// Why: on a freshly-indexed large repo the semantic (Stage 2) and KG (Stage 3)
270/// lanes can stay building for many minutes while the lexical lane is already
271/// serving. That transient warm-up window is recoverable via a lexical retry,
272/// unlike a genuinely missing index or a dead daemon — so it must be told apart
273/// from other in-band errors (issue #2783).
274/// What: `true` when trusty-search's structured `_meta.error_code` is
275/// `STAGE_NOT_READY` — the machine-readable contract from issue #138. (The
276/// human-readable text never carries the literal code, so `_meta` is the only
277/// reliable signal.)
278/// Test: `tests::is_stage_not_ready_detects_meta_code`.
279fn is_stage_not_ready(result: &Value) -> bool {
280    result
281        .get("_meta")
282        .and_then(|m| m.get("error_code"))
283        .and_then(Value::as_str)
284        == Some("STAGE_NOT_READY")
285}
286
287/// Whether a not-ready lane error should be retried on the lexical lane.
288///
289/// Why: only the semantic/symbol lanes gate on a warm-up stage; the `grep` lane
290/// is itself lexical, so a `grep` error is never a stage-not-ready condition to
291/// re-route. Isolating the decision keeps `execute` linear and unit-testable
292/// without a live daemon (issue #2783).
293/// What: `true` when the lane errored with STAGE_NOT_READY and `mode` is not
294/// already `grep`.
295/// Test: `tests::should_lexical_fallback_only_for_stage_not_ready`.
296fn should_lexical_fallback(mode: &str, result: &Value) -> bool {
297    mode != "grep" && is_stage_not_ready(result)
298}
299
300/// Build the `search_lexical` MCP arguments for a stage-not-ready retry.
301///
302/// Why: the lexical lane is always available on any indexed project, so it is
303/// the safe degraded path while embeddings finish building (issue #2783).
304/// What: mirrors trusty-search's `search_lexical` schema (`index_id`, `query`,
305/// `top_k`).
306/// Test: `tests::lexical_params_matches_search_lexical_schema`.
307fn lexical_params(index_id: &str, query: &str, top_k: usize) -> Value {
308    json!({ "index_id": index_id, "query": query, "top_k": top_k })
309}
310
311/// Retry a not-ready semantic/symbol query on the lexical lane.
312///
313/// Why: rather than returning empty and pushing the model back to ad-hoc grep
314/// (which a daily-driver probe showed derails discovery onto lookalike
315/// functions), transparently serve the always-available lexical results during
316/// the embedding warm-up window (issue #2783).
317/// What: calls `search_lexical`; returns the result text on success, or `None`
318/// when the call fails or itself errors (so the caller falls through to the
319/// grep/glob hint).
320/// Test: exercised end-to-end where a live daemon is available; the decision and
321/// argument shaping are covered by `should_lexical_fallback_*` /
322/// `lexical_params_*`.
323async fn lexical_fallback(
324    client: &mut StdioMcpClient,
325    index_id: &str,
326    query: &str,
327    top_k: usize,
328) -> Option<String> {
329    let result = client
330        .call_tool("search_lexical", lexical_params(index_id, query, top_k))
331        .await
332        .ok()?;
333    if is_mcp_error(&result) {
334        return None;
335    }
336    mcp_text(&result)
337}
338
339/// The trusty-search lane that ACTUALLY served a query (UI Phase 1).
340///
341/// Why: the mode the model asks for and the lane that answers are not the
342/// same thing — a `semantic`/`symbol` query against a still-building index
343/// transparently retries on the lexical lane (#2783). Reporting the
344/// requested mode would tell the UI a comfortable lie about how a change was
345/// discovered; this reports what happened.
346/// What: `label()` is the stable wire string carried by
347/// `Event::SearchPerformed.lane`. `Lexical` is only ever reached via the
348/// stage-not-ready retry — it is not a mode the model can request.
349/// Test: `tests::lane_labels_are_stable`,
350/// `tests::resolved_lane_reports_lexical_when_the_retry_served_it`.
351#[derive(Debug, Clone, Copy, PartialEq, Eq)]
352enum SearchLane {
353    /// `search_semantic` — embedding similarity.
354    Semantic,
355    /// `search_kg` — call-graph expansion around a symbol.
356    Symbol,
357    /// `grep` — regex/literal over indexed files.
358    Grep,
359    /// `search_lexical` — the degraded lane served during index warm-up.
360    Lexical,
361}
362
363impl SearchLane {
364    /// Resolve the lane a requested `mode` routes to (before any retry).
365    ///
366    /// Why: `build_call`'s mode matching and the telemetry lane must never
367    /// drift apart; both derive from this one mapping.
368    /// What: mirrors `build_call` exactly, including its "anything unknown is
369    /// semantic" default.
370    /// Test: `tests::lane_from_mode_matches_build_call_routing`.
371    fn from_mode(mode: &str) -> Self {
372        match mode {
373            "grep" => SearchLane::Grep,
374            "symbol" => SearchLane::Symbol,
375            _ => SearchLane::Semantic,
376        }
377    }
378
379    /// Resolve the lane that ACTUALLY served a query.
380    ///
381    /// Why: the one place the "which lane really answered?" question is
382    /// decided, so the answer the telemetry reports cannot drift from what
383    /// `execute` did — and so the lexical-retry case is unit-testable without
384    /// a live trusty-search daemon and a half-built index.
385    /// What: a stage-not-ready retry means the LEXICAL lane served the
386    /// results, whatever the model asked for; otherwise the requested mode's
387    /// lane did.
388    /// Test: `tests::resolved_lane_reports_lexical_when_the_retry_served_it`.
389    fn resolved(mode: &str, lexical_fallback_used: bool) -> Self {
390        if lexical_fallback_used {
391            SearchLane::Lexical
392        } else {
393            SearchLane::from_mode(mode)
394        }
395    }
396
397    /// The stable wire label for this lane.
398    fn label(self) -> &'static str {
399        match self {
400            SearchLane::Semantic => "semantic",
401            SearchLane::Symbol => "symbol",
402            SearchLane::Grep => "grep",
403            SearchLane::Lexical => "lexical",
404        }
405    }
406}
407
408/// Parse the hit count AND each hit's path/score from a trusty-search result
409/// payload, in one JSON parse (UI Phase 1; `hits` added DOC-39 Slice B).
410///
411/// Why: the UI renders "N hits" beside a search (`hit_count`) and the
412/// search-audit surface needs to know WHICH files those hits were
413/// (`hits`) — both are only recoverable from the same parsed array, so
414/// this walks it once for both rather than re-parsing `text` a second time.
415/// What: every trusty-search lane wraps its payload as a JSON object with an
416/// array under `results`, `hits`, or `matches` — the three keys observed
417/// across the semantic/KG/grep/lexical lanes. Returns `(None, vec![])` when
418/// `text` is not JSON or carries no recognisable array, so an uncountable
419/// shape is reported honestly as "unknown" rather than as a misleading `0`.
420/// Each array item's path is read from `path` (trusty-search's portable
421/// root-relative `CodeChunk` field), falling back to `file` (its absolute
422/// path, and the ONLY path field `grep`'s `GrepMatch` shape carries); an item
423/// with neither is skipped — a hit the UI cannot point at is not worth
424/// reporting. Score is read from `score`, defaulting to `0.0` for shapes
425/// (e.g. `grep`) that carry none at all.
426/// Test: `tests::parse_search_hits_reads_each_lane_shape`,
427/// `tests::parse_search_hits_is_none_for_unrecognised_payloads`,
428/// `tests::parse_search_hits_falls_back_to_file_and_defaults_missing_score`,
429/// `tests::parse_search_hits_skips_items_with_no_path_or_file`.
430fn parse_search_hits(text: &str) -> (Option<usize>, Vec<SearchHit>) {
431    let Ok(body) = serde_json::from_str::<Value>(text) else {
432        return (None, Vec::new());
433    };
434    let Some(items) = ["results", "hits", "matches"]
435        .iter()
436        .find_map(|key| body.get(*key).and_then(Value::as_array))
437    else {
438        return (None, Vec::new());
439    };
440    let hits = items
441        .iter()
442        .filter_map(|item| {
443            let path = item
444                .get("path")
445                .and_then(Value::as_str)
446                .or_else(|| item.get("file").and_then(Value::as_str))?;
447            let score = item.get("score").and_then(Value::as_f64).unwrap_or(0.0);
448            Some(SearchHit {
449                path: path.to_string(),
450                score,
451            })
452        })
453        .collect();
454    (Some(items.len()), hits)
455}
456
457/// Build the MCP arguments for `mode`, returning the tool name + params.
458///
459/// Why: keeps `execute` linear — each mode maps to one trusty-search lane with
460/// its own argument shape (`grep` takes `pattern`/`max_results` and an optional
461/// `index_id`; the semantic/KG lanes take `index_id`/`query`/`top_k`).
462/// What: returns `Err` with a fail-open message when a semantic/KG lane is
463/// requested but no index covers the project.
464/// Test: `tests::execute_fail_open_when_binary_absent` (mode routing is covered
465/// end-to-end where a live daemon is available).
466fn build_call(
467    mode: &str,
468    query: &str,
469    top_k: usize,
470    index_id: Option<&str>,
471) -> Result<(&'static str, Value), String> {
472    match mode {
473        "grep" => {
474            let mut params = json!({ "pattern": query, "max_results": top_k });
475            if let Some(id) = index_id {
476                params["index_id"] = json!(id);
477            }
478            Ok(("grep", params))
479        }
480        "symbol" => {
481            let id = index_id.ok_or_else(|| {
482                format!("no trusty-search index covers this project. {FALLBACK_HINT}")
483            })?;
484            Ok((
485                "search_kg",
486                json!({ "index_id": id, "query": query, "top_k": top_k }),
487            ))
488        }
489        // Default and "semantic".
490        _ => {
491            let id = index_id.ok_or_else(|| {
492                format!("no trusty-search index covers this project. {FALLBACK_HINT}")
493            })?;
494            Ok((
495                "search_semantic",
496                json!({ "index_id": id, "query": query, "top_k": top_k }),
497            ))
498        }
499    }
500}
501
502#[async_trait]
503impl ToolExecutor for TrustySearchTool {
504    fn name(&self) -> &str {
505        SEARCH_CODE_TOOL_NAME
506    }
507
508    /// JSON schema for `search_code`.
509    ///
510    /// Why: the description is a first-class LLM prompt — it tells the model to
511    /// prefer this tool for conceptual discovery and steers each `mode` to the
512    /// right lane, reusing trusty-search's own lane wording.
513    /// Test: `tests::schema_advertises_mode_and_query`.
514    fn schema(&self) -> Value {
515        json!({
516            "type": "function",
517            "function": {
518                "name": SEARCH_CODE_TOOL_NAME,
519                "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.",
520                "parameters": {
521                    "type": "object",
522                    "properties": {
523                        "query": {
524                            "type": "string",
525                            "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."
526                        },
527                        "mode": {
528                            "type": "string",
529                            "enum": ["semantic", "symbol", "grep"],
530                            "default": "semantic",
531                            "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."
532                        },
533                        "top_k": {
534                            "type": "integer",
535                            "description": "Maximum results (default 10, max 25)."
536                        }
537                    },
538                    "required": ["query"],
539                    "additionalProperties": false
540                }
541            }
542        })
543    }
544
545    /// Execute a discovery query, fail-open on any unavailability.
546    ///
547    /// Why: an explicit model tool call must never derail the agent loop — a
548    /// missing/unready trusty-search surfaces as a SUCCESSFUL "use grep/glob"
549    /// result, not a tool error the model might retry-loop on. (#2857) The
550    /// #2783 lexical-fallback branch is a silent degradation the model acts
551    /// on (it receives narrower exact-match results without knowing the
552    /// semantic/symbol lane was skipped) — it now emits `tracing::info!`
553    /// naming the mode and lane, so an operator can tell from stderr that a
554    /// run's discovery quality was degraded, matching this method's other
555    /// two `tracing::warn!` sites for a hard call failure / in-band error.
556    /// (UI Phase 1) Every path that actually reached a lane attaches a
557    /// [`SearchTelemetry`] carrying the REAL routed lane, the hit count, and
558    /// the whole call's latency — see [`SearchLane`]. The fail-open paths
559    /// (no daemon, no index, lane error with no usable retry) attach none:
560    /// they never reached a lane, so there is no search to report; the
561    /// generic tool events still narrate them.
562    /// Test: `tests::execute_fail_open_when_binary_absent`,
563    /// `tests::execute_rejects_malformed_args_recoverably`,
564    /// `tests::resolved_lane_reports_lexical_when_the_retry_served_it`,
565    /// `tests::execute_attaches_telemetry_when_lane_reply_has_no_text`.
566    async fn execute(&self, args: Value) -> ToolResult {
567        let started = std::time::Instant::now();
568        let parsed: SearchArgs = match serde_json::from_value(args) {
569            Ok(p) => p,
570            Err(e) => {
571                return ToolResult::err(format!(
572                    "search_code arguments did not match the expected shape ({e}). \
573                     'query' (string) is required."
574                ));
575            }
576        };
577        let top_k = parsed.top_k.unwrap_or(DEFAULT_TOP_K).clamp(1, MAX_TOP_K);
578        let mode = parsed.mode.as_deref().unwrap_or("semantic");
579
580        // (UI Phase 1) Stamp the telemetry from the lane that ACTUALLY served
581        // the query, measured at the moment of return so `latency_ms` covers
582        // any transparent retry too.
583        let telemetry = |lane: SearchLane, text: &str| {
584            let (hit_count, hits) = parse_search_hits(text);
585            ToolTelemetry::Search(SearchTelemetry {
586                lane: lane.label().to_string(),
587                query: parsed.query.clone(),
588                hit_count,
589                hits,
590                latency_ms: started.elapsed().as_millis() as u64,
591            })
592        };
593
594        let Some(session) = self.session().await else {
595            return ToolResult::ok(FALLBACK_HINT.to_string());
596        };
597
598        let (tool, params) =
599            match build_call(mode, &parsed.query, top_k, session.index_id.as_deref()) {
600                Ok(call) => call,
601                Err(msg) => return ToolResult::ok(msg),
602            };
603
604        let mut client = session.client.lock().await;
605        let result = match client.call_tool(tool, params).await {
606            Ok(v) => v,
607            Err(e) => {
608                warn!(tool, error = %e, "search_code: trusty-search call failed (fail-open)");
609                return ToolResult::ok(format!("trusty-search call failed. {FALLBACK_HINT}"));
610            }
611        };
612
613        if is_mcp_error(&result) {
614            let detail = mcp_text(&result).unwrap_or_default();
615            // Warm-up window: the semantic/KG stage isn't built yet, but the
616            // lexical lane is always available. Retry transparently and serve
617            // the (degraded) lexical hits rather than empty — so discovery still
618            // works while embeddings finish building (issue #2783).
619            if should_lexical_fallback(mode, &result)
620                && let Some(id) = session.index_id.as_deref()
621                && let Some(text) = lexical_fallback(&mut client, id, &parsed.query, top_k).await
622            {
623                let lane_label = if mode == "symbol" {
624                    "symbol graph"
625                } else {
626                    "semantic"
627                };
628                tracing::info!(
629                    mode,
630                    lane_label,
631                    "search_code: {lane_label} index not ready (STAGE_NOT_READY, #2783) — \
632                     serving degraded lexical results instead"
633                );
634                // The requested lane did NOT serve this — the lexical lane
635                // did. Report that, not the mode the model asked for.
636                return ToolResult::ok(format!(
637                    "trusty-search's {lane_label} index is still building; \
638                     showing lexical (exact-match) results instead:\n{text}"
639                ))
640                .with_telemetry(telemetry(SearchLane::resolved(mode, true), &text));
641            }
642            warn!(
643                tool,
644                detail, "search_code: trusty-search returned an error (fail-open)"
645            );
646            return ToolResult::ok(format!(
647                "trusty-search could not serve this query (its index may still be building). \
648                 {FALLBACK_HINT}"
649            ));
650        }
651
652        match mcp_text(&result) {
653            Some(text) => ToolResult::ok(format!("trusty-search ({mode}) results:\n{text}"))
654                .with_telemetry(telemetry(SearchLane::resolved(mode, false), &text)),
655            None => ToolResult::ok(format!(
656                "trusty-search returned no results. {FALLBACK_HINT}"
657            ))
658            .with_telemetry(telemetry(SearchLane::resolved(mode, false), "")),
659        }
660    }
661}
662
663#[cfg(test)]
664#[path = "trusty_search_tests.rs"]
665mod tests;