1mod dispatch;
2mod execute;
3pub mod helpers;
4
5use rmcp::handler::server::ServerHandler;
6use rmcp::model::*;
7use rmcp::service::{RequestContext, RoleServer};
8use rmcp::ErrorData;
9
10use crate::tools::{CrpMode, LeanCtxServer};
11
12impl ServerHandler for LeanCtxServer {
13 fn get_info(&self) -> ServerInfo {
14 let capabilities = ServerCapabilities::builder().enable_tools().build();
15
16 let instructions = crate::instructions::build_instructions(self.crp_mode);
17
18 InitializeResult::new(capabilities)
19 .with_server_info(Implementation::new("lean-ctx", env!("CARGO_PKG_VERSION")))
20 .with_instructions(instructions)
21 }
22
23 async fn initialize(
24 &self,
25 request: InitializeRequestParams,
26 _context: RequestContext<RoleServer>,
27 ) -> Result<InitializeResult, ErrorData> {
28 let name = request.client_info.name.clone();
29 tracing::info!("MCP client connected: {:?}", name);
30 *self.client_name.write().await = name.clone();
31
32 let derived_root = derive_project_root_from_cwd();
33 let cwd_str = std::env::current_dir()
34 .ok()
35 .map(|p| p.to_string_lossy().to_string())
36 .unwrap_or_default();
37 {
38 let mut session = self.session.write().await;
39 if !cwd_str.is_empty() {
40 session.shell_cwd = Some(cwd_str.clone());
41 }
42 if let Some(ref root) = derived_root {
43 session.project_root = Some(root.clone());
44 tracing::info!("Project root set to: {root}");
45 } else if let Some(ref root) = session.project_root {
46 let root_path = std::path::Path::new(root);
47 let root_has_marker = has_project_marker(root_path);
48 let root_str = root_path.to_string_lossy();
49 let root_suspicious = root_str.contains("/.claude")
50 || root_str.contains("/.codex")
51 || root_str.contains("/var/folders/")
52 || root_str.contains("/tmp/")
53 || root_str.contains("\\.claude")
54 || root_str.contains("\\.codex")
55 || root_str.contains("\\AppData\\Local\\Temp")
56 || root_str.contains("\\Temp\\");
57 if root_suspicious && !root_has_marker {
58 session.project_root = None;
59 }
60 }
61 let _ = session.save();
62 }
63
64 let agent_name = name.clone();
65 let agent_root = derived_root.clone().unwrap_or_default();
66 let agent_id_handle = self.agent_id.clone();
67 tokio::task::spawn_blocking(move || {
68 if std::env::var("LEAN_CTX_HEADLESS").is_ok() {
69 return;
70 }
71 if let Some(home) = dirs::home_dir() {
72 let _ = crate::rules_inject::inject_all_rules(&home);
73 }
74 crate::hooks::refresh_installed_hooks();
75 crate::core::version_check::check_background();
76
77 if !agent_root.is_empty() {
78 let role = match agent_name.to_lowercase().as_str() {
79 n if n.contains("cursor") => Some("coder"),
80 n if n.contains("claude") => Some("coder"),
81 n if n.contains("codex") => Some("coder"),
82 n if n.contains("antigravity") || n.contains("gemini") => Some("explorer"),
83 n if n.contains("review") => Some("reviewer"),
84 n if n.contains("test") => Some("tester"),
85 _ => None,
86 };
87 let env_role = std::env::var("LEAN_CTX_AGENT_ROLE").ok();
88 let effective_role = env_role.as_deref().or(role);
89 let mut registry = crate::core::agents::AgentRegistry::load_or_create();
90 registry.cleanup_stale(24);
91 let id = registry.register("mcp", effective_role, &agent_root);
92 let _ = registry.save();
93 if let Ok(mut guard) = agent_id_handle.try_write() {
94 *guard = Some(id);
95 }
96 }
97 });
98
99 let instructions =
100 crate::instructions::build_instructions_with_client(self.crp_mode, &name);
101 let capabilities = ServerCapabilities::builder().enable_tools().build();
102
103 Ok(InitializeResult::new(capabilities)
104 .with_server_info(Implementation::new("lean-ctx", env!("CARGO_PKG_VERSION")))
105 .with_instructions(instructions))
106 }
107
108 async fn list_tools(
109 &self,
110 _request: Option<PaginatedRequestParams>,
111 _context: RequestContext<RoleServer>,
112 ) -> Result<ListToolsResult, ErrorData> {
113 let all_tools = if crate::tool_defs::is_lazy_mode() {
114 crate::tool_defs::lazy_tool_defs()
115 } else if std::env::var("LEAN_CTX_UNIFIED").is_ok()
116 && std::env::var("LEAN_CTX_FULL_TOOLS").is_err()
117 {
118 crate::tool_defs::unified_tool_defs()
119 } else {
120 crate::tool_defs::granular_tool_defs()
121 };
122
123 let disabled = crate::core::config::Config::load().disabled_tools_effective();
124 let tools = if disabled.is_empty() {
125 all_tools
126 } else {
127 all_tools
128 .into_iter()
129 .filter(|t| !disabled.iter().any(|d| t.name.as_ref() == d.as_str()))
130 .collect()
131 };
132
133 let tools = {
134 let active = self.workflow.read().await.clone();
135 if let Some(run) = active {
136 if let Some(state) = run.spec.state(&run.current) {
137 if let Some(allowed) = &state.allowed_tools {
138 let mut allow: std::collections::HashSet<&str> =
139 allowed.iter().map(|s| s.as_str()).collect();
140 allow.insert("ctx");
141 allow.insert("ctx_workflow");
142 return Ok(ListToolsResult {
143 tools: tools
144 .into_iter()
145 .filter(|t| allow.contains(t.name.as_ref()))
146 .collect(),
147 ..Default::default()
148 });
149 }
150 }
151 }
152 tools
153 };
154
155 Ok(ListToolsResult {
156 tools,
157 ..Default::default()
158 })
159 }
160
161 async fn call_tool(
162 &self,
163 request: CallToolRequestParams,
164 _context: RequestContext<RoleServer>,
165 ) -> Result<CallToolResult, ErrorData> {
166 self.check_idle_expiry().await;
167
168 let original_name = request.name.as_ref().to_string();
169 let (resolved_name, resolved_args) = if original_name == "ctx" {
170 let sub = request
171 .arguments
172 .as_ref()
173 .and_then(|a| a.get("tool"))
174 .and_then(|v| v.as_str())
175 .map(|s| s.to_string())
176 .ok_or_else(|| {
177 ErrorData::invalid_params("'tool' is required for ctx meta-tool", None)
178 })?;
179 let tool_name = if sub.starts_with("ctx_") {
180 sub
181 } else {
182 format!("ctx_{sub}")
183 };
184 let mut args = request.arguments.unwrap_or_default();
185 args.remove("tool");
186 (tool_name, Some(args))
187 } else {
188 (original_name, request.arguments)
189 };
190 let name = resolved_name.as_str();
191 let args = &resolved_args;
192
193 if name != "ctx_workflow" {
194 let active = self.workflow.read().await.clone();
195 if let Some(run) = active {
196 if let Some(state) = run.spec.state(&run.current) {
197 if let Some(allowed) = &state.allowed_tools {
198 let allowed_ok = allowed.iter().any(|t| t == name) || name == "ctx";
199 if !allowed_ok {
200 let mut shown = allowed.clone();
201 shown.sort();
202 shown.truncate(30);
203 return Ok(CallToolResult::success(vec![Content::text(format!(
204 "Tool '{name}' blocked by workflow '{}' (state: {}). Allowed ({} shown): {}",
205 run.spec.name,
206 run.current,
207 shown.len(),
208 shown.join(", ")
209 ))]));
210 }
211 }
212 }
213 }
214 }
215
216 let auto_context = {
217 let task = {
218 let session = self.session.read().await;
219 session.task.as_ref().map(|t| t.description.clone())
220 };
221 let project_root = {
222 let session = self.session.read().await;
223 session.project_root.clone()
224 };
225 let mut cache = self.cache.write().await;
226 crate::tools::autonomy::session_lifecycle_pre_hook(
227 &self.autonomy,
228 name,
229 &mut cache,
230 task.as_deref(),
231 project_root.as_deref(),
232 self.crp_mode,
233 )
234 };
235
236 let throttle_result = {
237 let fp = args
238 .as_ref()
239 .map(|a| {
240 crate::core::loop_detection::LoopDetector::fingerprint(
241 &serde_json::Value::Object(a.clone()),
242 )
243 })
244 .unwrap_or_default();
245 let mut detector = self.loop_detector.write().await;
246
247 let is_search = crate::core::loop_detection::LoopDetector::is_search_tool(name);
248 let is_search_shell = name == "ctx_shell" && {
249 let cmd = args
250 .as_ref()
251 .and_then(|a| a.get("command"))
252 .and_then(|v| v.as_str())
253 .unwrap_or("");
254 crate::core::loop_detection::LoopDetector::is_search_shell_command(cmd)
255 };
256
257 if is_search || is_search_shell {
258 let search_pattern = args.as_ref().and_then(|a| {
259 a.get("pattern")
260 .or_else(|| a.get("query"))
261 .and_then(|v| v.as_str())
262 });
263 let shell_pattern = if is_search_shell {
264 args.as_ref()
265 .and_then(|a| a.get("command"))
266 .and_then(|v| v.as_str())
267 .and_then(helpers::extract_search_pattern_from_command)
268 } else {
269 None
270 };
271 let pat = search_pattern.or(shell_pattern.as_deref());
272 detector.record_search(name, &fp, pat)
273 } else {
274 detector.record_call(name, &fp)
275 }
276 };
277
278 if throttle_result.level == crate::core::loop_detection::ThrottleLevel::Blocked {
279 let msg = throttle_result.message.unwrap_or_default();
280 return Ok(CallToolResult::success(vec![Content::text(msg)]));
281 }
282
283 let throttle_warning =
284 if throttle_result.level == crate::core::loop_detection::ThrottleLevel::Reduced {
285 throttle_result.message.clone()
286 } else {
287 None
288 };
289
290 let tool_start = std::time::Instant::now();
291 let result_text = self.dispatch_tool(name, args).await?;
292
293 let mut result_text = result_text;
294
295 let archive_hint = {
297 use crate::core::archive;
298 let archivable = matches!(
299 name,
300 "ctx_shell"
301 | "ctx_read"
302 | "ctx_multi_read"
303 | "ctx_smart_read"
304 | "ctx_execute"
305 | "ctx_search"
306 | "ctx_tree"
307 );
308 if archivable && archive::should_archive(&result_text) {
309 let cmd = helpers::get_str(args, "command")
310 .or_else(|| helpers::get_str(args, "path"))
311 .unwrap_or_default();
312 let session_id = self.session.read().await.id.clone();
313 let tokens = crate::core::tokens::count_tokens(&result_text);
314 archive::store(name, &cmd, &result_text, Some(&session_id))
315 .map(|id| archive::format_hint(&id, result_text.len(), tokens))
316 } else {
317 None
318 }
319 };
320
321 {
322 let config = crate::core::config::Config::load();
323 let density = crate::core::config::OutputDensity::effective(&config.output_density);
324 result_text = crate::core::protocol::compress_output(&result_text, &density);
325 }
326
327 if let Some(hint) = archive_hint {
328 result_text = format!("{result_text}\n{hint}");
329 }
330
331 if let Some(ctx) = auto_context {
332 result_text = format!("{ctx}\n\n{result_text}");
333 }
334
335 if let Some(warning) = throttle_warning {
336 result_text = format!("{result_text}\n\n{warning}");
337 }
338
339 if name == "ctx_read" {
340 let read_path = self
341 .resolve_path_or_passthrough(&helpers::get_str(args, "path").unwrap_or_default())
342 .await;
343 let project_root = {
344 let session = self.session.read().await;
345 session.project_root.clone()
346 };
347 let mut cache = self.cache.write().await;
348 let enrich = crate::tools::autonomy::enrich_after_read(
349 &self.autonomy,
350 &mut cache,
351 &read_path,
352 project_root.as_deref(),
353 );
354 if let Some(hint) = enrich.related_hint {
355 result_text = format!("{result_text}\n{hint}");
356 }
357
358 crate::tools::autonomy::maybe_auto_dedup(&self.autonomy, &mut cache);
359 }
360
361 if name == "ctx_shell" {
362 let cmd = helpers::get_str(args, "command").unwrap_or_default();
363 let output_tokens = crate::core::tokens::count_tokens(&result_text);
364 let calls = self.tool_calls.read().await;
365 let last_original = calls.last().map(|c| c.original_tokens).unwrap_or(0);
366 drop(calls);
367 if let Some(hint) = crate::tools::autonomy::shell_efficiency_hint(
368 &self.autonomy,
369 &cmd,
370 last_original,
371 output_tokens,
372 ) {
373 result_text = format!("{result_text}\n{hint}");
374 }
375 }
376
377 {
378 let input = helpers::canonical_args_string(args);
379 let input_md5 = helpers::md5_hex(&input);
380 let output_md5 = helpers::md5_hex(&result_text);
381 let action = helpers::get_str(args, "action");
382 let agent_id = self.agent_id.read().await.clone();
383 let client_name = self.client_name.read().await.clone();
384 let mut explicit_intent: Option<(
385 crate::core::intent_protocol::IntentRecord,
386 Option<String>,
387 String,
388 )> = None;
389
390 {
391 let empty_args = serde_json::Map::new();
392 let args_map = args.as_ref().unwrap_or(&empty_args);
393 let mut session = self.session.write().await;
394 session.record_tool_receipt(
395 name,
396 action.as_deref(),
397 &input_md5,
398 &output_md5,
399 agent_id.as_deref(),
400 Some(&client_name),
401 );
402
403 if let Some(intent) = crate::core::intent_protocol::infer_from_tool_call(
404 name,
405 action.as_deref(),
406 args_map,
407 session.project_root.as_deref(),
408 ) {
409 let is_explicit =
410 intent.source == crate::core::intent_protocol::IntentSource::Explicit;
411 let root = session.project_root.clone();
412 let sid = session.id.clone();
413 session.record_intent(intent.clone());
414 if is_explicit {
415 explicit_intent = Some((intent, root, sid));
416 }
417 }
418 if session.should_save() {
419 let _ = session.save();
420 }
421 }
422
423 if let Some((intent, root, session_id)) = explicit_intent {
424 crate::core::intent_protocol::apply_side_effects(
425 &intent,
426 root.as_deref(),
427 &session_id,
428 );
429 }
430
431 if self.autonomy.is_enabled() {
433 let (calls, project_root) = {
434 let session = self.session.read().await;
435 (session.stats.total_tool_calls, session.project_root.clone())
436 };
437
438 if let Some(root) = project_root {
439 if crate::tools::autonomy::should_auto_consolidate(&self.autonomy, calls) {
440 let root_clone = root.clone();
441 tokio::task::spawn_blocking(move || {
442 let _ = crate::core::consolidation_engine::consolidate_latest(
443 &root_clone,
444 crate::core::consolidation_engine::ConsolidationBudgets::default(),
445 );
446 });
447 }
448 }
449 }
450
451 let agent_key = agent_id.unwrap_or_else(|| "unknown".to_string());
452 let input_tokens = crate::core::tokens::count_tokens(&input) as u64;
453 let output_tokens = crate::core::tokens::count_tokens(&result_text) as u64;
454 let mut store = crate::core::a2a::cost_attribution::CostStore::load();
455 store.record_tool_call(&agent_key, &client_name, name, input_tokens, output_tokens);
456 let _ = store.save();
457 }
458
459 let skip_checkpoint = matches!(
460 name,
461 "ctx_compress"
462 | "ctx_metrics"
463 | "ctx_benchmark"
464 | "ctx_analyze"
465 | "ctx_cache"
466 | "ctx_discover"
467 | "ctx_dedup"
468 | "ctx_session"
469 | "ctx_knowledge"
470 | "ctx_agent"
471 | "ctx_share"
472 | "ctx_wrapped"
473 | "ctx_overview"
474 | "ctx_preload"
475 | "ctx_cost"
476 | "ctx_gain"
477 | "ctx_heatmap"
478 | "ctx_task"
479 | "ctx_impact"
480 | "ctx_architecture"
481 | "ctx_workflow"
482 );
483
484 if !skip_checkpoint && self.increment_and_check() {
485 if let Some(checkpoint) = self.auto_checkpoint().await {
486 let combined = format!(
487 "{result_text}\n\n--- AUTO CHECKPOINT (every {} calls) ---\n{checkpoint}",
488 self.checkpoint_interval
489 );
490 return Ok(CallToolResult::success(vec![Content::text(combined)]));
491 }
492 }
493
494 let tool_duration_ms = tool_start.elapsed().as_millis() as u64;
495 if tool_duration_ms > 100 {
496 LeanCtxServer::append_tool_call_log(
497 name,
498 tool_duration_ms,
499 0,
500 0,
501 None,
502 &chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string(),
503 );
504 }
505
506 let current_count = self.call_count.load(std::sync::atomic::Ordering::Relaxed);
507 if current_count > 0 && current_count.is_multiple_of(100) {
508 std::thread::spawn(crate::cloud_sync::cloud_background_tasks);
509 }
510
511 Ok(CallToolResult::success(vec![Content::text(result_text)]))
512 }
513}
514
515pub fn build_instructions_for_test(crp_mode: CrpMode) -> String {
516 crate::instructions::build_instructions(crp_mode)
517}
518
519pub fn build_claude_code_instructions_for_test() -> String {
520 crate::instructions::claude_code_instructions()
521}
522
523const PROJECT_MARKERS: &[&str] = &[
524 ".git",
525 "Cargo.toml",
526 "package.json",
527 "go.mod",
528 "pyproject.toml",
529 "setup.py",
530 "pom.xml",
531 "build.gradle",
532 "Makefile",
533 ".lean-ctx.toml",
534];
535
536fn has_project_marker(dir: &std::path::Path) -> bool {
537 PROJECT_MARKERS.iter().any(|m| dir.join(m).exists())
538}
539
540fn is_home_or_agent_dir(dir: &std::path::Path) -> bool {
541 if let Some(home) = dirs::home_dir() {
542 if dir == home {
543 return true;
544 }
545 }
546 let dir_str = dir.to_string_lossy();
547 dir_str.ends_with("/.claude")
548 || dir_str.ends_with("/.codex")
549 || dir_str.contains("/.claude/")
550 || dir_str.contains("/.codex/")
551}
552
553fn git_toplevel_from(dir: &std::path::Path) -> Option<String> {
554 std::process::Command::new("git")
555 .args(["rev-parse", "--show-toplevel"])
556 .current_dir(dir)
557 .stdout(std::process::Stdio::piped())
558 .stderr(std::process::Stdio::null())
559 .output()
560 .ok()
561 .and_then(|o| {
562 if o.status.success() {
563 String::from_utf8(o.stdout)
564 .ok()
565 .map(|s| s.trim().to_string())
566 } else {
567 None
568 }
569 })
570}
571
572pub fn derive_project_root_from_cwd() -> Option<String> {
573 let cwd = std::env::current_dir().ok()?;
574 let canonical = crate::core::pathutil::safe_canonicalize_or_self(&cwd);
575
576 if is_home_or_agent_dir(&canonical) {
577 return git_toplevel_from(&canonical);
578 }
579
580 if has_project_marker(&canonical) {
581 return Some(canonical.to_string_lossy().to_string());
582 }
583
584 if let Some(git_root) = git_toplevel_from(&canonical) {
585 return Some(git_root);
586 }
587
588 if let Some(root) = detect_multi_root_workspace(&canonical) {
589 return Some(root);
590 }
591
592 None
593}
594
595fn detect_multi_root_workspace(dir: &std::path::Path) -> Option<String> {
599 let entries = std::fs::read_dir(dir).ok()?;
600 let mut child_projects: Vec<String> = Vec::new();
601
602 for entry in entries.flatten() {
603 let path = entry.path();
604 if path.is_dir() && has_project_marker(&path) {
605 let canonical = crate::core::pathutil::safe_canonicalize_or_self(&path);
606 child_projects.push(canonical.to_string_lossy().to_string());
607 }
608 }
609
610 if child_projects.len() >= 2 {
611 let existing = std::env::var("LEAN_CTX_ALLOW_PATH").unwrap_or_default();
612 let sep = if cfg!(windows) { ";" } else { ":" };
613 let merged = if existing.is_empty() {
614 child_projects.join(sep)
615 } else {
616 format!("{existing}{sep}{}", child_projects.join(sep))
617 };
618 std::env::set_var("LEAN_CTX_ALLOW_PATH", &merged);
619 tracing::info!(
620 "Multi-root workspace detected at {}: auto-allowing {} child projects",
621 dir.display(),
622 child_projects.len()
623 );
624 return Some(dir.to_string_lossy().to_string());
625 }
626
627 None
628}
629
630pub fn tool_descriptions_for_test() -> Vec<(&'static str, &'static str)> {
631 crate::tool_defs::list_all_tool_defs()
632 .into_iter()
633 .map(|(name, desc, _)| (name, desc))
634 .collect()
635}
636
637pub fn tool_schemas_json_for_test() -> String {
638 crate::tool_defs::list_all_tool_defs()
639 .iter()
640 .map(|(name, _, schema)| format!("{}: {}", name, schema))
641 .collect::<Vec<_>>()
642 .join("\n")
643}
644
645#[cfg(test)]
646mod tests {
647 use super::*;
648
649 #[test]
650 fn project_markers_detected() {
651 let tmp = tempfile::tempdir().unwrap();
652 let root = tmp.path().join("myproject");
653 std::fs::create_dir_all(&root).unwrap();
654 assert!(!has_project_marker(&root));
655
656 std::fs::create_dir(root.join(".git")).unwrap();
657 assert!(has_project_marker(&root));
658 }
659
660 #[test]
661 fn home_dir_detected_as_agent_dir() {
662 if let Some(home) = dirs::home_dir() {
663 assert!(is_home_or_agent_dir(&home));
664 }
665 }
666
667 #[test]
668 fn agent_dirs_detected() {
669 let claude = std::path::PathBuf::from("/home/user/.claude");
670 assert!(is_home_or_agent_dir(&claude));
671 let codex = std::path::PathBuf::from("/home/user/.codex");
672 assert!(is_home_or_agent_dir(&codex));
673 let project = std::path::PathBuf::from("/home/user/projects/myapp");
674 assert!(!is_home_or_agent_dir(&project));
675 }
676
677 #[test]
678 fn test_unified_tool_count() {
679 let tools = crate::tool_defs::unified_tool_defs();
680 assert_eq!(tools.len(), 5, "Expected 5 unified tools");
681 }
682
683 #[test]
684 fn test_granular_tool_count() {
685 let tools = crate::tool_defs::granular_tool_defs();
686 assert!(tools.len() >= 25, "Expected at least 25 granular tools");
687 }
688
689 #[test]
690 fn disabled_tools_filters_list() {
691 let all = crate::tool_defs::granular_tool_defs();
692 let total = all.len();
693 let disabled = ["ctx_graph".to_string(), "ctx_agent".to_string()];
694 let filtered: Vec<_> = all
695 .into_iter()
696 .filter(|t| !disabled.iter().any(|d| t.name.as_ref() == d.as_str()))
697 .collect();
698 assert_eq!(filtered.len(), total - 2);
699 assert!(!filtered.iter().any(|t| t.name.as_ref() == "ctx_graph"));
700 assert!(!filtered.iter().any(|t| t.name.as_ref() == "ctx_agent"));
701 }
702
703 #[test]
704 fn empty_disabled_tools_returns_all() {
705 let all = crate::tool_defs::granular_tool_defs();
706 let total = all.len();
707 let disabled: Vec<String> = vec![];
708 let filtered: Vec<_> = all
709 .into_iter()
710 .filter(|t| !disabled.iter().any(|d| t.name.as_ref() == d.as_str()))
711 .collect();
712 assert_eq!(filtered.len(), total);
713 }
714
715 #[test]
716 fn misspelled_disabled_tool_is_silently_ignored() {
717 let all = crate::tool_defs::granular_tool_defs();
718 let total = all.len();
719 let disabled = ["ctx_nonexistent_tool".to_string()];
720 let filtered: Vec<_> = all
721 .into_iter()
722 .filter(|t| !disabled.iter().any(|d| t.name.as_ref() == d.as_str()))
723 .collect();
724 assert_eq!(filtered.len(), total);
725 }
726
727 #[test]
728 fn detect_multi_root_workspace_with_child_projects() {
729 let tmp = tempfile::tempdir().unwrap();
730 let workspace = tmp.path().join("workspace");
731 std::fs::create_dir_all(&workspace).unwrap();
732
733 let proj_a = workspace.join("project-a");
734 let proj_b = workspace.join("project-b");
735 std::fs::create_dir_all(proj_a.join(".git")).unwrap();
736 std::fs::create_dir_all(&proj_b).unwrap();
737 std::fs::write(proj_b.join("package.json"), "{}").unwrap();
738
739 let result = detect_multi_root_workspace(&workspace);
740 assert!(
741 result.is_some(),
742 "should detect workspace with 2 child projects"
743 );
744
745 std::env::remove_var("LEAN_CTX_ALLOW_PATH");
746 }
747
748 #[test]
749 fn detect_multi_root_workspace_returns_none_for_single_project() {
750 let tmp = tempfile::tempdir().unwrap();
751 let workspace = tmp.path().join("workspace");
752 std::fs::create_dir_all(&workspace).unwrap();
753
754 let proj_a = workspace.join("project-a");
755 std::fs::create_dir_all(proj_a.join(".git")).unwrap();
756
757 let result = detect_multi_root_workspace(&workspace);
758 assert!(
759 result.is_none(),
760 "should not detect workspace with only 1 child project"
761 );
762 }
763}