1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
3
4use serde::{Deserialize, Serialize};
5
6use crate::core::bm25_index::{BM25Index, SearchResult};
7
8const DEFAULT_RRF_K: f64 = 60.0;
10
11pub const DEFAULT_MAX_ROOTS: usize = 16;
13
14pub const MAX_ROOTS_CEILING: usize = 256;
17
18pub const MAX_ROOTS_ENV: &str = "LEAN_CTX_MAX_ROOTS";
21
22fn effective_max_roots(env: Option<&str>, configured: Option<usize>) -> usize {
26 env.and_then(|v| v.trim().parse::<usize>().ok())
27 .or(configured)
28 .unwrap_or(DEFAULT_MAX_ROOTS)
29 .clamp(1, MAX_ROOTS_CEILING)
30}
31
32fn max_roots_from_env(configured: Option<usize>) -> usize {
33 effective_max_roots(std::env::var(MAX_ROOTS_ENV).ok().as_deref(), configured)
34}
35
36#[derive(Debug, Clone)]
38pub struct RepoSearchResult {
39 pub repo_alias: String,
40 pub repo_path: String,
41 pub file_path: String,
42 pub symbol_name: String,
43 pub content: String,
44 pub start_line: usize,
45 pub end_line: usize,
46 pub score: f64,
47}
48
49#[derive(Debug, Clone)]
51pub struct FusedSearchResult {
52 pub repo_alias: String,
53 pub repo_path: String,
54 pub file_path: String,
55 pub symbol_name: String,
56 pub content: String,
57 pub start_line: usize,
58 pub end_line: usize,
59 pub rrf_score: f64,
60}
61
62#[derive(Debug, Clone, Serialize, Deserialize)]
64pub struct RepoRootConfig {
65 pub path: String,
66 #[serde(default)]
67 pub alias: Option<String>,
68}
69
70impl RepoRootConfig {
71 pub fn effective_alias(&self) -> String {
72 self.alias.clone().unwrap_or_else(|| {
73 Path::new(&self.path)
74 .file_name()
75 .and_then(|n| n.to_str())
76 .unwrap_or("unknown")
77 .to_string()
78 })
79 }
80}
81
82#[derive(Debug, Clone, Serialize, Deserialize, Default)]
84pub struct MultiRepoConfig {
85 #[serde(default)]
86 pub repos: Vec<RepoRootConfig>,
87 #[serde(default)]
88 pub rrf_k: Option<f64>,
89 #[serde(default, skip_serializing_if = "Option::is_none")]
91 pub max_roots: Option<usize>,
92}
93
94impl MultiRepoConfig {
95 pub fn load() -> Self {
96 let config_path = config_file_path();
97 if !config_path.exists() {
98 return Self::default();
99 }
100 match std::fs::read_to_string(&config_path) {
101 Ok(content) => toml::from_str(&content).unwrap_or_default(),
102 Err(_) => Self::default(),
103 }
104 }
105
106 pub fn save(&self) -> Result<(), String> {
107 let config_path = config_file_path();
108 if let Some(parent) = config_path.parent() {
109 std::fs::create_dir_all(parent)
110 .map_err(|e| format!("Failed to create config dir: {e}"))?;
111 }
112 let content =
113 toml::to_string_pretty(self).map_err(|e| format!("Failed to serialize config: {e}"))?;
114 let defaults = toml::to_string_pretty(&Self::default())
115 .map_err(|e| format!("Failed to serialize defaults: {e}"))?;
116 crate::config_io::write_toml_preserving_minimal(&config_path, &content, &defaults)
117 .map_err(|e| format!("Failed to write config: {e}"))?;
118 Ok(())
119 }
120}
121
122pub struct ActiveRepoRoot {
124 pub config: RepoRootConfig,
125 pub path: PathBuf,
126 index: Option<BM25Index>,
127}
128
129impl std::fmt::Debug for ActiveRepoRoot {
130 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131 f.debug_struct("ActiveRepoRoot")
132 .field("config", &self.config)
133 .field("path", &self.path)
134 .field("has_index", &self.index.is_some())
135 .finish()
136 }
137}
138
139impl ActiveRepoRoot {
140 fn new(config: RepoRootConfig) -> Result<Self, String> {
141 let path = PathBuf::from(&config.path);
142 if !path.is_dir() {
143 return Err(format!(
144 "Path does not exist or is not a directory: {}",
145 config.path
146 ));
147 }
148 let path = path
149 .canonicalize()
150 .map_err(|e| format!("Cannot canonicalize {}: {e}", config.path))?;
151 Ok(Self {
152 config,
153 path,
154 index: None,
155 })
156 }
157
158 fn ensure_index(&mut self) {
159 if self.index.is_some() {
160 return;
161 }
162 self.index = Some(BM25Index::load_or_build(&self.path));
163 }
164
165 pub fn alias(&self) -> String {
166 self.config.effective_alias()
167 }
168
169 pub fn search(&mut self, query: &str, max_results: usize) -> Vec<RepoSearchResult> {
170 self.ensure_index();
171 let Some(ref index) = self.index else {
172 return Vec::new();
173 };
174
175 let results: Vec<SearchResult> = index.search(query, max_results);
176 let alias = self.alias();
177 let repo_path = self.path.to_string_lossy().to_string();
178
179 results
180 .into_iter()
181 .enumerate()
182 .map(|(rank, sr)| RepoSearchResult {
183 repo_alias: alias.clone(),
184 repo_path: repo_path.clone(),
185 file_path: sr.file_path,
186 symbol_name: sr.symbol_name,
187 content: sr.snippet,
188 start_line: sr.start_line,
189 end_line: sr.end_line,
190 score: 1.0 / (rank as f64 + 1.0),
191 })
192 .collect()
193 }
194}
195
196pub struct MultiRepoManager {
198 roots: Vec<ActiveRepoRoot>,
199 rrf_k: f64,
200 max_roots: usize,
201}
202
203impl MultiRepoManager {
204 pub fn new() -> Self {
205 Self {
206 roots: Vec::new(),
207 rrf_k: DEFAULT_RRF_K,
208 max_roots: max_roots_from_env(None),
209 }
210 }
211
212 pub fn with_rrf_k(mut self, k: f64) -> Self {
213 self.rrf_k = k;
214 self
215 }
216
217 pub fn from_config(config: &MultiRepoConfig) -> Result<Self, String> {
218 let mut manager = Self::new();
219 if let Some(k) = config.rrf_k {
220 manager.rrf_k = k;
221 }
222 manager.max_roots = max_roots_from_env(config.max_roots)
227 .max(config.repos.len())
228 .min(MAX_ROOTS_CEILING);
229 for repo_config in &config.repos {
230 manager.add_root_config(repo_config.clone())?;
231 }
232 Ok(manager)
233 }
234
235 pub fn add_root(&mut self, path: &str, alias: Option<&str>) -> Result<(), String> {
236 if self.roots.len() >= self.max_roots {
237 return Err(self.max_roots_error());
238 }
239 let config = RepoRootConfig {
240 path: path.to_string(),
241 alias: alias.map(String::from),
242 };
243 let root = ActiveRepoRoot::new(config)?;
244 if !authorized(&root.path) {
245 return Err(format!(
246 "{path} is not a root of the launcher-bound Workspace — repo roots cannot widen it"
247 ));
248 }
249 if self.roots.iter().any(|r| r.path == root.path) {
250 return Err(format!("Root already exists: {path}"));
251 }
252 self.roots.push(root);
253 Ok(())
254 }
255
256 fn add_root_config(&mut self, config: RepoRootConfig) -> Result<(), String> {
257 if self.roots.len() >= self.max_roots {
258 return Err(self.max_roots_error());
259 }
260 let root = ActiveRepoRoot::new(config)?;
261 if self.roots.iter().any(|r| r.path == root.path) {
262 return Err(format!(
263 "Root already exists: {}",
264 root.path.to_string_lossy()
265 ));
266 }
267 self.roots.push(root);
268 Ok(())
269 }
270
271 #[must_use]
273 pub fn with_max_roots(mut self, max_roots: usize) -> Self {
274 self.max_roots = max_roots.clamp(1, MAX_ROOTS_CEILING);
275 self
276 }
277
278 pub fn max_roots(&self) -> usize {
280 self.max_roots
281 }
282
283 fn max_roots_error(&self) -> String {
284 let max = self.max_roots;
285 if max >= MAX_ROOTS_CEILING {
286 format!("Maximum number of roots ({max}) reached; this is the hard ceiling")
287 } else {
288 format!(
289 "Maximum number of roots ({max}) reached. Raise it with {MAX_ROOTS_ENV}=<n> \
290 or max_roots = <n> in {} (at most {MAX_ROOTS_CEILING})",
291 config_file_path().display()
292 )
293 }
294 }
295
296 pub fn remove_root(&mut self, path: &str) -> Result<(), String> {
297 let normalized = PathBuf::from(path)
298 .canonicalize()
299 .unwrap_or_else(|_| PathBuf::from(path));
300 let before = self.roots.len();
301 self.roots
302 .retain(|r| r.path != normalized && r.config.path != path);
303 if self.roots.len() == before {
304 return Err(format!("Root not found: {path}"));
305 }
306 Ok(())
307 }
308
309 pub fn list_roots(&self) -> Vec<RootInfo> {
310 self.roots
311 .iter()
312 .filter(|r| authorized(&r.path))
313 .map(|r| RootInfo {
314 path: r.path.to_string_lossy().to_string(),
315 alias: r.alias(),
316 has_index: r.index.is_some(),
317 })
318 .collect()
319 }
320
321 pub fn root_count(&self) -> usize {
322 self.roots.len()
323 }
324
325 pub fn rrf_k(&self) -> f64 {
328 self.rrf_k
329 }
330
331 pub fn is_active(&self) -> bool {
332 self.roots.len() > 1
333 }
334
335 pub fn resolve_root(&self, repo: &str) -> Option<usize> {
337 self.roots.iter().position(|r| {
338 r.alias() == repo || r.config.path == repo || r.path.to_string_lossy() == repo
339 })
340 }
341
342 pub fn search(
344 &mut self,
345 query: &str,
346 max_results: usize,
347 filter_roots: Option<&[String]>,
348 ) -> Vec<FusedSearchResult> {
349 self.search_with(query, max_results, filter_roots, |_, _, search| search())
350 }
351
352 pub fn search_with(
358 &mut self,
359 query: &str,
360 max_results: usize,
361 filter_roots: Option<&[String]>,
362 mut per_root: impl FnMut(
363 &str,
364 &Path,
365 &mut dyn FnMut() -> Vec<RepoSearchResult>,
366 ) -> Vec<RepoSearchResult>,
367 ) -> Vec<FusedSearchResult> {
368 let per_root_max = (max_results * 2).max(20);
369
370 let mut all_results: HashMap<String, FusedSearchResult> = HashMap::new();
371
372 for root in &mut self.roots {
373 if !authorized(&root.path) {
374 continue;
375 }
376 if let Some(filter) = filter_roots {
377 let alias = root.alias();
378 let path = root.path.to_string_lossy().to_string();
379 if !filter.iter().any(|f| f == &alias || f == &path) {
380 continue;
381 }
382 }
383
384 let alias = root.alias();
385 let path = root.path.clone();
386 let results = per_root(&alias, &path, &mut || root.search(query, per_root_max));
387
388 for (rank, result) in results.iter().enumerate() {
389 let rrf_contribution = 1.0 / (self.rrf_k + rank as f64 + 1.0);
390 let key = format!(
391 "{}:{}:{}",
392 result.repo_alias, result.file_path, result.start_line
393 );
394
395 all_results
396 .entry(key)
397 .and_modify(|existing| {
398 existing.rrf_score += rrf_contribution;
399 })
400 .or_insert_with(|| FusedSearchResult {
401 repo_alias: result.repo_alias.clone(),
402 repo_path: result.repo_path.clone(),
403 file_path: result.file_path.clone(),
404 symbol_name: result.symbol_name.clone(),
405 content: result.content.clone(),
406 start_line: result.start_line,
407 end_line: result.end_line,
408 rrf_score: rrf_contribution,
409 });
410 }
411 }
412
413 let mut fused: Vec<FusedSearchResult> = all_results.into_values().collect();
414 fused.sort_by(|a, b| {
415 b.rrf_score
416 .partial_cmp(&a.rrf_score)
417 .unwrap_or(std::cmp::Ordering::Equal)
418 });
419 fused.truncate(max_results);
420 fused
421 }
422
423 pub fn search_single_repo(
425 &mut self,
426 repo: &str,
427 query: &str,
428 max_results: usize,
429 ) -> Result<Vec<RepoSearchResult>, String> {
430 let idx = self
431 .resolve_root(repo)
432 .ok_or_else(|| format!("Unknown repo: {repo}"))?;
433 if !authorized(&self.roots[idx].path) {
434 return Err(format!(
435 "{repo} is not a root of the launcher-bound Workspace"
436 ));
437 }
438 Ok(self.roots[idx].search(query, max_results))
439 }
440}
441
442impl Default for MultiRepoManager {
443 fn default() -> Self {
444 Self::new()
445 }
446}
447
448#[derive(Debug, Clone, Serialize)]
450pub struct RootInfo {
451 pub path: String,
452 pub alias: String,
453 pub has_index: bool,
454}
455
456pub fn config_file_path() -> PathBuf {
462 crate::core::paths::config_dir_member("multi-repo.toml")
463 .unwrap_or_else(|_| PathBuf::from("~/.config/lean-ctx/multi-repo.toml"))
464}
465
466static GLOBAL_MANAGER: std::sync::OnceLock<std::sync::Mutex<MultiRepoManager>> =
468 std::sync::OnceLock::new();
469
470pub fn global_manager() -> &'static std::sync::Mutex<MultiRepoManager> {
471 GLOBAL_MANAGER.get_or_init(|| {
472 let config = MultiRepoConfig::load();
473 let manager = MultiRepoManager::from_config(&config).unwrap_or_default();
474 std::sync::Mutex::new(manager)
475 })
476}
477
478pub fn init_with_roots(
480 roots: &[(String, Option<String>)],
481 rrf_k: Option<f64>,
482) -> Result<(), String> {
483 let mut manager = MultiRepoManager::new();
484 if let Some(k) = rrf_k {
485 manager.rrf_k = k;
486 }
487 manager.max_roots = max_roots_from_env(MultiRepoConfig::load().max_roots)
491 .max(roots.len())
492 .min(MAX_ROOTS_CEILING);
493 for (path, alias) in roots {
494 manager.add_root(path, alias.as_deref())?;
495 }
496 GLOBAL_MANAGER
497 .set(std::sync::Mutex::new(manager))
498 .map_err(|_| "Multi-repo manager already initialized".to_string())
499}
500
501pub fn resolve_repo_root(repo: &str) -> Option<String> {
505 let manager = global_manager();
506 let mgr = manager.lock().ok()?;
507 let idx = mgr.resolve_root(repo)?;
508 let root = &mgr.roots[idx].path;
509 authorized(root).then(|| root.to_string_lossy().to_string())
510}
511
512pub fn known_aliases() -> Vec<String> {
516 let manager = global_manager();
517 let Ok(mgr) = manager.lock() else {
518 return Vec::new();
519 };
520 mgr.roots.iter().map(ActiveRepoRoot::alias).collect()
521}
522
523pub fn is_multi_repo_active() -> bool {
525 let manager = global_manager();
526 manager.lock().is_ok_and(|mgr| mgr.is_active())
527}
528
529pub fn all_root_paths() -> Vec<String> {
531 let manager = global_manager();
532 let Ok(mgr) = manager.lock() else {
533 return Vec::new();
534 };
535 mgr.roots
536 .iter()
537 .filter(|r| authorized(&r.path))
538 .map(|r| r.path.to_string_lossy().to_string())
539 .collect()
540}
541
542fn authorized(root: &Path) -> bool {
547 crate::core::workspace_authority::root_authorized(root)
548}
549
550pub fn format_fused_results(results: &[FusedSearchResult]) -> String {
552 if results.is_empty() {
553 return "No results found across repos.".to_string();
554 }
555
556 let mut out = String::with_capacity(results.len() * 200);
557 out.push_str(&format!(
558 "Cross-repo results ({} matches):\n\n",
559 results.len()
560 ));
561
562 for (i, result) in results.iter().enumerate() {
563 out.push_str(&format!(
564 "{}. [{}] {}:{}-{} ({})\n RRF: {:.4}\n",
565 i + 1,
566 result.repo_alias,
567 result.file_path,
568 result.start_line,
569 result.end_line,
570 result.symbol_name,
571 result.rrf_score,
572 ));
573 let preview: String = result
574 .content
575 .lines()
576 .take(3)
577 .collect::<Vec<_>>()
578 .join("\n");
579 if !preview.is_empty() {
580 out.push_str(&format!(" {}\n", preview.replace('\n', "\n ")));
581 }
582 out.push('\n');
583 }
584 out
585}
586
587#[cfg(test)]
588pub mod tests {
589 use super::*;
590
591 #[test]
592 fn repo_root_config_effective_alias() {
593 let cfg = RepoRootConfig {
594 path: "/home/user/projects/backend".to_string(),
595 alias: None,
596 };
597 assert_eq!(cfg.effective_alias(), "backend");
598
599 let cfg_with_alias = RepoRootConfig {
600 path: "/home/user/projects/backend".to_string(),
601 alias: Some("api".to_string()),
602 };
603 assert_eq!(cfg_with_alias.effective_alias(), "api");
604 }
605
606 #[test]
607 fn multi_repo_config_default_is_empty() {
608 let cfg = MultiRepoConfig::default();
609 assert!(cfg.repos.is_empty());
610 assert!(cfg.rrf_k.is_none());
611 }
612
613 #[test]
614 fn multi_repo_config_deserialize() {
615 let toml_str = r#"
616rrf_k = 45.0
617
618[[repos]]
619path = "/home/user/backend"
620alias = "backend"
621
622[[repos]]
623path = "/home/user/frontend"
624"#;
625 let cfg: MultiRepoConfig = toml::from_str(toml_str).unwrap();
626 assert_eq!(cfg.repos.len(), 2);
627 assert_eq!(cfg.rrf_k, Some(45.0));
628 assert_eq!(cfg.repos[0].alias, Some("backend".to_string()));
629 assert_eq!(cfg.repos[1].alias, None);
630 }
631
632 #[test]
633 fn manager_max_roots_enforced() {
634 let mut manager = MultiRepoManager::new().with_max_roots(DEFAULT_MAX_ROOTS);
635 for i in 0..DEFAULT_MAX_ROOTS {
636 let dir = std::env::temp_dir().join(format!("multi_repo_test_{i}"));
637 let _ = std::fs::create_dir_all(&dir);
638 let _ = manager.add_root(&dir.to_string_lossy(), Some(&format!("repo{i}")));
639 }
640 let extra = std::env::temp_dir().join("multi_repo_test_extra");
641 let _ = std::fs::create_dir_all(&extra);
642 let result = manager.add_root(&extra.to_string_lossy(), None);
643 assert!(result.is_err());
644
645 for i in 0..=DEFAULT_MAX_ROOTS {
646 let dir = std::env::temp_dir().join(format!("multi_repo_test_{i}"));
647 let _ = std::fs::remove_dir_all(&dir);
648 }
649 let _ = std::fs::remove_dir_all(&extra);
650 }
651
652 #[test]
655 fn configured_max_roots_admits_more_than_the_default_gh2237() {
656 let base = tempfile::tempdir().unwrap();
657 let mut manager = MultiRepoManager::new().with_max_roots(20);
658 for i in 0..20 {
659 let dir = base.path().join(format!("r{i}"));
660 std::fs::create_dir_all(&dir).unwrap();
661 manager
662 .add_root(&dir.to_string_lossy(), Some(&format!("repo{i}")))
663 .unwrap();
664 }
665 assert_eq!(manager.root_count(), 20);
666 let extra = base.path().join("extra");
667 std::fs::create_dir_all(&extra).unwrap();
668 let err = manager
669 .add_root(&extra.to_string_lossy(), None)
670 .unwrap_err();
671 assert!(err.contains("(20)") && err.contains(MAX_ROOTS_ENV), "{err}");
672 }
673
674 #[test]
678 fn saved_roots_load_beyond_the_default_without_the_env_gh2237() {
679 let base = tempfile::tempdir().unwrap();
680 let repos = (0..DEFAULT_MAX_ROOTS + 4)
681 .map(|i| {
682 let dir = base.path().join(format!("r{i}"));
683 std::fs::create_dir_all(&dir).unwrap();
684 RepoRootConfig {
685 path: dir.to_string_lossy().into_owned(),
686 alias: Some(format!("repo{i}")),
687 }
688 })
689 .collect();
690 let config = MultiRepoConfig {
691 repos,
692 ..MultiRepoConfig::default()
693 };
694 let manager = MultiRepoManager::from_config(&config).unwrap();
695 assert_eq!(manager.root_count(), DEFAULT_MAX_ROOTS + 4);
696 assert!(manager.max_roots() >= DEFAULT_MAX_ROOTS + 4);
697 }
698
699 #[test]
700 fn max_roots_from_config_env_and_ceiling_gh2237() {
701 assert_eq!(effective_max_roots(None, None), DEFAULT_MAX_ROOTS);
702 assert_eq!(effective_max_roots(None, Some(32)), 32);
703 assert_eq!(effective_max_roots(Some("40"), Some(32)), 40);
704 assert_eq!(effective_max_roots(Some(" 24 "), None), 24);
705 assert_eq!(effective_max_roots(Some("lots"), Some(32)), 32);
706 assert_eq!(effective_max_roots(Some("0"), None), 1);
707 assert_eq!(effective_max_roots(Some("100000"), None), MAX_ROOTS_CEILING);
708 let cfg: MultiRepoConfig = toml::from_str("max_roots = 32\n").unwrap();
709 assert_eq!(cfg.max_roots, Some(32));
710 assert_eq!(
711 MultiRepoManager::from_config(&cfg).unwrap().max_roots(),
712 max_roots_from_env(Some(32))
713 );
714 }
715
716 #[test]
717 fn manager_duplicate_root_rejected() {
718 let dir = std::env::temp_dir().join("multi_repo_dup_test");
719 let _ = std::fs::create_dir_all(&dir);
720 let mut manager = MultiRepoManager::new();
721 assert!(
722 manager
723 .add_root(&dir.to_string_lossy(), Some("first"))
724 .is_ok()
725 );
726 assert!(
727 manager
728 .add_root(&dir.to_string_lossy(), Some("second"))
729 .is_err()
730 );
731 let _ = std::fs::remove_dir_all(&dir);
732 }
733
734 #[test]
735 fn rrf_fusion_basic() {
736 let manager = MultiRepoManager::new().with_rrf_k(60.0);
737 let score: f64 = 1.0 / (60.0 + 0.0 + 1.0);
739 assert!((score - 0.01639).abs() < 0.001);
740
741 assert_eq!(manager.rrf_k, 60.0);
742 }
743
744 #[test]
745 fn remove_root_works() {
746 let dir = std::env::temp_dir().join("multi_repo_remove_test");
747 let _ = std::fs::create_dir_all(&dir);
748 let mut manager = MultiRepoManager::new();
749 manager
750 .add_root(&dir.to_string_lossy(), Some("removable"))
751 .unwrap();
752 assert_eq!(manager.root_count(), 1);
753 manager.remove_root(&dir.to_string_lossy()).unwrap();
754 assert_eq!(manager.root_count(), 0);
755 let _ = std::fs::remove_dir_all(&dir);
756 }
757
758 #[test]
759 fn list_roots_returns_info() {
760 let dir = std::env::temp_dir().join("multi_repo_list_test");
761 let _ = std::fs::create_dir_all(&dir);
762 let mut manager = MultiRepoManager::new();
763 manager
764 .add_root(&dir.to_string_lossy(), Some("myrepo"))
765 .unwrap();
766 let roots = manager.list_roots();
767 assert_eq!(roots.len(), 1);
768 assert_eq!(roots[0].alias, "myrepo");
769 let _ = std::fs::remove_dir_all(&dir);
770 }
771
772 #[test]
773 fn format_empty_results() {
774 let results: Vec<FusedSearchResult> = Vec::new();
775 let output = format_fused_results(&results);
776 assert!(output.contains("No results"));
777 }
778}