rumdl_lib/lsp/
server.rs

1//! Main Language Server Protocol server implementation for rumdl
2//!
3//! This module implements the core LSP server following Ruff's architecture.
4//! It provides real-time markdown linting, diagnostics, and code actions.
5
6use std::collections::HashMap;
7use std::path::PathBuf;
8use std::sync::Arc;
9
10use anyhow::Result;
11use tokio::sync::RwLock;
12use tower_lsp::jsonrpc::Result as JsonRpcResult;
13use tower_lsp::lsp_types::*;
14use tower_lsp::{Client, LanguageServer};
15
16use crate::config::Config;
17use crate::lint;
18use crate::lsp::types::{RumdlLspConfig, warning_to_code_actions, warning_to_diagnostic};
19use crate::rule::Rule;
20use crate::rules;
21
22/// Represents a document in the LSP server's cache
23#[derive(Clone, Debug, PartialEq)]
24struct DocumentEntry {
25    /// The document content
26    content: String,
27    /// Version number from the editor (None for disk-loaded documents)
28    version: Option<i32>,
29    /// Whether the document was loaded from disk (true) or opened in editor (false)
30    from_disk: bool,
31}
32
33/// Cache entry for resolved configuration
34#[derive(Clone, Debug)]
35pub(crate) struct ConfigCacheEntry {
36    /// The resolved configuration
37    pub(crate) config: Config,
38    /// Config file path that was loaded (for invalidation)
39    pub(crate) config_file: Option<PathBuf>,
40    /// True if this entry came from the global/user fallback (no project config)
41    pub(crate) from_global_fallback: bool,
42}
43
44/// Main LSP server for rumdl
45///
46/// Following Ruff's pattern, this server provides:
47/// - Real-time diagnostics as users type
48/// - Code actions for automatic fixes
49/// - Configuration management
50/// - Multi-file support
51/// - Multi-root workspace support with per-file config resolution
52#[derive(Clone)]
53pub struct RumdlLanguageServer {
54    client: Client,
55    /// Configuration for the LSP server
56    config: Arc<RwLock<RumdlLspConfig>>,
57    /// Rumdl core configuration (fallback/default)
58    #[cfg_attr(test, allow(dead_code))]
59    pub(crate) rumdl_config: Arc<RwLock<Config>>,
60    /// Document store for open files and cached disk files
61    documents: Arc<RwLock<HashMap<Url, DocumentEntry>>>,
62    /// Workspace root folders from the client
63    #[cfg_attr(test, allow(dead_code))]
64    pub(crate) workspace_roots: Arc<RwLock<Vec<PathBuf>>>,
65    /// Configuration cache: maps directory path to resolved config
66    /// Key is the directory where config search started (file's parent dir)
67    #[cfg_attr(test, allow(dead_code))]
68    pub(crate) config_cache: Arc<RwLock<HashMap<PathBuf, ConfigCacheEntry>>>,
69}
70
71impl RumdlLanguageServer {
72    pub fn new(client: Client) -> Self {
73        Self {
74            client,
75            config: Arc::new(RwLock::new(RumdlLspConfig::default())),
76            rumdl_config: Arc::new(RwLock::new(Config::default())),
77            documents: Arc::new(RwLock::new(HashMap::new())),
78            workspace_roots: Arc::new(RwLock::new(Vec::new())),
79            config_cache: Arc::new(RwLock::new(HashMap::new())),
80        }
81    }
82
83    /// Get document content, either from cache or by reading from disk
84    ///
85    /// This method first checks if the document is in the cache (opened in editor).
86    /// If not found, it attempts to read the file from disk and caches it for
87    /// future requests.
88    async fn get_document_content(&self, uri: &Url) -> Option<String> {
89        // First check the cache
90        {
91            let docs = self.documents.read().await;
92            if let Some(entry) = docs.get(uri) {
93                return Some(entry.content.clone());
94            }
95        }
96
97        // If not in cache and it's a file URI, try to read from disk
98        if let Ok(path) = uri.to_file_path() {
99            if let Ok(content) = tokio::fs::read_to_string(&path).await {
100                // Cache the document for future requests
101                let entry = DocumentEntry {
102                    content: content.clone(),
103                    version: None,
104                    from_disk: true,
105                };
106
107                let mut docs = self.documents.write().await;
108                docs.insert(uri.clone(), entry);
109
110                log::debug!("Loaded document from disk and cached: {uri}");
111                return Some(content);
112            } else {
113                log::debug!("Failed to read file from disk: {uri}");
114            }
115        }
116
117        None
118    }
119
120    /// Apply LSP config overrides to the filtered rules
121    fn apply_lsp_config_overrides(
122        &self,
123        mut filtered_rules: Vec<Box<dyn Rule>>,
124        lsp_config: &RumdlLspConfig,
125    ) -> Vec<Box<dyn Rule>> {
126        // Apply enable_rules override from LSP config (if specified, only these rules are active)
127        if let Some(enable) = &lsp_config.enable_rules
128            && !enable.is_empty()
129        {
130            let enable_set: std::collections::HashSet<String> = enable.iter().cloned().collect();
131            filtered_rules.retain(|rule| enable_set.contains(rule.name()));
132        }
133
134        // Apply disable_rules override from LSP config
135        if let Some(disable) = &lsp_config.disable_rules
136            && !disable.is_empty()
137        {
138            let disable_set: std::collections::HashSet<String> = disable.iter().cloned().collect();
139            filtered_rules.retain(|rule| !disable_set.contains(rule.name()));
140        }
141
142        filtered_rules
143    }
144
145    /// Check if a file URI should be excluded based on exclude patterns
146    async fn should_exclude_uri(&self, uri: &Url) -> bool {
147        // Try to convert URI to file path
148        let file_path = match uri.to_file_path() {
149            Ok(path) => path,
150            Err(_) => return false, // If we can't get a path, don't exclude
151        };
152
153        // Resolve configuration for this specific file to get its exclude patterns
154        let rumdl_config = self.resolve_config_for_file(&file_path).await;
155        let exclude_patterns = &rumdl_config.global.exclude;
156
157        // If no exclude patterns, don't exclude
158        if exclude_patterns.is_empty() {
159            return false;
160        }
161
162        // Convert path to relative path for pattern matching
163        // This matches the CLI behavior in find_markdown_files
164        let path_to_check = if file_path.is_absolute() {
165            // Try to make it relative to the current directory
166            if let Ok(cwd) = std::env::current_dir() {
167                // Canonicalize both paths to handle symlinks
168                if let (Ok(canonical_cwd), Ok(canonical_path)) = (cwd.canonicalize(), file_path.canonicalize()) {
169                    if let Ok(relative) = canonical_path.strip_prefix(&canonical_cwd) {
170                        relative.to_string_lossy().to_string()
171                    } else {
172                        // Path is absolute but not under cwd
173                        file_path.to_string_lossy().to_string()
174                    }
175                } else {
176                    // Canonicalization failed
177                    file_path.to_string_lossy().to_string()
178                }
179            } else {
180                file_path.to_string_lossy().to_string()
181            }
182        } else {
183            // Already relative
184            file_path.to_string_lossy().to_string()
185        };
186
187        // Check if path matches any exclude pattern
188        for pattern in exclude_patterns {
189            if let Ok(glob) = globset::Glob::new(pattern) {
190                let matcher = glob.compile_matcher();
191                if matcher.is_match(&path_to_check) {
192                    log::debug!("Excluding file from LSP linting: {path_to_check}");
193                    return true;
194                }
195            }
196        }
197
198        false
199    }
200
201    /// Lint a document and return diagnostics
202    pub(crate) async fn lint_document(&self, uri: &Url, text: &str) -> Result<Vec<Diagnostic>> {
203        let config_guard = self.config.read().await;
204
205        // Skip linting if disabled
206        if !config_guard.enable_linting {
207            return Ok(Vec::new());
208        }
209
210        let lsp_config = config_guard.clone();
211        drop(config_guard); // Release config lock early
212
213        // Check if file should be excluded based on exclude patterns
214        if self.should_exclude_uri(uri).await {
215            return Ok(Vec::new());
216        }
217
218        // Resolve configuration for this specific file
219        let rumdl_config = if let Ok(file_path) = uri.to_file_path() {
220            self.resolve_config_for_file(&file_path).await
221        } else {
222            // Fallback to global config for non-file URIs
223            (*self.rumdl_config.read().await).clone()
224        };
225
226        let all_rules = rules::all_rules(&rumdl_config);
227        let flavor = rumdl_config.markdown_flavor();
228
229        // Use the standard filter_rules function which respects config's disabled rules
230        let mut filtered_rules = rules::filter_rules(&all_rules, &rumdl_config.global);
231
232        // Apply LSP config overrides (select_rules, ignore_rules from VSCode settings)
233        filtered_rules = self.apply_lsp_config_overrides(filtered_rules, &lsp_config);
234
235        // Run rumdl linting with the configured flavor
236        match crate::lint(text, &filtered_rules, false, flavor) {
237            Ok(warnings) => {
238                let diagnostics = warnings.iter().map(warning_to_diagnostic).collect();
239                Ok(diagnostics)
240            }
241            Err(e) => {
242                log::error!("Failed to lint document {uri}: {e}");
243                Ok(Vec::new())
244            }
245        }
246    }
247
248    /// Update diagnostics for a document
249    async fn update_diagnostics(&self, uri: Url, text: String) {
250        // Get the document version if available
251        let version = {
252            let docs = self.documents.read().await;
253            docs.get(&uri).and_then(|entry| entry.version)
254        };
255
256        match self.lint_document(&uri, &text).await {
257            Ok(diagnostics) => {
258                self.client.publish_diagnostics(uri, diagnostics, version).await;
259            }
260            Err(e) => {
261                log::error!("Failed to update diagnostics: {e}");
262            }
263        }
264    }
265
266    /// Apply all available fixes to a document
267    async fn apply_all_fixes(&self, uri: &Url, text: &str) -> Result<Option<String>> {
268        // Check if file should be excluded based on exclude patterns
269        if self.should_exclude_uri(uri).await {
270            return Ok(None);
271        }
272
273        let config_guard = self.config.read().await;
274        let lsp_config = config_guard.clone();
275        drop(config_guard);
276
277        // Resolve configuration for this specific file
278        let rumdl_config = if let Ok(file_path) = uri.to_file_path() {
279            self.resolve_config_for_file(&file_path).await
280        } else {
281            // Fallback to global config for non-file URIs
282            (*self.rumdl_config.read().await).clone()
283        };
284
285        let all_rules = rules::all_rules(&rumdl_config);
286        let flavor = rumdl_config.markdown_flavor();
287
288        // Use the standard filter_rules function which respects config's disabled rules
289        let mut filtered_rules = rules::filter_rules(&all_rules, &rumdl_config.global);
290
291        // Apply LSP config overrides (select_rules, ignore_rules from VSCode settings)
292        filtered_rules = self.apply_lsp_config_overrides(filtered_rules, &lsp_config);
293
294        // First, run lint to get active warnings (respecting ignore comments)
295        // This tells us which rules actually have unfixed issues
296        let mut rules_with_warnings = std::collections::HashSet::new();
297        let mut fixed_text = text.to_string();
298
299        match lint(&fixed_text, &filtered_rules, false, flavor) {
300            Ok(warnings) => {
301                for warning in warnings {
302                    if let Some(rule_name) = &warning.rule_name {
303                        rules_with_warnings.insert(rule_name.clone());
304                    }
305                }
306            }
307            Err(e) => {
308                log::warn!("Failed to lint document for auto-fix: {e}");
309                return Ok(None);
310            }
311        }
312
313        // Early return if no warnings to fix
314        if rules_with_warnings.is_empty() {
315            return Ok(None);
316        }
317
318        // Only apply fixes for rules that have active warnings
319        let mut any_changes = false;
320
321        for rule in &filtered_rules {
322            // Skip rules that don't have any active warnings
323            if !rules_with_warnings.contains(rule.name()) {
324                continue;
325            }
326
327            let ctx = crate::lint_context::LintContext::new(&fixed_text, flavor);
328            match rule.fix(&ctx) {
329                Ok(new_text) => {
330                    if new_text != fixed_text {
331                        fixed_text = new_text;
332                        any_changes = true;
333                    }
334                }
335                Err(e) => {
336                    // Only log if it's an actual error, not just "rule doesn't support auto-fix"
337                    let msg = e.to_string();
338                    if !msg.contains("does not support automatic fixing") {
339                        log::warn!("Failed to apply fix for rule {}: {}", rule.name(), e);
340                    }
341                }
342            }
343        }
344
345        if any_changes { Ok(Some(fixed_text)) } else { Ok(None) }
346    }
347
348    /// Get the end position of a document
349    fn get_end_position(&self, text: &str) -> Position {
350        let mut line = 0u32;
351        let mut character = 0u32;
352
353        for ch in text.chars() {
354            if ch == '\n' {
355                line += 1;
356                character = 0;
357            } else {
358                character += 1;
359            }
360        }
361
362        Position { line, character }
363    }
364
365    /// Get code actions for diagnostics at a position
366    async fn get_code_actions(&self, uri: &Url, text: &str, range: Range) -> Result<Vec<CodeAction>> {
367        let config_guard = self.config.read().await;
368        let lsp_config = config_guard.clone();
369        drop(config_guard);
370
371        // Resolve configuration for this specific file
372        let rumdl_config = if let Ok(file_path) = uri.to_file_path() {
373            self.resolve_config_for_file(&file_path).await
374        } else {
375            // Fallback to global config for non-file URIs
376            (*self.rumdl_config.read().await).clone()
377        };
378
379        let all_rules = rules::all_rules(&rumdl_config);
380        let flavor = rumdl_config.markdown_flavor();
381
382        // Use the standard filter_rules function which respects config's disabled rules
383        let mut filtered_rules = rules::filter_rules(&all_rules, &rumdl_config.global);
384
385        // Apply LSP config overrides (select_rules, ignore_rules from VSCode settings)
386        filtered_rules = self.apply_lsp_config_overrides(filtered_rules, &lsp_config);
387
388        match crate::lint(text, &filtered_rules, false, flavor) {
389            Ok(warnings) => {
390                let mut actions = Vec::new();
391                let mut fixable_count = 0;
392
393                for warning in &warnings {
394                    // Check if warning is within the requested range
395                    let warning_line = (warning.line.saturating_sub(1)) as u32;
396                    if warning_line >= range.start.line && warning_line <= range.end.line {
397                        // Get all code actions for this warning (fix + ignore actions)
398                        let mut warning_actions = warning_to_code_actions(warning, uri, text);
399                        actions.append(&mut warning_actions);
400
401                        if warning.fix.is_some() {
402                            fixable_count += 1;
403                        }
404                    }
405                }
406
407                // Add "Fix all" action if there are multiple fixable issues in range
408                if fixable_count > 1 {
409                    // Count total fixable issues in the document
410                    let total_fixable = warnings.iter().filter(|w| w.fix.is_some()).count();
411
412                    if let Ok(fixed_content) = crate::utils::fix_utils::apply_warning_fixes(text, &warnings)
413                        && fixed_content != text
414                    {
415                        // Calculate proper end position
416                        let mut line = 0u32;
417                        let mut character = 0u32;
418                        for ch in text.chars() {
419                            if ch == '\n' {
420                                line += 1;
421                                character = 0;
422                            } else {
423                                character += 1;
424                            }
425                        }
426
427                        let fix_all_action = CodeAction {
428                            title: format!("Fix all rumdl issues ({total_fixable} fixable)"),
429                            kind: Some(CodeActionKind::QUICKFIX),
430                            diagnostics: Some(Vec::new()),
431                            edit: Some(WorkspaceEdit {
432                                changes: Some(
433                                    [(
434                                        uri.clone(),
435                                        vec![TextEdit {
436                                            range: Range {
437                                                start: Position { line: 0, character: 0 },
438                                                end: Position { line, character },
439                                            },
440                                            new_text: fixed_content,
441                                        }],
442                                    )]
443                                    .into_iter()
444                                    .collect(),
445                                ),
446                                ..Default::default()
447                            }),
448                            command: None,
449                            is_preferred: Some(true),
450                            disabled: None,
451                            data: None,
452                        };
453
454                        // Insert at the beginning to make it prominent
455                        actions.insert(0, fix_all_action);
456                    }
457                }
458
459                Ok(actions)
460            }
461            Err(e) => {
462                log::error!("Failed to get code actions: {e}");
463                Ok(Vec::new())
464            }
465        }
466    }
467
468    /// Load or reload rumdl configuration from files
469    async fn load_configuration(&self, notify_client: bool) {
470        let config_guard = self.config.read().await;
471        let explicit_config_path = config_guard.config_path.clone();
472        drop(config_guard);
473
474        // Use the same discovery logic as CLI but with LSP-specific error handling
475        match Self::load_config_for_lsp(explicit_config_path.as_deref()) {
476            Ok(sourced_config) => {
477                let loaded_files = sourced_config.loaded_files.clone();
478                *self.rumdl_config.write().await = sourced_config.into();
479
480                if !loaded_files.is_empty() {
481                    let message = format!("Loaded rumdl config from: {}", loaded_files.join(", "));
482                    log::info!("{message}");
483                    if notify_client {
484                        self.client.log_message(MessageType::INFO, &message).await;
485                    }
486                } else {
487                    log::info!("Using default rumdl configuration (no config files found)");
488                }
489            }
490            Err(e) => {
491                let message = format!("Failed to load rumdl config: {e}");
492                log::warn!("{message}");
493                if notify_client {
494                    self.client.log_message(MessageType::WARNING, &message).await;
495                }
496                // Use default configuration
497                *self.rumdl_config.write().await = crate::config::Config::default();
498            }
499        }
500    }
501
502    /// Reload rumdl configuration from files (with client notification)
503    async fn reload_configuration(&self) {
504        self.load_configuration(true).await;
505    }
506
507    /// Load configuration for LSP - similar to CLI loading but returns Result
508    fn load_config_for_lsp(
509        config_path: Option<&str>,
510    ) -> Result<crate::config::SourcedConfig, crate::config::ConfigError> {
511        // Use the same configuration loading as the CLI
512        crate::config::SourcedConfig::load_with_discovery(config_path, None, false)
513    }
514
515    /// Resolve configuration for a specific file
516    ///
517    /// This method searches for a configuration file starting from the file's directory
518    /// and walking up the directory tree until a workspace root is hit or a config is found.
519    ///
520    /// Results are cached to avoid repeated filesystem access.
521    pub(crate) async fn resolve_config_for_file(&self, file_path: &std::path::Path) -> Config {
522        // Get the directory to start searching from
523        let search_dir = file_path.parent().unwrap_or(file_path).to_path_buf();
524
525        // Check cache first
526        {
527            let cache = self.config_cache.read().await;
528            if let Some(entry) = cache.get(&search_dir) {
529                let source_owned: String; // ensure owned storage for logging
530                let source: &str = if entry.from_global_fallback {
531                    "global/user fallback"
532                } else if let Some(path) = &entry.config_file {
533                    source_owned = path.to_string_lossy().to_string();
534                    &source_owned
535                } else {
536                    "<unknown>"
537                };
538                log::debug!(
539                    "Config cache hit for directory: {} (loaded from: {})",
540                    search_dir.display(),
541                    source
542                );
543                return entry.config.clone();
544            }
545        }
546
547        // Cache miss - need to search for config
548        log::debug!(
549            "Config cache miss for directory: {}, searching for config...",
550            search_dir.display()
551        );
552
553        // Try to find workspace root for this file
554        let workspace_root = {
555            let workspace_roots = self.workspace_roots.read().await;
556            workspace_roots
557                .iter()
558                .find(|root| search_dir.starts_with(root))
559                .map(|p| p.to_path_buf())
560        };
561
562        // Search upward from the file's directory
563        let mut current_dir = search_dir.clone();
564        let mut found_config: Option<(Config, Option<PathBuf>)> = None;
565
566        loop {
567            // Try to find a config file in the current directory
568            const CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml", "pyproject.toml", ".markdownlint.json"];
569
570            for config_file_name in CONFIG_FILES {
571                let config_path = current_dir.join(config_file_name);
572                if config_path.exists() {
573                    log::debug!("Found config file: {}", config_path.display());
574
575                    // Load the config
576                    if let Ok(sourced) = Self::load_config_for_lsp(Some(config_path.to_str().unwrap())) {
577                        found_config = Some((sourced.into(), Some(config_path)));
578                        break;
579                    }
580                }
581            }
582
583            if found_config.is_some() {
584                break;
585            }
586
587            // Check if we've hit a workspace root
588            if let Some(ref root) = workspace_root
589                && &current_dir == root
590            {
591                log::debug!("Hit workspace root without finding config: {}", root.display());
592                break;
593            }
594
595            // Move up to parent directory
596            if let Some(parent) = current_dir.parent() {
597                current_dir = parent.to_path_buf();
598            } else {
599                // Hit filesystem root
600                break;
601            }
602        }
603
604        // Use found config or fall back to global/user config loaded at initialization
605        let (config, config_file) = if let Some((cfg, path)) = found_config {
606            (cfg, path)
607        } else {
608            log::debug!("No project config found; using global/user fallback config");
609            let fallback = self.rumdl_config.read().await.clone();
610            (fallback, None)
611        };
612
613        // Cache the result
614        let from_global = config_file.is_none();
615        let entry = ConfigCacheEntry {
616            config: config.clone(),
617            config_file,
618            from_global_fallback: from_global,
619        };
620
621        self.config_cache.write().await.insert(search_dir, entry);
622
623        config
624    }
625}
626
627#[tower_lsp::async_trait]
628impl LanguageServer for RumdlLanguageServer {
629    async fn initialize(&self, params: InitializeParams) -> JsonRpcResult<InitializeResult> {
630        log::info!("Initializing rumdl Language Server");
631
632        // Parse client capabilities and configuration
633        if let Some(options) = params.initialization_options
634            && let Ok(config) = serde_json::from_value::<RumdlLspConfig>(options)
635        {
636            *self.config.write().await = config;
637        }
638
639        // Extract and store workspace roots
640        let mut roots = Vec::new();
641        if let Some(workspace_folders) = params.workspace_folders {
642            for folder in workspace_folders {
643                if let Ok(path) = folder.uri.to_file_path() {
644                    log::info!("Workspace root: {}", path.display());
645                    roots.push(path);
646                }
647            }
648        } else if let Some(root_uri) = params.root_uri
649            && let Ok(path) = root_uri.to_file_path()
650        {
651            log::info!("Workspace root: {}", path.display());
652            roots.push(path);
653        }
654        *self.workspace_roots.write().await = roots;
655
656        // Load rumdl configuration with auto-discovery (fallback/default)
657        self.load_configuration(false).await;
658
659        Ok(InitializeResult {
660            capabilities: ServerCapabilities {
661                text_document_sync: Some(TextDocumentSyncCapability::Options(TextDocumentSyncOptions {
662                    open_close: Some(true),
663                    change: Some(TextDocumentSyncKind::FULL),
664                    will_save: Some(false),
665                    will_save_wait_until: Some(true),
666                    save: Some(TextDocumentSyncSaveOptions::SaveOptions(SaveOptions {
667                        include_text: Some(false),
668                    })),
669                })),
670                code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
671                document_formatting_provider: Some(OneOf::Left(true)),
672                document_range_formatting_provider: Some(OneOf::Left(true)),
673                diagnostic_provider: Some(DiagnosticServerCapabilities::Options(DiagnosticOptions {
674                    identifier: Some("rumdl".to_string()),
675                    inter_file_dependencies: false,
676                    workspace_diagnostics: false,
677                    work_done_progress_options: WorkDoneProgressOptions::default(),
678                })),
679                workspace: Some(WorkspaceServerCapabilities {
680                    workspace_folders: Some(WorkspaceFoldersServerCapabilities {
681                        supported: Some(true),
682                        change_notifications: Some(OneOf::Left(true)),
683                    }),
684                    file_operations: None,
685                }),
686                ..Default::default()
687            },
688            server_info: Some(ServerInfo {
689                name: "rumdl".to_string(),
690                version: Some(env!("CARGO_PKG_VERSION").to_string()),
691            }),
692        })
693    }
694
695    async fn initialized(&self, _: InitializedParams) {
696        let version = env!("CARGO_PKG_VERSION");
697
698        // Get binary path and build time
699        let (binary_path, build_time) = std::env::current_exe()
700            .ok()
701            .map(|path| {
702                let path_str = path.to_str().unwrap_or("unknown").to_string();
703                let build_time = std::fs::metadata(&path)
704                    .ok()
705                    .and_then(|metadata| metadata.modified().ok())
706                    .and_then(|modified| modified.duration_since(std::time::UNIX_EPOCH).ok())
707                    .and_then(|duration| {
708                        let secs = duration.as_secs();
709                        chrono::DateTime::from_timestamp(secs as i64, 0)
710                            .map(|dt| dt.format("%Y-%m-%d %H:%M:%S UTC").to_string())
711                    })
712                    .unwrap_or_else(|| "unknown".to_string());
713                (path_str, build_time)
714            })
715            .unwrap_or_else(|| ("unknown".to_string(), "unknown".to_string()));
716
717        let working_dir = std::env::current_dir()
718            .ok()
719            .and_then(|p| p.to_str().map(|s| s.to_string()))
720            .unwrap_or_else(|| "unknown".to_string());
721
722        log::info!("rumdl Language Server v{version} initialized (built: {build_time}, binary: {binary_path})");
723        log::info!("Working directory: {working_dir}");
724
725        self.client
726            .log_message(MessageType::INFO, format!("rumdl v{version} Language Server started"))
727            .await;
728    }
729
730    async fn did_change_workspace_folders(&self, params: DidChangeWorkspaceFoldersParams) {
731        // Update workspace roots
732        let mut roots = self.workspace_roots.write().await;
733
734        // Remove deleted workspace folders
735        for removed in &params.event.removed {
736            if let Ok(path) = removed.uri.to_file_path() {
737                roots.retain(|r| r != &path);
738                log::info!("Removed workspace root: {}", path.display());
739            }
740        }
741
742        // Add new workspace folders
743        for added in &params.event.added {
744            if let Ok(path) = added.uri.to_file_path()
745                && !roots.contains(&path)
746            {
747                log::info!("Added workspace root: {}", path.display());
748                roots.push(path);
749            }
750        }
751        drop(roots);
752
753        // Clear config cache as workspace structure changed
754        self.config_cache.write().await.clear();
755
756        // Reload fallback configuration
757        self.reload_configuration().await;
758    }
759
760    async fn shutdown(&self) -> JsonRpcResult<()> {
761        log::info!("Shutting down rumdl Language Server");
762        Ok(())
763    }
764
765    async fn did_open(&self, params: DidOpenTextDocumentParams) {
766        let uri = params.text_document.uri;
767        let text = params.text_document.text;
768        let version = params.text_document.version;
769
770        let entry = DocumentEntry {
771            content: text.clone(),
772            version: Some(version),
773            from_disk: false,
774        };
775        self.documents.write().await.insert(uri.clone(), entry);
776
777        self.update_diagnostics(uri, text).await;
778    }
779
780    async fn did_change(&self, params: DidChangeTextDocumentParams) {
781        let uri = params.text_document.uri;
782        let version = params.text_document.version;
783
784        if let Some(change) = params.content_changes.into_iter().next() {
785            let text = change.text;
786
787            let entry = DocumentEntry {
788                content: text.clone(),
789                version: Some(version),
790                from_disk: false,
791            };
792            self.documents.write().await.insert(uri.clone(), entry);
793
794            self.update_diagnostics(uri, text).await;
795        }
796    }
797
798    async fn will_save_wait_until(&self, params: WillSaveTextDocumentParams) -> JsonRpcResult<Option<Vec<TextEdit>>> {
799        let config_guard = self.config.read().await;
800        let enable_auto_fix = config_guard.enable_auto_fix;
801        drop(config_guard);
802
803        if !enable_auto_fix {
804            return Ok(None);
805        }
806
807        // Get the current document content
808        let text = match self.get_document_content(&params.text_document.uri).await {
809            Some(content) => content,
810            None => return Ok(None),
811        };
812
813        // Apply all fixes
814        match self.apply_all_fixes(&params.text_document.uri, &text).await {
815            Ok(Some(fixed_text)) => {
816                // Return a single edit that replaces the entire document
817                Ok(Some(vec![TextEdit {
818                    range: Range {
819                        start: Position { line: 0, character: 0 },
820                        end: self.get_end_position(&text),
821                    },
822                    new_text: fixed_text,
823                }]))
824            }
825            Ok(None) => Ok(None),
826            Err(e) => {
827                log::error!("Failed to generate fixes in will_save_wait_until: {e}");
828                Ok(None)
829            }
830        }
831    }
832
833    async fn did_save(&self, params: DidSaveTextDocumentParams) {
834        // Re-lint the document after save
835        // Note: Auto-fixing is now handled by will_save_wait_until which runs before the save
836        if let Some(entry) = self.documents.read().await.get(&params.text_document.uri) {
837            self.update_diagnostics(params.text_document.uri, entry.content.clone())
838                .await;
839        }
840    }
841
842    async fn did_close(&self, params: DidCloseTextDocumentParams) {
843        // Remove document from storage
844        self.documents.write().await.remove(&params.text_document.uri);
845
846        // Clear diagnostics
847        self.client
848            .publish_diagnostics(params.text_document.uri, Vec::new(), None)
849            .await;
850    }
851
852    async fn did_change_watched_files(&self, params: DidChangeWatchedFilesParams) {
853        // Check if any of the changed files are config files
854        const CONFIG_FILES: &[&str] = &[".rumdl.toml", "rumdl.toml", "pyproject.toml", ".markdownlint.json"];
855
856        for change in &params.changes {
857            if let Ok(path) = change.uri.to_file_path()
858                && let Some(file_name) = path.file_name().and_then(|f| f.to_str())
859                && CONFIG_FILES.contains(&file_name)
860            {
861                log::info!("Config file changed: {}, invalidating config cache", path.display());
862
863                // Invalidate all cache entries that were loaded from this config file
864                let mut cache = self.config_cache.write().await;
865                cache.retain(|_, entry| {
866                    if let Some(config_file) = &entry.config_file {
867                        config_file != &path
868                    } else {
869                        true
870                    }
871                });
872
873                // Also reload the global fallback configuration
874                drop(cache);
875                self.reload_configuration().await;
876
877                // Re-lint all open documents
878                // First collect URIs and content to avoid holding lock during async operations
879                let docs_to_update: Vec<(Url, String)> = {
880                    let docs = self.documents.read().await;
881                    docs.iter()
882                        .filter(|(_, entry)| !entry.from_disk)
883                        .map(|(uri, entry)| (uri.clone(), entry.content.clone()))
884                        .collect()
885                };
886
887                // Now update diagnostics without holding the lock
888                for (uri, text) in docs_to_update {
889                    self.update_diagnostics(uri, text).await;
890                }
891
892                break;
893            }
894        }
895    }
896
897    async fn code_action(&self, params: CodeActionParams) -> JsonRpcResult<Option<CodeActionResponse>> {
898        let uri = params.text_document.uri;
899        let range = params.range;
900
901        if let Some(text) = self.get_document_content(&uri).await {
902            match self.get_code_actions(&uri, &text, range).await {
903                Ok(actions) => {
904                    let response: Vec<CodeActionOrCommand> =
905                        actions.into_iter().map(CodeActionOrCommand::CodeAction).collect();
906                    Ok(Some(response))
907                }
908                Err(e) => {
909                    log::error!("Failed to get code actions: {e}");
910                    Ok(None)
911                }
912            }
913        } else {
914            Ok(None)
915        }
916    }
917
918    async fn range_formatting(&self, params: DocumentRangeFormattingParams) -> JsonRpcResult<Option<Vec<TextEdit>>> {
919        // For markdown linting, we format the entire document because:
920        // 1. Many markdown rules have document-wide implications (e.g., heading hierarchy, list consistency)
921        // 2. Fixes often need surrounding context to be applied correctly
922        // 3. This approach is common among linters (ESLint, rustfmt, etc. do similar)
923        log::debug!(
924            "Range formatting requested for {:?}, formatting entire document due to rule interdependencies",
925            params.range
926        );
927
928        let formatting_params = DocumentFormattingParams {
929            text_document: params.text_document,
930            options: params.options,
931            work_done_progress_params: params.work_done_progress_params,
932        };
933
934        self.formatting(formatting_params).await
935    }
936
937    async fn formatting(&self, params: DocumentFormattingParams) -> JsonRpcResult<Option<Vec<TextEdit>>> {
938        let uri = params.text_document.uri;
939
940        log::debug!("Formatting request for: {uri}");
941
942        if let Some(text) = self.get_document_content(&uri).await {
943            // Get config with LSP overrides
944            let config_guard = self.config.read().await;
945            let lsp_config = config_guard.clone();
946            drop(config_guard);
947
948            // Resolve configuration for this specific file
949            let rumdl_config = if let Ok(file_path) = uri.to_file_path() {
950                self.resolve_config_for_file(&file_path).await
951            } else {
952                // Fallback to global config for non-file URIs
953                self.rumdl_config.read().await.clone()
954            };
955
956            let all_rules = rules::all_rules(&rumdl_config);
957            let flavor = rumdl_config.markdown_flavor();
958
959            // Use the standard filter_rules function which respects config's disabled rules
960            let mut filtered_rules = rules::filter_rules(&all_rules, &rumdl_config.global);
961
962            // Apply LSP config overrides
963            filtered_rules = self.apply_lsp_config_overrides(filtered_rules, &lsp_config);
964
965            // Use warning fixes for all rules
966            match crate::lint(&text, &filtered_rules, false, flavor) {
967                Ok(warnings) => {
968                    log::debug!(
969                        "Found {} warnings, {} with fixes",
970                        warnings.len(),
971                        warnings.iter().filter(|w| w.fix.is_some()).count()
972                    );
973
974                    let has_fixes = warnings.iter().any(|w| w.fix.is_some());
975                    if has_fixes {
976                        match crate::utils::fix_utils::apply_warning_fixes(&text, &warnings) {
977                            Ok(fixed_content) => {
978                                if fixed_content != text {
979                                    log::debug!("Returning formatting edits");
980                                    let end_position = self.get_end_position(&text);
981                                    let edit = TextEdit {
982                                        range: Range {
983                                            start: Position { line: 0, character: 0 },
984                                            end: end_position,
985                                        },
986                                        new_text: fixed_content,
987                                    };
988                                    return Ok(Some(vec![edit]));
989                                }
990                            }
991                            Err(e) => {
992                                log::error!("Failed to apply fixes: {e}");
993                            }
994                        }
995                    }
996                    Ok(Some(Vec::new()))
997                }
998                Err(e) => {
999                    log::error!("Failed to format document: {e}");
1000                    Ok(Some(Vec::new()))
1001                }
1002            }
1003        } else {
1004            log::warn!("Document not found: {uri}");
1005            Ok(None)
1006        }
1007    }
1008
1009    async fn diagnostic(&self, params: DocumentDiagnosticParams) -> JsonRpcResult<DocumentDiagnosticReportResult> {
1010        let uri = params.text_document.uri;
1011
1012        if let Some(text) = self.get_document_content(&uri).await {
1013            match self.lint_document(&uri, &text).await {
1014                Ok(diagnostics) => Ok(DocumentDiagnosticReportResult::Report(DocumentDiagnosticReport::Full(
1015                    RelatedFullDocumentDiagnosticReport {
1016                        related_documents: None,
1017                        full_document_diagnostic_report: FullDocumentDiagnosticReport {
1018                            result_id: None,
1019                            items: diagnostics,
1020                        },
1021                    },
1022                ))),
1023                Err(e) => {
1024                    log::error!("Failed to get diagnostics: {e}");
1025                    Ok(DocumentDiagnosticReportResult::Report(DocumentDiagnosticReport::Full(
1026                        RelatedFullDocumentDiagnosticReport {
1027                            related_documents: None,
1028                            full_document_diagnostic_report: FullDocumentDiagnosticReport {
1029                                result_id: None,
1030                                items: Vec::new(),
1031                            },
1032                        },
1033                    )))
1034                }
1035            }
1036        } else {
1037            Ok(DocumentDiagnosticReportResult::Report(DocumentDiagnosticReport::Full(
1038                RelatedFullDocumentDiagnosticReport {
1039                    related_documents: None,
1040                    full_document_diagnostic_report: FullDocumentDiagnosticReport {
1041                        result_id: None,
1042                        items: Vec::new(),
1043                    },
1044                },
1045            )))
1046        }
1047    }
1048}
1049
1050#[cfg(test)]
1051mod tests {
1052    use super::*;
1053    use crate::rule::LintWarning;
1054    use tower_lsp::LspService;
1055
1056    fn create_test_server() -> RumdlLanguageServer {
1057        let (service, _socket) = LspService::new(RumdlLanguageServer::new);
1058        service.inner().clone()
1059    }
1060
1061    #[tokio::test]
1062    async fn test_server_creation() {
1063        let server = create_test_server();
1064
1065        // Verify default configuration
1066        let config = server.config.read().await;
1067        assert!(config.enable_linting);
1068        assert!(!config.enable_auto_fix);
1069    }
1070
1071    #[tokio::test]
1072    async fn test_lint_document() {
1073        let server = create_test_server();
1074
1075        // Test linting with a simple markdown document
1076        let uri = Url::parse("file:///test.md").unwrap();
1077        let text = "# Test\n\nThis is a test  \nWith trailing spaces  ";
1078
1079        let diagnostics = server.lint_document(&uri, text).await.unwrap();
1080
1081        // Should find trailing spaces violations
1082        assert!(!diagnostics.is_empty());
1083        assert!(diagnostics.iter().any(|d| d.message.contains("trailing")));
1084    }
1085
1086    #[tokio::test]
1087    async fn test_lint_document_disabled() {
1088        let server = create_test_server();
1089
1090        // Disable linting
1091        server.config.write().await.enable_linting = false;
1092
1093        let uri = Url::parse("file:///test.md").unwrap();
1094        let text = "# Test\n\nThis is a test  \nWith trailing spaces  ";
1095
1096        let diagnostics = server.lint_document(&uri, text).await.unwrap();
1097
1098        // Should return empty diagnostics when disabled
1099        assert!(diagnostics.is_empty());
1100    }
1101
1102    #[tokio::test]
1103    async fn test_get_code_actions() {
1104        let server = create_test_server();
1105
1106        let uri = Url::parse("file:///test.md").unwrap();
1107        let text = "# Test\n\nThis is a test  \nWith trailing spaces  ";
1108
1109        // Create a range covering the whole document
1110        let range = Range {
1111            start: Position { line: 0, character: 0 },
1112            end: Position { line: 3, character: 21 },
1113        };
1114
1115        let actions = server.get_code_actions(&uri, text, range).await.unwrap();
1116
1117        // Should have code actions for fixing trailing spaces
1118        assert!(!actions.is_empty());
1119        assert!(actions.iter().any(|a| a.title.contains("trailing")));
1120    }
1121
1122    #[tokio::test]
1123    async fn test_get_code_actions_outside_range() {
1124        let server = create_test_server();
1125
1126        let uri = Url::parse("file:///test.md").unwrap();
1127        let text = "# Test\n\nThis is a test  \nWith trailing spaces  ";
1128
1129        // Create a range that doesn't cover the violations
1130        let range = Range {
1131            start: Position { line: 0, character: 0 },
1132            end: Position { line: 0, character: 6 },
1133        };
1134
1135        let actions = server.get_code_actions(&uri, text, range).await.unwrap();
1136
1137        // Should have no code actions for this range
1138        assert!(actions.is_empty());
1139    }
1140
1141    #[tokio::test]
1142    async fn test_document_storage() {
1143        let server = create_test_server();
1144
1145        let uri = Url::parse("file:///test.md").unwrap();
1146        let text = "# Test Document";
1147
1148        // Store document
1149        let entry = DocumentEntry {
1150            content: text.to_string(),
1151            version: Some(1),
1152            from_disk: false,
1153        };
1154        server.documents.write().await.insert(uri.clone(), entry);
1155
1156        // Verify storage
1157        let stored = server.documents.read().await.get(&uri).map(|e| e.content.clone());
1158        assert_eq!(stored, Some(text.to_string()));
1159
1160        // Remove document
1161        server.documents.write().await.remove(&uri);
1162
1163        // Verify removal
1164        let stored = server.documents.read().await.get(&uri).cloned();
1165        assert_eq!(stored, None);
1166    }
1167
1168    #[tokio::test]
1169    async fn test_configuration_loading() {
1170        let server = create_test_server();
1171
1172        // Load configuration with auto-discovery
1173        server.load_configuration(false).await;
1174
1175        // Verify configuration was loaded successfully
1176        // The config could be from: .rumdl.toml, pyproject.toml, .markdownlint.json, or default
1177        let rumdl_config = server.rumdl_config.read().await;
1178        // The loaded config is valid regardless of source
1179        drop(rumdl_config); // Just verify we can access it without panic
1180    }
1181
1182    #[tokio::test]
1183    async fn test_load_config_for_lsp() {
1184        // Test with no config file
1185        let result = RumdlLanguageServer::load_config_for_lsp(None);
1186        assert!(result.is_ok());
1187
1188        // Test with non-existent config file
1189        let result = RumdlLanguageServer::load_config_for_lsp(Some("/nonexistent/config.toml"));
1190        assert!(result.is_err());
1191    }
1192
1193    #[tokio::test]
1194    async fn test_warning_conversion() {
1195        let warning = LintWarning {
1196            message: "Test warning".to_string(),
1197            line: 1,
1198            column: 1,
1199            end_line: 1,
1200            end_column: 10,
1201            severity: crate::rule::Severity::Warning,
1202            fix: None,
1203            rule_name: Some("MD001".to_string()),
1204        };
1205
1206        // Test diagnostic conversion
1207        let diagnostic = warning_to_diagnostic(&warning);
1208        assert_eq!(diagnostic.message, "Test warning");
1209        assert_eq!(diagnostic.severity, Some(DiagnosticSeverity::WARNING));
1210        assert_eq!(diagnostic.code, Some(NumberOrString::String("MD001".to_string())));
1211
1212        // Test code action conversion (no fix, but should have ignore action)
1213        let uri = Url::parse("file:///test.md").unwrap();
1214        let actions = warning_to_code_actions(&warning, &uri, "Test content");
1215        // Should have 1 action: ignore-line (no fix available)
1216        assert_eq!(actions.len(), 1);
1217        assert_eq!(actions[0].title, "Ignore MD001 for this line");
1218    }
1219
1220    #[tokio::test]
1221    async fn test_multiple_documents() {
1222        let server = create_test_server();
1223
1224        let uri1 = Url::parse("file:///test1.md").unwrap();
1225        let uri2 = Url::parse("file:///test2.md").unwrap();
1226        let text1 = "# Document 1";
1227        let text2 = "# Document 2";
1228
1229        // Store multiple documents
1230        {
1231            let mut docs = server.documents.write().await;
1232            let entry1 = DocumentEntry {
1233                content: text1.to_string(),
1234                version: Some(1),
1235                from_disk: false,
1236            };
1237            let entry2 = DocumentEntry {
1238                content: text2.to_string(),
1239                version: Some(1),
1240                from_disk: false,
1241            };
1242            docs.insert(uri1.clone(), entry1);
1243            docs.insert(uri2.clone(), entry2);
1244        }
1245
1246        // Verify both are stored
1247        let docs = server.documents.read().await;
1248        assert_eq!(docs.len(), 2);
1249        assert_eq!(docs.get(&uri1).map(|s| s.content.as_str()), Some(text1));
1250        assert_eq!(docs.get(&uri2).map(|s| s.content.as_str()), Some(text2));
1251    }
1252
1253    #[tokio::test]
1254    async fn test_auto_fix_on_save() {
1255        let server = create_test_server();
1256
1257        // Enable auto-fix
1258        {
1259            let mut config = server.config.write().await;
1260            config.enable_auto_fix = true;
1261        }
1262
1263        let uri = Url::parse("file:///test.md").unwrap();
1264        let text = "#Heading without space"; // MD018 violation
1265
1266        // Store document
1267        let entry = DocumentEntry {
1268            content: text.to_string(),
1269            version: Some(1),
1270            from_disk: false,
1271        };
1272        server.documents.write().await.insert(uri.clone(), entry);
1273
1274        // Test apply_all_fixes
1275        let fixed = server.apply_all_fixes(&uri, text).await.unwrap();
1276        assert!(fixed.is_some());
1277        // MD018 adds space, MD047 adds trailing newline
1278        assert_eq!(fixed.unwrap(), "# Heading without space\n");
1279    }
1280
1281    #[tokio::test]
1282    async fn test_get_end_position() {
1283        let server = create_test_server();
1284
1285        // Single line
1286        let pos = server.get_end_position("Hello");
1287        assert_eq!(pos.line, 0);
1288        assert_eq!(pos.character, 5);
1289
1290        // Multiple lines
1291        let pos = server.get_end_position("Hello\nWorld\nTest");
1292        assert_eq!(pos.line, 2);
1293        assert_eq!(pos.character, 4);
1294
1295        // Empty string
1296        let pos = server.get_end_position("");
1297        assert_eq!(pos.line, 0);
1298        assert_eq!(pos.character, 0);
1299
1300        // Ends with newline - position should be at start of next line
1301        let pos = server.get_end_position("Hello\n");
1302        assert_eq!(pos.line, 1);
1303        assert_eq!(pos.character, 0);
1304    }
1305
1306    #[tokio::test]
1307    async fn test_empty_document_handling() {
1308        let server = create_test_server();
1309
1310        let uri = Url::parse("file:///empty.md").unwrap();
1311        let text = "";
1312
1313        // Test linting empty document
1314        let diagnostics = server.lint_document(&uri, text).await.unwrap();
1315        assert!(diagnostics.is_empty());
1316
1317        // Test code actions on empty document
1318        let range = Range {
1319            start: Position { line: 0, character: 0 },
1320            end: Position { line: 0, character: 0 },
1321        };
1322        let actions = server.get_code_actions(&uri, text, range).await.unwrap();
1323        assert!(actions.is_empty());
1324    }
1325
1326    #[tokio::test]
1327    async fn test_config_update() {
1328        let server = create_test_server();
1329
1330        // Update config
1331        {
1332            let mut config = server.config.write().await;
1333            config.enable_auto_fix = true;
1334            config.config_path = Some("/custom/path.toml".to_string());
1335        }
1336
1337        // Verify update
1338        let config = server.config.read().await;
1339        assert!(config.enable_auto_fix);
1340        assert_eq!(config.config_path, Some("/custom/path.toml".to_string()));
1341    }
1342
1343    #[tokio::test]
1344    async fn test_document_formatting() {
1345        let server = create_test_server();
1346        let uri = Url::parse("file:///test.md").unwrap();
1347        let text = "# Test\n\nThis is a test  \nWith trailing spaces  ";
1348
1349        // Store document
1350        let entry = DocumentEntry {
1351            content: text.to_string(),
1352            version: Some(1),
1353            from_disk: false,
1354        };
1355        server.documents.write().await.insert(uri.clone(), entry);
1356
1357        // Create formatting params
1358        let params = DocumentFormattingParams {
1359            text_document: TextDocumentIdentifier { uri: uri.clone() },
1360            options: FormattingOptions {
1361                tab_size: 4,
1362                insert_spaces: true,
1363                properties: HashMap::new(),
1364                trim_trailing_whitespace: Some(true),
1365                insert_final_newline: Some(true),
1366                trim_final_newlines: Some(true),
1367            },
1368            work_done_progress_params: WorkDoneProgressParams::default(),
1369        };
1370
1371        // Call formatting
1372        let result = server.formatting(params).await.unwrap();
1373
1374        // Should return text edits that fix the trailing spaces
1375        assert!(result.is_some());
1376        let edits = result.unwrap();
1377        assert!(!edits.is_empty());
1378
1379        // The new text should have trailing spaces removed
1380        let edit = &edits[0];
1381        // The formatted text should have the trailing spaces removed from the middle line
1382        // and a final newline added
1383        let expected = "# Test\n\nThis is a test  \nWith trailing spaces\n";
1384        assert_eq!(edit.new_text, expected);
1385    }
1386
1387    /// Test that resolve_config_for_file() finds the correct config in multi-root workspace
1388    #[tokio::test]
1389    async fn test_resolve_config_for_file_multi_root() {
1390        use std::fs;
1391        use tempfile::tempdir;
1392
1393        let temp_dir = tempdir().unwrap();
1394        let temp_path = temp_dir.path();
1395
1396        // Setup project A with line_length=60
1397        let project_a = temp_path.join("project_a");
1398        let project_a_docs = project_a.join("docs");
1399        fs::create_dir_all(&project_a_docs).unwrap();
1400
1401        let config_a = project_a.join(".rumdl.toml");
1402        fs::write(
1403            &config_a,
1404            r#"
1405[global]
1406
1407[MD013]
1408line_length = 60
1409"#,
1410        )
1411        .unwrap();
1412
1413        // Setup project B with line_length=120
1414        let project_b = temp_path.join("project_b");
1415        fs::create_dir(&project_b).unwrap();
1416
1417        let config_b = project_b.join(".rumdl.toml");
1418        fs::write(
1419            &config_b,
1420            r#"
1421[global]
1422
1423[MD013]
1424line_length = 120
1425"#,
1426        )
1427        .unwrap();
1428
1429        // Create LSP server and initialize with workspace roots
1430        let server = create_test_server();
1431
1432        // Set workspace roots
1433        {
1434            let mut roots = server.workspace_roots.write().await;
1435            roots.push(project_a.clone());
1436            roots.push(project_b.clone());
1437        }
1438
1439        // Test file in project A
1440        let file_a = project_a_docs.join("test.md");
1441        fs::write(&file_a, "# Test A\n").unwrap();
1442
1443        let config_for_a = server.resolve_config_for_file(&file_a).await;
1444        let line_length_a = crate::config::get_rule_config_value::<usize>(&config_for_a, "MD013", "line_length");
1445        assert_eq!(line_length_a, Some(60), "File in project_a should get line_length=60");
1446
1447        // Test file in project B
1448        let file_b = project_b.join("test.md");
1449        fs::write(&file_b, "# Test B\n").unwrap();
1450
1451        let config_for_b = server.resolve_config_for_file(&file_b).await;
1452        let line_length_b = crate::config::get_rule_config_value::<usize>(&config_for_b, "MD013", "line_length");
1453        assert_eq!(line_length_b, Some(120), "File in project_b should get line_length=120");
1454    }
1455
1456    /// Test that config resolution respects workspace root boundaries
1457    #[tokio::test]
1458    async fn test_config_resolution_respects_workspace_boundaries() {
1459        use std::fs;
1460        use tempfile::tempdir;
1461
1462        let temp_dir = tempdir().unwrap();
1463        let temp_path = temp_dir.path();
1464
1465        // Create parent config that should NOT be used
1466        let parent_config = temp_path.join(".rumdl.toml");
1467        fs::write(
1468            &parent_config,
1469            r#"
1470[global]
1471
1472[MD013]
1473line_length = 80
1474"#,
1475        )
1476        .unwrap();
1477
1478        // Create workspace root with its own config
1479        let workspace_root = temp_path.join("workspace");
1480        let workspace_subdir = workspace_root.join("subdir");
1481        fs::create_dir_all(&workspace_subdir).unwrap();
1482
1483        let workspace_config = workspace_root.join(".rumdl.toml");
1484        fs::write(
1485            &workspace_config,
1486            r#"
1487[global]
1488
1489[MD013]
1490line_length = 100
1491"#,
1492        )
1493        .unwrap();
1494
1495        let server = create_test_server();
1496
1497        // Register workspace_root as a workspace root
1498        {
1499            let mut roots = server.workspace_roots.write().await;
1500            roots.push(workspace_root.clone());
1501        }
1502
1503        // Test file deep in subdirectory
1504        let test_file = workspace_subdir.join("deep").join("test.md");
1505        fs::create_dir_all(test_file.parent().unwrap()).unwrap();
1506        fs::write(&test_file, "# Test\n").unwrap();
1507
1508        let config = server.resolve_config_for_file(&test_file).await;
1509        let line_length = crate::config::get_rule_config_value::<usize>(&config, "MD013", "line_length");
1510
1511        // Should find workspace_root/.rumdl.toml (100), NOT parent config (80)
1512        assert_eq!(
1513            line_length,
1514            Some(100),
1515            "Should find workspace config, not parent config outside workspace"
1516        );
1517    }
1518
1519    /// Test that config cache works (cache hit scenario)
1520    #[tokio::test]
1521    async fn test_config_cache_hit() {
1522        use std::fs;
1523        use tempfile::tempdir;
1524
1525        let temp_dir = tempdir().unwrap();
1526        let temp_path = temp_dir.path();
1527
1528        let project = temp_path.join("project");
1529        fs::create_dir(&project).unwrap();
1530
1531        let config_file = project.join(".rumdl.toml");
1532        fs::write(
1533            &config_file,
1534            r#"
1535[global]
1536
1537[MD013]
1538line_length = 75
1539"#,
1540        )
1541        .unwrap();
1542
1543        let server = create_test_server();
1544        {
1545            let mut roots = server.workspace_roots.write().await;
1546            roots.push(project.clone());
1547        }
1548
1549        let test_file = project.join("test.md");
1550        fs::write(&test_file, "# Test\n").unwrap();
1551
1552        // First call - cache miss
1553        let config1 = server.resolve_config_for_file(&test_file).await;
1554        let line_length1 = crate::config::get_rule_config_value::<usize>(&config1, "MD013", "line_length");
1555        assert_eq!(line_length1, Some(75));
1556
1557        // Verify cache was populated
1558        {
1559            let cache = server.config_cache.read().await;
1560            let search_dir = test_file.parent().unwrap();
1561            assert!(
1562                cache.contains_key(search_dir),
1563                "Cache should be populated after first call"
1564            );
1565        }
1566
1567        // Second call - cache hit (should return same config without filesystem access)
1568        let config2 = server.resolve_config_for_file(&test_file).await;
1569        let line_length2 = crate::config::get_rule_config_value::<usize>(&config2, "MD013", "line_length");
1570        assert_eq!(line_length2, Some(75));
1571    }
1572
1573    /// Test nested directory config search (file searches upward)
1574    #[tokio::test]
1575    async fn test_nested_directory_config_search() {
1576        use std::fs;
1577        use tempfile::tempdir;
1578
1579        let temp_dir = tempdir().unwrap();
1580        let temp_path = temp_dir.path();
1581
1582        let project = temp_path.join("project");
1583        fs::create_dir(&project).unwrap();
1584
1585        // Config at project root
1586        let config = project.join(".rumdl.toml");
1587        fs::write(
1588            &config,
1589            r#"
1590[global]
1591
1592[MD013]
1593line_length = 110
1594"#,
1595        )
1596        .unwrap();
1597
1598        // File deep in nested structure
1599        let deep_dir = project.join("src").join("docs").join("guides");
1600        fs::create_dir_all(&deep_dir).unwrap();
1601        let deep_file = deep_dir.join("test.md");
1602        fs::write(&deep_file, "# Test\n").unwrap();
1603
1604        let server = create_test_server();
1605        {
1606            let mut roots = server.workspace_roots.write().await;
1607            roots.push(project.clone());
1608        }
1609
1610        let resolved_config = server.resolve_config_for_file(&deep_file).await;
1611        let line_length = crate::config::get_rule_config_value::<usize>(&resolved_config, "MD013", "line_length");
1612
1613        assert_eq!(
1614            line_length,
1615            Some(110),
1616            "Should find config by searching upward from deep directory"
1617        );
1618    }
1619
1620    /// Test fallback to default config when no config file found
1621    #[tokio::test]
1622    async fn test_fallback_to_default_config() {
1623        use std::fs;
1624        use tempfile::tempdir;
1625
1626        let temp_dir = tempdir().unwrap();
1627        let temp_path = temp_dir.path();
1628
1629        let project = temp_path.join("project");
1630        fs::create_dir(&project).unwrap();
1631
1632        // No config file created!
1633
1634        let test_file = project.join("test.md");
1635        fs::write(&test_file, "# Test\n").unwrap();
1636
1637        let server = create_test_server();
1638        {
1639            let mut roots = server.workspace_roots.write().await;
1640            roots.push(project.clone());
1641        }
1642
1643        let config = server.resolve_config_for_file(&test_file).await;
1644
1645        // Default global line_length is 80
1646        assert_eq!(
1647            config.global.line_length, 80,
1648            "Should fall back to default config when no config file found"
1649        );
1650    }
1651
1652    /// Test config priority: closer config wins over parent config
1653    #[tokio::test]
1654    async fn test_config_priority_closer_wins() {
1655        use std::fs;
1656        use tempfile::tempdir;
1657
1658        let temp_dir = tempdir().unwrap();
1659        let temp_path = temp_dir.path();
1660
1661        let project = temp_path.join("project");
1662        fs::create_dir(&project).unwrap();
1663
1664        // Parent config
1665        let parent_config = project.join(".rumdl.toml");
1666        fs::write(
1667            &parent_config,
1668            r#"
1669[global]
1670
1671[MD013]
1672line_length = 100
1673"#,
1674        )
1675        .unwrap();
1676
1677        // Subdirectory with its own config (should override parent)
1678        let subdir = project.join("subdir");
1679        fs::create_dir(&subdir).unwrap();
1680
1681        let subdir_config = subdir.join(".rumdl.toml");
1682        fs::write(
1683            &subdir_config,
1684            r#"
1685[global]
1686
1687[MD013]
1688line_length = 50
1689"#,
1690        )
1691        .unwrap();
1692
1693        let server = create_test_server();
1694        {
1695            let mut roots = server.workspace_roots.write().await;
1696            roots.push(project.clone());
1697        }
1698
1699        // File in subdirectory
1700        let test_file = subdir.join("test.md");
1701        fs::write(&test_file, "# Test\n").unwrap();
1702
1703        let config = server.resolve_config_for_file(&test_file).await;
1704        let line_length = crate::config::get_rule_config_value::<usize>(&config, "MD013", "line_length");
1705
1706        assert_eq!(
1707            line_length,
1708            Some(50),
1709            "Closer config (subdir) should override parent config"
1710        );
1711    }
1712}