Skip to main content

vtcode_core/tools/
search_runtime.rs

1use std::path::{Path, PathBuf};
2use std::sync::{Mutex, OnceLock};
3
4use tracing::warn;
5
6use crate::command_safety::shell_parser::prewarm_bash_parser;
7use crate::utils::common::detect_workspace_languages;
8
9/// The readiness of a search backend.
10///
11/// Search is implemented natively, so there is nothing to install and nothing
12/// to probe: the backend is ready whenever the runtime is available. The
13/// variant set is kept so the status surface stays uniform for callers that
14/// report search health.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum SearchToolReadiness {
17    /// The backend is available.
18    Ready,
19    /// The backend is not available.
20    Missing,
21    /// The backend failed to initialise.
22    Error,
23}
24
25impl SearchToolReadiness {
26    #[must_use]
27    pub fn is_ready(self) -> bool {
28        matches!(self, Self::Ready)
29    }
30
31    #[must_use]
32    pub fn label(self) -> &'static str {
33        match self {
34            Self::Ready => "ready",
35            Self::Missing => "missing",
36            Self::Error => "error",
37        }
38    }
39}
40
41/// The status of the search backends.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub struct SearchToolBundleStatus {
44    /// The native content-search backend.
45    pub content_search: SearchToolReadiness,
46    /// The native declaration-search backend.
47    pub declaration_search: SearchToolReadiness,
48}
49
50impl SearchToolBundleStatus {
51    #[must_use]
52    pub fn all_ready(self) -> bool {
53        self.content_search.is_ready() && self.declaration_search.is_ready()
54    }
55
56    #[must_use]
57    pub fn all_unavailable(self) -> bool {
58        !self.content_search.is_ready() && !self.declaration_search.is_ready()
59    }
60
61    #[must_use]
62    pub fn has_errors(self) -> bool {
63        matches!(self.content_search, SearchToolReadiness::Error)
64            || matches!(self.declaration_search, SearchToolReadiness::Error)
65    }
66
67    #[must_use]
68    pub fn header_summary(self) -> String {
69        if self.all_ready() {
70            return "Search: native".to_string();
71        }
72        format!(
73            "Search: content {} \u{00b7} declarations {}",
74            self.content_search.label(),
75            self.declaration_search.label()
76        )
77    }
78}
79
80/// A snapshot of the search runtime for one workspace.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub(crate) struct SearchRuntimeSnapshot {
83    /// The languages present in the workspace.
84    pub(crate) workspace_languages: Vec<String>,
85    /// The status of the search backends.
86    pub(crate) search_tools: SearchToolBundleStatus,
87    /// Whether the bash safety parser is available.
88    pub(crate) bash_tree_sitter_ready: bool,
89}
90
91/// Bounded per-workspace search-runtime snapshot cache. Snapshots are cheap to
92/// recompute relative to the value of caching (detect/prewarm only happens on
93/// miss), and keying by workspace path means an unbounded map would leak one
94/// entry per distinct workspace ever seen in a long-lived process. A small LRU
95/// cap bounds memory while keeping the hot workspace cached.
96const SEARCH_RUNTIME_CACHE_CAP: usize = 16;
97
98static SEARCH_RUNTIME_CACHE: OnceLock<Mutex<lru::LruCache<PathBuf, SearchRuntimeSnapshot>>> = OnceLock::new();
99
100pub(crate) fn snapshot_for_workspace(workspace_root: &Path) -> SearchRuntimeSnapshot {
101    let workspace_root = workspace_root.to_path_buf();
102    let cache = SEARCH_RUNTIME_CACHE.get_or_init(|| {
103        let capacity = std::num::NonZeroUsize::new(SEARCH_RUNTIME_CACHE_CAP)
104            .expect("SEARCH_RUNTIME_CACHE_CAP is a non-zero const");
105        Mutex::new(lru::LruCache::new(capacity))
106    });
107
108    // Check cache first; recover from poison by clearing and returning None to recompute
109    {
110        let mut cache_guard = cache.lock().unwrap_or_else(|poisoned| {
111            warn!("search runtime cache mutex poisoned; recovering");
112            poisoned.into_inner()
113        });
114        if let Some(snapshot) = cache_guard.get(&workspace_root).cloned() {
115            return snapshot;
116        }
117    }
118
119    let workspace_languages = detect_workspace_languages(&workspace_root);
120    // Both search backends are native, so they are ready whenever the runtime
121    // is available. Only the bash safety parser can fail, and it reports its
122    // own readiness separately.
123    let search_tools = SearchToolBundleStatus {
124        content_search: SearchToolReadiness::Ready,
125        declaration_search: SearchToolReadiness::Ready,
126    };
127    let snapshot = SearchRuntimeSnapshot {
128        workspace_languages,
129        search_tools,
130        bash_tree_sitter_ready: prewarm_bash_parser().is_ok(),
131    };
132
133    let mut guard = cache.lock().unwrap_or_else(|poisoned| {
134        warn!("search runtime cache mutex poisoned; recovering");
135        poisoned.into_inner()
136    });
137    guard.get_or_insert(workspace_root, || snapshot.clone()).clone()
138}
139
140pub fn dominant_workspace_language(workspace_root: &Path) -> Option<String> {
141    snapshot_for_workspace(workspace_root).workspace_languages.into_iter().next()
142}
143
144pub fn search_tool_bundle_status(workspace_root: &Path) -> SearchToolBundleStatus {
145    snapshot_for_workspace(workspace_root).search_tools
146}