mod dispatch;
mod execute;
pub mod helpers;
pub mod pipeline_stages;
pub mod registry;
pub mod role_guard;
pub mod tool_trait;

use rmcp::handler::server::ServerHandler;
use rmcp::model::{
    CallToolRequestParams, CallToolResult, Content, Implementation, InitializeRequestParams,
    InitializeResult, ListToolsResult, PaginatedRequestParams, ServerCapabilities, ServerInfo,
};
use rmcp::service::{RequestContext, RoleServer};
use rmcp::ErrorData;

use crate::tools::{CrpMode, LeanCtxServer};

impl ServerHandler for LeanCtxServer {
    fn get_info(&self) -> ServerInfo {
        let capabilities = ServerCapabilities::builder().enable_tools().build();

        let config = crate::core::config::Config::load();
        let level = crate::core::config::CompressionLevel::effective(&config);
        let _ = crate::core::terse::rules_inject::inject(&level);

        let instructions = crate::instructions::build_instructions(CrpMode::effective());

        InitializeResult::new(capabilities)
            .with_server_info(Implementation::new("lean-ctx", env!("CARGO_PKG_VERSION")))
            .with_instructions(instructions)
    }

    async fn initialize(
        &self,
        request: InitializeRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<InitializeResult, ErrorData> {
        let name = request.client_info.name.clone();
        tracing::info!("MCP client connected: {:?}", name);
        *self.client_name.write().await = name.clone();

        let derived_root = derive_project_root_from_cwd();
        let cwd_str = std::env::current_dir()
            .ok()
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_default();
        {
            let mut session = self.session.write().await;
            if !cwd_str.is_empty() {
                session.shell_cwd = Some(cwd_str.clone());
            }
            if let Some(ref root) = derived_root {
                session.project_root = Some(root.clone());
                tracing::info!("Project root set to: {root}");
            } else if let Some(ref root) = session.project_root {
                let root_path = std::path::Path::new(root);
                let root_has_marker = has_project_marker(root_path);
                let root_str = root_path.to_string_lossy();
                let root_suspicious = root_str.contains("/.claude")
                    || root_str.contains("/.codex")
                    || root_str.contains("/var/folders/")
                    || root_str.contains("/tmp/")
                    || root_str.contains("\\.claude")
                    || root_str.contains("\\.codex")
                    || root_str.contains("\\AppData\\Local\\Temp")
                    || root_str.contains("\\Temp\\");
                if root_suspicious && !root_has_marker {
                    session.project_root = None;
                }
            }
            if self.session_mode == crate::tools::SessionMode::Shared {
                if let Some(ref root) = session.project_root {
                    if let Some(ref rt) = self.context_os {
                        rt.shared_sessions.persist_best_effort(
                            root,
                            &self.workspace_id,
                            &self.channel_id,
                            &session,
                        );
                        rt.metrics.record_session_persisted();
                    }
                }
            } else {
                let _ = session.save();
            }
        }

        let agent_name = name.clone();
        let agent_root = derived_root.clone().unwrap_or_default();
        let agent_id_handle = self.agent_id.clone();
        tokio::task::spawn_blocking(move || {
            if std::env::var("LEAN_CTX_HEADLESS").is_ok() {
                return;
            }

            // Avoid startup stampedes when multiple agent sessions initialize at once.
            // These are best-effort maintenance tasks; it's fine to skip if another
            // lean-ctx instance is already doing them.
            let maintenance = crate::core::startup_guard::try_acquire_lock(
                "startup-maintenance",
                std::time::Duration::from_secs(2),
                std::time::Duration::from_mins(2),
            );
            if maintenance.is_some() {
                if let Some(home) = dirs::home_dir() {
                    let _ = crate::rules_inject::inject_all_rules(&home);
                }
                crate::hooks::refresh_installed_hooks();
                crate::core::version_check::check_background();
            }
            drop(maintenance);

            if !agent_root.is_empty() {
                let heuristic_role = match agent_name.to_lowercase().as_str() {
                    n if n.contains("cursor") => Some("coder"),
                    n if n.contains("claude") => Some("coder"),
                    n if n.contains("codex") => Some("coder"),
                    n if n.contains("antigravity") || n.contains("gemini") => Some("coder"),
                    n if n.contains("review") => Some("reviewer"),
                    n if n.contains("test") => Some("debugger"),
                    _ => None,
                };
                let env_role = std::env::var("LEAN_CTX_ROLE")
                    .or_else(|_| std::env::var("LEAN_CTX_AGENT_ROLE"))
                    .ok();
                let effective_role = env_role.as_deref().or(heuristic_role).unwrap_or("coder");

                let _ = crate::core::roles::set_active_role(effective_role);

                let mut registry = crate::core::agents::AgentRegistry::load_or_create();
                registry.cleanup_stale(24);
                let id = registry.register("mcp", Some(effective_role), &agent_root);
                let _ = registry.save();
                if let Ok(mut guard) = agent_id_handle.try_write() {
                    *guard = Some(id);
                }
            }
        });

        let instructions =
            crate::instructions::build_instructions_with_client(CrpMode::effective(), &name);
        let capabilities = ServerCapabilities::builder().enable_tools().build();

        Ok(InitializeResult::new(capabilities)
            .with_server_info(Implementation::new("lean-ctx", env!("CARGO_PKG_VERSION")))
            .with_instructions(instructions))
    }

    async fn list_tools(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListToolsResult, ErrorData> {
        let all_tools = if crate::tool_defs::is_full_mode() {
            crate::tool_defs::granular_tool_defs()
        } else if std::env::var("LEAN_CTX_UNIFIED").is_ok() {
            crate::tool_defs::unified_tool_defs()
        } else {
            crate::tool_defs::lazy_tool_defs()
        };

        let disabled = crate::core::config::Config::load().disabled_tools_effective();
        let tools = if disabled.is_empty() {
            all_tools
        } else {
            all_tools
                .into_iter()
                .filter(|t| !disabled.iter().any(|d| t.name.as_ref() == d.as_str()))
                .collect()
        };

        let tools = {
            let active = self.workflow.read().await.clone();
            if let Some(run) = active {
                if let Some(state) = run.spec.state(&run.current) {
                    if let Some(allowed) = &state.allowed_tools {
                        let mut allow: std::collections::HashSet<&str> =
                            allowed.iter().map(std::string::String::as_str).collect();
                        allow.insert("ctx");
                        allow.insert("ctx_workflow");
                        return Ok(ListToolsResult {
                            tools: tools
                                .into_iter()
                                .filter(|t| allow.contains(t.name.as_ref()))
                                .collect(),
                            ..Default::default()
                        });
                    }
                }
            }
            tools
        };

        let tools = {
            let level = crate::core::config::Config::load().compression_level;
            let mode =
                crate::core::terse::mcp_compress::DescriptionMode::from_compression_level(&level);
            if mode == crate::core::terse::mcp_compress::DescriptionMode::Full {
                tools
            } else {
                tools
                    .into_iter()
                    .map(|mut t| {
                        let compressed = crate::core::terse::mcp_compress::compress_description(
                            t.name.as_ref(),
                            t.description.as_deref().unwrap_or(""),
                            mode,
                        );
                        t.description = Some(compressed.into());
                        t
                    })
                    .collect()
            }
        };

        Ok(ListToolsResult {
            tools,
            ..Default::default()
        })
    }

    async fn call_tool(
        &self,
        request: CallToolRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, ErrorData> {
        self.check_idle_expiry().await;

        let original_name = request.name.as_ref().to_string();
        let (resolved_name, resolved_args) = if original_name == "ctx" {
            let sub = request
                .arguments
                .as_ref()
                .and_then(|a| a.get("tool"))
                .and_then(|v| v.as_str())
                .map(std::string::ToString::to_string)
                .ok_or_else(|| {
                    ErrorData::invalid_params("'tool' is required for ctx meta-tool", None)
                })?;
            let tool_name = if sub.starts_with("ctx_") {
                sub
            } else {
                format!("ctx_{sub}")
            };
            let mut args = request.arguments.unwrap_or_default();
            args.remove("tool");
            (tool_name, Some(args))
        } else {
            (original_name, request.arguments)
        };
        let name = resolved_name.as_str();
        let args = resolved_args.as_ref();

        let role_check = role_guard::check_tool_access(name);
        if let Some(denied) = role_guard::into_call_tool_result(&role_check) {
            tracing::warn!(
                tool = name,
                role = %role_check.role_name,
                "Tool blocked by role policy"
            );
            return Ok(denied);
        }

        if name != "ctx_workflow" {
            let active = self.workflow.read().await.clone();
            if let Some(run) = active {
                if let Some(state) = run.spec.state(&run.current) {
                    if let Some(allowed) = &state.allowed_tools {
                        let allowed_ok = allowed.iter().any(|t| t == name) || name == "ctx";
                        if !allowed_ok {
                            let mut shown = allowed.clone();
                            shown.sort();
                            shown.truncate(30);
                            return Ok(CallToolResult::success(vec![Content::text(format!(
                                "Tool '{name}' blocked by workflow '{}' (state: {}). Allowed ({} shown): {}",
                                run.spec.name,
                                run.current,
                                shown.len(),
                                shown.join(", ")
                            ))]));
                        }
                    }
                }
            }
        }

        let auto_context = {
            let task = {
                let session = self.session.read().await;
                session.task.as_ref().map(|t| t.description.clone())
            };
            let project_root = {
                let session = self.session.read().await;
                session.project_root.clone()
            };
            let mut cache = self.cache.write().await;
            crate::tools::autonomy::session_lifecycle_pre_hook(
                &self.autonomy,
                name,
                &mut cache,
                task.as_deref(),
                project_root.as_deref(),
                CrpMode::effective(),
            )
        };

        let throttle_result = {
            let fp = args
                .map(|a| {
                    crate::core::loop_detection::LoopDetector::fingerprint(
                        &serde_json::Value::Object(a.clone()),
                    )
                })
                .unwrap_or_default();
            let mut detector = self.loop_detector.write().await;

            let is_search = crate::core::loop_detection::LoopDetector::is_search_tool(name);
            let is_search_shell = name == "ctx_shell" && {
                let cmd = args
                    .as_ref()
                    .and_then(|a| a.get("command"))
                    .and_then(|v| v.as_str())
                    .unwrap_or("");
                crate::core::loop_detection::LoopDetector::is_search_shell_command(cmd)
            };

            if is_search || is_search_shell {
                let search_pattern = args.and_then(|a| {
                    a.get("pattern")
                        .or_else(|| a.get("query"))
                        .and_then(|v| v.as_str())
                });
                let shell_pattern = if is_search_shell {
                    args.and_then(|a| a.get("command"))
                        .and_then(|v| v.as_str())
                        .and_then(helpers::extract_search_pattern_from_command)
                } else {
                    None
                };
                let pat = search_pattern.or(shell_pattern.as_deref());
                detector.record_search(name, &fp, pat)
            } else {
                detector.record_call(name, &fp)
            }
        };

        if throttle_result.level == crate::core::loop_detection::ThrottleLevel::Blocked {
            let msg = throttle_result.message.unwrap_or_default();
            return Ok(CallToolResult::success(vec![Content::text(msg)]));
        }

        let throttle_warning =
            if throttle_result.level == crate::core::loop_detection::ThrottleLevel::Reduced {
                throttle_result.message.clone()
            } else {
                None
            };

        let config = crate::core::config::Config::load();
        let minimal = config.minimal_overhead_effective();

        {
            use crate::core::budget_tracker::{BudgetLevel, BudgetTracker};
            let snap = BudgetTracker::global().check();
            if *snap.worst_level() == BudgetLevel::Exhausted
                && name != "ctx_session"
                && name != "ctx_cost"
                && name != "ctx_metrics"
            {
                for (dim, lvl, used, limit) in [
                    (
                        "tokens",
                        &snap.tokens.level,
                        format!("{}", snap.tokens.used),
                        format!("{}", snap.tokens.limit),
                    ),
                    (
                        "shell",
                        &snap.shell.level,
                        format!("{}", snap.shell.used),
                        format!("{}", snap.shell.limit),
                    ),
                    (
                        "cost",
                        &snap.cost.level,
                        format!("${:.2}", snap.cost.used_usd),
                        format!("${:.2}", snap.cost.limit_usd),
                    ),
                ] {
                    if *lvl == BudgetLevel::Exhausted {
                        crate::core::events::emit_budget_exhausted(&snap.role, dim, &used, &limit);
                    }
                }
                let msg = format!(
                    "[BUDGET EXHAUSTED] {}\n\
                     Use `ctx_session action=role` to check/switch roles, \
                     or `ctx_session action=reset` to start fresh.",
                    snap.format_compact()
                );
                tracing::warn!(tool = name, "{msg}");
                return Ok(CallToolResult::success(vec![Content::text(msg)]));
            }
        }

        if is_shell_tool_name(name) {
            crate::core::budget_tracker::BudgetTracker::global().record_shell();
        }

        let tool_start = std::time::Instant::now();
        let mut result_text = {
            use futures::FutureExt;
            use std::panic::AssertUnwindSafe;
            match AssertUnwindSafe(self.dispatch_tool(name, args, minimal))
                .catch_unwind()
                .await
            {
                Ok(Ok(text)) => text,
                Ok(Err(e)) => return Err(e),
                Err(panic_payload) => {
                    let detail = if let Some(s) = panic_payload.downcast_ref::<&str>() {
                        (*s).to_string()
                    } else if let Some(s) = panic_payload.downcast_ref::<String>() {
                        s.clone()
                    } else {
                        "unknown".to_string()
                    };
                    tracing::error!(tool = name, "Tool panicked: {detail}");
                    format!("ERROR: lean-ctx internal error in tool '{name}'.\n\
                             The MCP server is still running. Please retry or use a different approach.")
                }
            }
        };

        let is_raw_shell = name == "ctx_shell" && {
            let arg_raw = helpers::get_bool(args, "raw").unwrap_or(false);
            let arg_bypass = helpers::get_bool(args, "bypass").unwrap_or(false);
            arg_raw
                || arg_bypass
                || std::env::var("LEAN_CTX_DISABLED").is_ok()
                || std::env::var("LEAN_CTX_RAW").is_ok()
        };

        let pre_terse_len = result_text.len();
        let output_tokens = {
            let tokens = crate::core::tokens::count_tokens(&result_text) as u64;
            crate::core::budget_tracker::BudgetTracker::global().record_tokens(tokens);
            tokens
        };

        crate::core::anomaly::record_metric("tokens_per_call", output_tokens as f64);
        // Persist anomaly detector so dashboard state survives restarts.
        crate::core::anomaly::save();

        let budget_warning = {
            use crate::core::budget_tracker::{BudgetLevel, BudgetTracker};
            let snap = BudgetTracker::global().check();
            if *snap.worst_level() == BudgetLevel::Warning {
                for (dim, lvl, used, limit, pct) in [
                    (
                        "tokens",
                        &snap.tokens.level,
                        format!("{}", snap.tokens.used),
                        format!("{}", snap.tokens.limit),
                        snap.tokens.percent,
                    ),
                    (
                        "shell",
                        &snap.shell.level,
                        format!("{}", snap.shell.used),
                        format!("{}", snap.shell.limit),
                        snap.shell.percent,
                    ),
                    (
                        "cost",
                        &snap.cost.level,
                        format!("${:.2}", snap.cost.used_usd),
                        format!("${:.2}", snap.cost.limit_usd),
                        snap.cost.percent,
                    ),
                ] {
                    if *lvl == BudgetLevel::Warning {
                        crate::core::events::emit_budget_warning(
                            &snap.role, dim, &used, &limit, pct,
                        );
                    }
                }
                Some(format!("[BUDGET WARNING] {}", snap.format_compact()))
            } else {
                None
            }
        };

        let archive_hint = if minimal || is_raw_shell {
            None
        } else {
            use crate::core::archive;
            let archivable = matches!(
                name,
                "ctx_shell"
                    | "ctx_read"
                    | "ctx_multi_read"
                    | "ctx_smart_read"
                    | "ctx_execute"
                    | "ctx_search"
                    | "ctx_tree"
            );
            if archivable && archive::should_archive(&result_text) {
                let cmd = helpers::get_str(args, "command")
                    .or_else(|| helpers::get_str(args, "path"))
                    .unwrap_or_default();
                let session_id = self.session.read().await.id.clone();
                let to_store = crate::core::redaction::redact_text_if_enabled(&result_text);
                let tokens = crate::core::tokens::count_tokens(&to_store);
                archive::store(name, &cmd, &to_store, Some(&session_id))
                    .map(|id| archive::format_hint(&id, to_store.len(), tokens))
            } else {
                None
            }
        };

        let pre_compression = result_text.clone();
        let skip_terse = is_raw_shell
            || (name == "ctx_shell"
                && helpers::get_str(args, "command")
                    .is_some_and(|c| crate::shell::compress::has_structural_output(&c)));
        let compression = crate::core::config::CompressionLevel::effective(&config);
        if compression.is_active() && !skip_terse {
            let terse_result =
                crate::core::terse::pipeline::compress(&result_text, &compression, None);
            if terse_result.quality_passed && terse_result.savings_pct >= 1.0 {
                result_text = terse_result.output;
            }
        }

        if !is_raw_shell {
            let verify_cfg = crate::core::profiles::active_profile().verification;
            let vr = crate::core::output_verification::verify_output(
                &pre_compression,
                &result_text,
                &verify_cfg,
            );
            if !vr.warnings.is_empty() {
                let msg = format!("[VERIFY] {}", vr.format_compact());
                result_text = format!("{result_text}\n\n{msg}");
            }
        }

        if let Some(hint) = archive_hint {
            result_text = format!("{result_text}\n{hint}");
        }

        if !is_raw_shell {
            if let Some(ctx) = auto_context {
                result_text = format!("{ctx}\n\n{result_text}");
            }
        }

        if let Some(warning) = throttle_warning {
            result_text = format!("{result_text}\n\n{warning}");
        }

        if let Some(bw) = budget_warning {
            result_text = format!("{result_text}\n\n{bw}");
        }

        if !self
            .rules_stale_checked
            .swap(true, std::sync::atomic::Ordering::Relaxed)
        {
            let client = self.client_name.read().await.clone();
            if !client.is_empty() {
                if let Some(stale_msg) = crate::rules_inject::check_rules_freshness(&client) {
                    result_text = format!("{result_text}\n\n{stale_msg}");
                }
            }
        }

        {
            // Evaluate SLOs for observability (watch/dashboard), but keep tool outputs clean.
            let _ = crate::core::slo::evaluate();
        }

        if name == "ctx_read" {
            if minimal {
                let mut cache = self.cache.write().await;
                crate::tools::autonomy::maybe_auto_dedup(&self.autonomy, &mut cache, name);
            } else {
                let read_path = self
                    .resolve_path_or_passthrough(
                        &helpers::get_str(args, "path").unwrap_or_default(),
                    )
                    .await;
                let project_root = {
                    let session = self.session.read().await;
                    session.project_root.clone()
                };
                let mut cache = self.cache.write().await;
                let enrich = crate::tools::autonomy::enrich_after_read(
                    &self.autonomy,
                    &mut cache,
                    &read_path,
                    project_root.as_deref(),
                    None,
                    crate::tools::CrpMode::effective(),
                    false,
                );
                if let Some(hint) = enrich.related_hint {
                    result_text = format!("{result_text}\n{hint}");
                }
                crate::tools::autonomy::maybe_auto_dedup(&self.autonomy, &mut cache, name);
            }
        }

        if !minimal && !is_raw_shell && name == "ctx_shell" {
            let cmd = helpers::get_str(args, "command").unwrap_or_default();
            let calls = self.tool_calls.read().await;
            let last_original = calls.last().map_or(0, |c| c.original_tokens);
            drop(calls);
            let pre_hint_tokens = crate::core::tokens::count_tokens(&result_text);
            if let Some(hint) = crate::tools::autonomy::shell_efficiency_hint(
                &self.autonomy,
                &cmd,
                last_original,
                pre_hint_tokens,
            ) {
                result_text = format!("{result_text}\n{hint}");
            }
        }

        #[allow(clippy::cast_possible_truncation)]
        let output_token_count = if result_text.len() == pre_terse_len {
            output_tokens as usize
        } else {
            crate::core::tokens::count_tokens(&result_text)
        };
        let action = helpers::get_str(args, "action");

        // K-bounded staleness guard: warn if shared context has diverged.
        const K_STALENESS_BOUND: i64 = 10;
        if self.session_mode == crate::tools::SessionMode::Shared {
            if let Some(ref rt) = self.context_os {
                let latest = rt.bus.latest_id(&self.workspace_id, &self.channel_id);
                let cursor = self
                    .last_seen_event_id
                    .load(std::sync::atomic::Ordering::Relaxed);
                if cursor > 0 && latest - cursor > K_STALENESS_BOUND {
                    let gap = latest - cursor;
                    result_text = format!(
                        "[CONTEXT STALE] {gap} events happened since your last read. \
                         Use ctx_session(action=\"status\") to sync.\n\n{result_text}"
                    );
                }
                self.last_seen_event_id
                    .store(latest, std::sync::atomic::Ordering::Relaxed);
            }
        }

        {
            let input = helpers::canonical_args_string(args);
            let input_md5 = helpers::hash_fast(&input);
            let output_md5 = helpers::hash_fast(&result_text);
            let agent_id = self.agent_id.read().await.clone();
            let client_name = self.client_name.read().await.clone();
            let mut explicit_intent: Option<(
                crate::core::intent_protocol::IntentRecord,
                Option<String>,
                String,
            )> = None;

            let pending_session_save = {
                let empty_args = serde_json::Map::new();
                let args_map = args.unwrap_or(&empty_args);
                let mut session = self.session.write().await;
                session.record_tool_receipt(
                    name,
                    action.as_deref(),
                    &input_md5,
                    &output_md5,
                    agent_id.as_deref(),
                    Some(&client_name),
                );

                if let Some(intent) = crate::core::intent_protocol::infer_from_tool_call(
                    name,
                    action.as_deref(),
                    args_map,
                    session.project_root.as_deref(),
                ) {
                    let is_explicit =
                        intent.source == crate::core::intent_protocol::IntentSource::Explicit;
                    let root = session.project_root.clone();
                    let sid = session.id.clone();
                    session.record_intent(intent.clone());
                    if is_explicit {
                        explicit_intent = Some((intent, root, sid));
                    }
                }
                if session.should_save() {
                    session.prepare_save().ok()
                } else {
                    None
                }
            };

            if let Some(prepared) = pending_session_save {
                tokio::task::spawn_blocking(move || {
                    let _ = prepared.write_to_disk();
                });
            }

            if let Some((intent, root, session_id)) = explicit_intent {
                let _ = crate::core::intent_protocol::apply_side_effects(
                    &intent,
                    root.as_deref(),
                    &session_id,
                );
            }

            if self.autonomy.is_enabled() {
                let (calls, project_root) = {
                    let session = self.session.read().await;
                    (session.stats.total_tool_calls, session.project_root.clone())
                };

                if let Some(root) = project_root {
                    if crate::tools::autonomy::should_auto_consolidate(&self.autonomy, calls) {
                        let root_clone = root.clone();
                        tokio::task::spawn_blocking(move || {
                            let _ = crate::core::consolidation_engine::consolidate_latest(
                                &root_clone,
                                crate::core::consolidation_engine::ConsolidationBudgets::default(),
                            );
                        });
                    }
                }
            }

            let agent_key = agent_id.unwrap_or_else(|| "unknown".to_string());
            let input_token_count = crate::core::tokens::count_tokens(&input) as u64;
            let output_token_count_u64 = output_token_count as u64;
            let name_owned = name.to_string();
            tokio::task::spawn_blocking(move || {
                let pricing = crate::core::gain::model_pricing::ModelPricing::load();
                let quote = pricing.quote_from_env_or_agent_type(&client_name);
                let cost_usd =
                    quote
                        .cost
                        .estimate_usd(input_token_count, output_token_count_u64, 0, 0);
                crate::core::budget_tracker::BudgetTracker::global().record_cost_usd(cost_usd);

                let mut store = crate::core::a2a::cost_attribution::CostStore::load();
                store.record_tool_call(
                    &agent_key,
                    &client_name,
                    &name_owned,
                    input_token_count,
                    output_token_count_u64,
                    0,
                );
                let _ = store.save();
            });
        }

        // Context Bus: conflict detection for knowledge writes in shared mode.
        if self.session_mode == crate::tools::SessionMode::Shared
            && name == "ctx_knowledge"
            && action.as_deref() == Some("remember")
        {
            if let Some(ref rt) = self.context_os {
                let my_agent = self.agent_id.read().await.clone();
                let category = helpers::get_str(args, "category");
                let key = helpers::get_str(args, "key");
                if let (Some(ref cat), Some(ref k)) = (&category, &key) {
                    let recent = rt.bus.recent_by_kind(
                        &self.workspace_id,
                        &self.channel_id,
                        "knowledge_remembered",
                        20,
                    );
                    for ev in &recent {
                        let p = &ev.payload;
                        let ev_cat = p.get("category").and_then(|v| v.as_str());
                        let ev_key = p.get("key").and_then(|v| v.as_str());
                        let ev_actor = ev.actor.as_deref();
                        if ev_cat == Some(cat.as_str())
                            && ev_key == Some(k.as_str())
                            && ev_actor != my_agent.as_deref()
                        {
                            let other = ev_actor.unwrap_or("unknown");
                            result_text = format!(
                                "[CONFLICT] Agent '{other}' recently wrote to the same knowledge key \
                                 '{cat}/{k}'. Review before proceeding.\n\n{result_text}"
                            );
                            break;
                        }
                    }
                }
            }
        }

        // Context OS: persist shared session + publish events.
        if self.session_mode == crate::tools::SessionMode::Shared {
            let ws = self.workspace_id.clone();
            let ch = self.channel_id.clone();
            let rt = self.context_os.clone();
            let agent = self.agent_id.read().await.clone();
            let tool = name.to_string();
            let tool_action = action.clone();
            let tool_path = helpers::get_str(args, "path");
            let tool_category = helpers::get_str(args, "category");
            let tool_key = helpers::get_str(args, "key");
            let session_snapshot = self.session.read().await.clone();
            let session_task = session_snapshot.task.clone();
            tokio::task::spawn_blocking(move || {
                let Some(rt) = rt else {
                    return;
                };
                let Some(root) = session_snapshot.project_root.as_deref() else {
                    return;
                };
                rt.shared_sessions
                    .persist_best_effort(root, &ws, &ch, &session_snapshot);
                rt.metrics.record_session_persisted();

                let mut base_payload = serde_json::json!({
                    "tool": tool,
                    "action": tool_action,
                });
                if let Some(ref p) = tool_path {
                    base_payload["path"] = serde_json::Value::String(p.clone());
                }
                if let Some(ref c) = tool_category {
                    base_payload["category"] = serde_json::Value::String(c.clone());
                }
                if let Some(ref k) = tool_key {
                    base_payload["key"] = serde_json::Value::String(k.clone());
                }
                if let Some(ref t) = session_task {
                    base_payload["reasoning"] = serde_json::Value::String(t.description.clone());
                }

                if rt
                    .bus
                    .append(
                        &ws,
                        &ch,
                        &crate::core::context_os::ContextEventKindV1::ToolCallRecorded,
                        agent.as_deref(),
                        base_payload.clone(),
                    )
                    .is_some()
                {
                    rt.metrics.record_event_appended();
                    rt.metrics.record_event_broadcast();
                }

                if let Some(secondary) =
                    crate::core::context_os::secondary_event_kind(&tool, tool_action.as_deref())
                {
                    if rt
                        .bus
                        .append(&ws, &ch, &secondary, agent.as_deref(), base_payload)
                        .is_some()
                    {
                        rt.metrics.record_event_appended();
                        rt.metrics.record_event_broadcast();
                    }
                }
            });
        }

        let skip_checkpoint = minimal
            || matches!(
                name,
                "ctx_compress"
                    | "ctx_metrics"
                    | "ctx_benchmark"
                    | "ctx_analyze"
                    | "ctx_cache"
                    | "ctx_discover"
                    | "ctx_dedup"
                    | "ctx_session"
                    | "ctx_knowledge"
                    | "ctx_agent"
                    | "ctx_share"
                    | "ctx_wrapped"
                    | "ctx_overview"
                    | "ctx_preload"
                    | "ctx_cost"
                    | "ctx_gain"
                    | "ctx_heatmap"
                    | "ctx_task"
                    | "ctx_impact"
                    | "ctx_architecture"
                    | "ctx_smells"
                    | "ctx_workflow"
            );

        if !skip_checkpoint && self.increment_and_check() {
            if let Some(checkpoint) = self.auto_checkpoint().await {
                let interval = LeanCtxServer::checkpoint_interval_effective();
                let combined = format!(
                    "{result_text}\n\n--- AUTO CHECKPOINT (every {interval} calls) ---\n{checkpoint}"
                );
                return Ok(CallToolResult::success(vec![Content::text(combined)]));
            }
        }

        let tool_duration_ms = tool_start.elapsed().as_millis() as u64;
        if tool_duration_ms > 100 {
            LeanCtxServer::append_tool_call_log(
                name,
                tool_duration_ms,
                0,
                0,
                None,
                &chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string(),
            );
        }

        let current_count = self.call_count.load(std::sync::atomic::Ordering::Relaxed);
        if current_count > 0 && current_count.is_multiple_of(100) {
            std::thread::spawn(crate::cloud_sync::cloud_background_tasks);
        }

        Ok(CallToolResult::success(vec![Content::text(result_text)]))
    }
}

pub fn build_instructions_for_test(crp_mode: CrpMode) -> String {
    crate::instructions::build_instructions_for_test(crp_mode)
}

pub fn build_claude_code_instructions_for_test() -> String {
    crate::instructions::claude_code_instructions()
}

const PROJECT_MARKERS: &[&str] = &[
    ".git",
    "Cargo.toml",
    "package.json",
    "go.mod",
    "pyproject.toml",
    "setup.py",
    "pom.xml",
    "build.gradle",
    "Makefile",
    ".lean-ctx.toml",
];

fn has_project_marker(dir: &std::path::Path) -> bool {
    PROJECT_MARKERS.iter().any(|m| dir.join(m).exists())
}

fn is_home_or_agent_dir(dir: &std::path::Path) -> bool {
    if let Some(home) = dirs::home_dir() {
        if dir == home {
            return true;
        }
    }
    let dir_str = dir.to_string_lossy();
    dir_str.ends_with("/.claude")
        || dir_str.ends_with("/.codex")
        || dir_str.contains("/.claude/")
        || dir_str.contains("/.codex/")
}

fn git_toplevel_from(dir: &std::path::Path) -> Option<String> {
    std::process::Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .current_dir(dir)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .output()
        .ok()
        .and_then(|o| {
            if o.status.success() {
                String::from_utf8(o.stdout)
                    .ok()
                    .map(|s| s.trim().to_string())
            } else {
                None
            }
        })
}

pub fn derive_project_root_from_cwd() -> Option<String> {
    let cwd = std::env::current_dir().ok()?;
    let canonical = crate::core::pathutil::safe_canonicalize_or_self(&cwd);

    if is_home_or_agent_dir(&canonical) {
        return git_toplevel_from(&canonical);
    }

    if has_project_marker(&canonical) {
        return Some(canonical.to_string_lossy().to_string());
    }

    if let Some(git_root) = git_toplevel_from(&canonical) {
        return Some(git_root);
    }

    if let Some(root) = detect_multi_root_workspace(&canonical) {
        return Some(root);
    }

    None
}

/// Detect a multi-root workspace: a directory that has no project markers
/// itself, but contains child directories that do. In this case, use the
/// parent as jail root and auto-allow all child projects via LEAN_CTX_ALLOW_PATH.
fn detect_multi_root_workspace(dir: &std::path::Path) -> Option<String> {
    let entries = std::fs::read_dir(dir).ok()?;
    let mut child_projects: Vec<String> = Vec::new();

    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() && has_project_marker(&path) {
            let canonical = crate::core::pathutil::safe_canonicalize_or_self(&path);
            child_projects.push(canonical.to_string_lossy().to_string());
        }
    }

    if child_projects.len() >= 2 {
        let existing = std::env::var("LEAN_CTX_ALLOW_PATH").unwrap_or_default();
        let sep = if cfg!(windows) { ";" } else { ":" };
        let merged = if existing.is_empty() {
            child_projects.join(sep)
        } else {
            format!("{existing}{sep}{}", child_projects.join(sep))
        };
        std::env::set_var("LEAN_CTX_ALLOW_PATH", &merged);
        tracing::info!(
            "Multi-root workspace detected at {}: auto-allowing {} child projects",
            dir.display(),
            child_projects.len()
        );
        return Some(dir.to_string_lossy().to_string());
    }

    None
}

pub fn tool_descriptions_for_test() -> Vec<(&'static str, &'static str)> {
    crate::tool_defs::list_all_tool_defs()
        .into_iter()
        .map(|(name, desc, _)| (name, desc))
        .collect()
}

pub fn tool_schemas_json_for_test() -> String {
    crate::tool_defs::list_all_tool_defs()
        .iter()
        .map(|(name, _, schema)| format!("{name}: {schema}"))
        .collect::<Vec<_>>()
        .join("\n")
}

fn is_shell_tool_name(name: &str) -> bool {
    matches!(name, "ctx_shell" | "ctx_execute")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn project_markers_detected() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("myproject");
        std::fs::create_dir_all(&root).unwrap();
        assert!(!has_project_marker(&root));

        std::fs::create_dir(root.join(".git")).unwrap();
        assert!(has_project_marker(&root));
    }

    #[test]
    fn home_dir_detected_as_agent_dir() {
        if let Some(home) = dirs::home_dir() {
            assert!(is_home_or_agent_dir(&home));
        }
    }

    #[test]
    fn agent_dirs_detected() {
        let claude = std::path::PathBuf::from("/home/user/.claude");
        assert!(is_home_or_agent_dir(&claude));
        let codex = std::path::PathBuf::from("/home/user/.codex");
        assert!(is_home_or_agent_dir(&codex));
        let project = std::path::PathBuf::from("/home/user/projects/myapp");
        assert!(!is_home_or_agent_dir(&project));
    }

    #[test]
    fn test_unified_tool_count() {
        let tools = crate::tool_defs::unified_tool_defs();
        assert_eq!(tools.len(), 5, "Expected 5 unified tools");
    }

    #[test]
    fn test_granular_tool_count() {
        let tools = crate::tool_defs::granular_tool_defs();
        assert!(tools.len() >= 25, "Expected at least 25 granular tools");
    }

    #[test]
    fn disabled_tools_filters_list() {
        let all = crate::tool_defs::granular_tool_defs();
        let total = all.len();
        let disabled = ["ctx_graph".to_string(), "ctx_agent".to_string()];
        let filtered: Vec<_> = all
            .into_iter()
            .filter(|t| !disabled.iter().any(|d| t.name.as_ref() == d.as_str()))
            .collect();
        assert_eq!(filtered.len(), total - 2);
        assert!(!filtered.iter().any(|t| t.name.as_ref() == "ctx_graph"));
        assert!(!filtered.iter().any(|t| t.name.as_ref() == "ctx_agent"));
    }

    #[test]
    fn empty_disabled_tools_returns_all() {
        let all = crate::tool_defs::granular_tool_defs();
        let total = all.len();
        let disabled: Vec<String> = vec![];
        let filtered: Vec<_> = all
            .into_iter()
            .filter(|t| !disabled.iter().any(|d| t.name.as_ref() == d.as_str()))
            .collect();
        assert_eq!(filtered.len(), total);
    }

    #[test]
    fn misspelled_disabled_tool_is_silently_ignored() {
        let all = crate::tool_defs::granular_tool_defs();
        let total = all.len();
        let disabled = ["ctx_nonexistent_tool".to_string()];
        let filtered: Vec<_> = all
            .into_iter()
            .filter(|t| !disabled.iter().any(|d| t.name.as_ref() == d.as_str()))
            .collect();
        assert_eq!(filtered.len(), total);
    }

    #[test]
    fn detect_multi_root_workspace_with_child_projects() {
        let tmp = tempfile::tempdir().unwrap();
        let workspace = tmp.path().join("workspace");
        std::fs::create_dir_all(&workspace).unwrap();

        let proj_a = workspace.join("project-a");
        let proj_b = workspace.join("project-b");
        std::fs::create_dir_all(proj_a.join(".git")).unwrap();
        std::fs::create_dir_all(&proj_b).unwrap();
        std::fs::write(proj_b.join("package.json"), "{}").unwrap();

        let result = detect_multi_root_workspace(&workspace);
        assert!(
            result.is_some(),
            "should detect workspace with 2 child projects"
        );

        std::env::remove_var("LEAN_CTX_ALLOW_PATH");
    }

    #[test]
    fn detect_multi_root_workspace_returns_none_for_single_project() {
        let tmp = tempfile::tempdir().unwrap();
        let workspace = tmp.path().join("workspace");
        std::fs::create_dir_all(&workspace).unwrap();

        let proj_a = workspace.join("project-a");
        std::fs::create_dir_all(proj_a.join(".git")).unwrap();

        let result = detect_multi_root_workspace(&workspace);
        assert!(
            result.is_none(),
            "should not detect workspace with only 1 child project"
        );
    }
}
