agnix-lsp 0.3.0

Language Server Protocol implementation for agnix
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
//! LSP backend implementation for agnix.
//!
//! Implements the Language Server Protocol using tower-lsp, providing
//! real-time validation of agent configuration files.

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

use tokio::sync::RwLock;
use tower_lsp::jsonrpc::Result;
use tower_lsp::lsp_types::*;
use tower_lsp::{Client, LanguageServer};

use crate::code_actions::fixes_to_code_actions;
use crate::diagnostic_mapper::{deserialize_fixes, to_lsp_diagnostics};
use crate::hover_provider::hover_at_position;

fn create_error_diagnostic(code: &str, message: String) -> Diagnostic {
    Diagnostic {
        range: Range {
            start: Position {
                line: 0,
                character: 0,
            },
            end: Position {
                line: 0,
                character: 0,
            },
        },
        severity: Some(DiagnosticSeverity::ERROR),
        code: Some(NumberOrString::String(code.to_string())),
        code_description: None,
        source: Some("agnix".to_string()),
        message,
        related_information: None,
        tags: None,
        data: None,
    }
}

/// LSP backend that handles validation requests.
///
/// The backend maintains a connection to the LSP client and validates
/// files on open, change, and save events. It also provides code actions
/// for quick fixes and hover documentation for configuration fields.
///
/// # Performance Notes
///
/// Both `LintConfig` and `ValidatorRegistry` are cached and reused across
/// validations to avoid repeated allocations.
pub struct Backend {
    client: Client,
    /// Cached lint configuration reused across validations.
    /// Wrapped in RwLock to allow loading from .agnix.toml after initialize().
    config: RwLock<Arc<agnix_core::LintConfig>>,
    /// Workspace root path for boundary validation (security).
    /// Set during initialize() from the client's root_uri.
    workspace_root: RwLock<Option<PathBuf>>,
    documents: RwLock<HashMap<Url, String>>,
    /// Cached validator registry reused across validations.
    /// Immutable after construction; Arc enables sharing across spawn_blocking tasks.
    registry: Arc<agnix_core::ValidatorRegistry>,
}

impl Backend {
    /// Create a new backend instance with the given client connection.
    pub fn new(client: Client) -> Self {
        Self {
            client,
            config: RwLock::new(Arc::new(agnix_core::LintConfig::default())),
            workspace_root: RwLock::new(None),
            documents: RwLock::new(HashMap::new()),
            registry: Arc::new(agnix_core::ValidatorRegistry::with_defaults()),
        }
    }

    /// Run validation on a file in a blocking task.
    ///
    /// agnix-core validation is CPU-bound and synchronous, so we run it
    /// in a blocking task to avoid blocking the async runtime.
    ///
    /// Both `LintConfig` and `ValidatorRegistry` are cloned from cached
    /// instances to avoid repeated allocations on each validation.
    async fn validate_file(&self, path: PathBuf) -> Vec<Diagnostic> {
        let config = Arc::clone(&*self.config.read().await);
        let registry = Arc::clone(&self.registry);
        let result = tokio::task::spawn_blocking(move || {
            agnix_core::validate_file_with_registry(&path, &config, &registry)
        })
        .await;

        match result {
            Ok(Ok(diagnostics)) => to_lsp_diagnostics(diagnostics),
            Ok(Err(e)) => vec![create_error_diagnostic(
                "agnix::validation-error",
                format!("Validation error: {}", e),
            )],
            Err(e) => vec![create_error_diagnostic(
                "agnix::internal-error",
                format!("Internal error: {}", e),
            )],
        }
    }

    /// Validate from cached content and publish diagnostics.
    ///
    /// Used for did_change events where we have the content in memory.
    /// This avoids reading from disk and provides real-time feedback.
    async fn validate_from_content_and_publish(&self, uri: Url) {
        let file_path = match uri.to_file_path() {
            Ok(p) => p,
            Err(()) => {
                self.client
                    .log_message(MessageType::WARNING, format!("Invalid file URI: {}", uri))
                    .await;
                return;
            }
        };

        // Security: Validate file is within workspace boundaries
        if let Some(ref workspace_root) = *self.workspace_root.read().await {
            let canonical_path = match file_path.canonicalize() {
                Ok(p) => p,
                Err(_) => file_path.clone(),
            };
            let canonical_root = workspace_root
                .canonicalize()
                .unwrap_or_else(|_| workspace_root.clone());

            if !canonical_path.starts_with(&canonical_root) {
                self.client
                    .log_message(
                        MessageType::WARNING,
                        format!("File outside workspace boundary: {}", uri),
                    )
                    .await;
                return;
            }
        }

        // Get content from cache
        let content = {
            let docs = self.documents.read().await;
            match docs.get(&uri) {
                Some(c) => c.clone(),
                None => {
                    // Fall back to file-based validation
                    drop(docs);
                    let diagnostics = self.validate_file(file_path).await;
                    self.client
                        .publish_diagnostics(uri, diagnostics, None)
                        .await;
                    return;
                }
            }
        };

        let config = Arc::clone(&*self.config.read().await);
        let result = tokio::task::spawn_blocking(move || {
            let file_type = agnix_core::detect_file_type(&file_path);
            if file_type == agnix_core::FileType::Unknown {
                return Ok(vec![]);
            }

            let registry = agnix_core::ValidatorRegistry::with_defaults();
            let validators = registry.validators_for(file_type);
            let mut diagnostics = Vec::new();

            for validator in validators {
                diagnostics.extend(validator.validate(&file_path, &content, &config));
            }

            Ok::<_, agnix_core::LintError>(diagnostics)
        })
        .await;

        let diagnostics = match result {
            Ok(Ok(diagnostics)) => to_lsp_diagnostics(diagnostics),
            Ok(Err(e)) => vec![create_error_diagnostic(
                "agnix::validation-error",
                format!("Validation error: {}", e),
            )],
            Err(e) => vec![create_error_diagnostic(
                "agnix::internal-error",
                format!("Internal error: {}", e),
            )],
        };

        self.client
            .publish_diagnostics(uri, diagnostics, None)
            .await;
    }

    /// Get cached document content for a URI.
    async fn get_document_content(&self, uri: &Url) -> Option<String> {
        self.documents.read().await.get(uri).cloned()
    }
}

#[tower_lsp::async_trait]
impl LanguageServer for Backend {
    async fn initialize(&self, params: InitializeParams) -> Result<InitializeResult> {
        // Capture workspace root for path boundary validation
        if let Some(root_uri) = params.root_uri {
            if let Ok(root_path) = root_uri.to_file_path() {
                *self.workspace_root.write().await = Some(root_path.clone());

                // Try to load config from .agnix.toml in workspace root
                let config_path = root_path.join(".agnix.toml");
                if config_path.exists() {
                    match agnix_core::LintConfig::load(&config_path) {
                        Ok(loaded_config) => {
                            *self.config.write().await = Arc::new(loaded_config);
                        }
                        Err(e) => {
                            // Log error but continue with default config
                            self.client
                                .log_message(
                                    MessageType::WARNING,
                                    format!("Failed to load .agnix.toml: {}", e),
                                )
                                .await;
                        }
                    }
                }
            }
        }

        Ok(InitializeResult {
            capabilities: ServerCapabilities {
                text_document_sync: Some(TextDocumentSyncCapability::Kind(
                    TextDocumentSyncKind::FULL,
                )),
                code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
                hover_provider: Some(HoverProviderCapability::Simple(true)),
                ..Default::default()
            },
            server_info: Some(ServerInfo {
                name: "agnix-lsp".to_string(),
                version: Some(env!("CARGO_PKG_VERSION").to_string()),
            }),
        })
    }

    async fn initialized(&self, _: InitializedParams) {
        self.client
            .log_message(MessageType::INFO, "agnix-lsp initialized")
            .await;
    }

    async fn shutdown(&self) -> Result<()> {
        Ok(())
    }

    async fn did_open(&self, params: DidOpenTextDocumentParams) {
        {
            let mut docs = self.documents.write().await;
            docs.insert(
                params.text_document.uri.clone(),
                params.text_document.text.clone(),
            );
        }
        self.validate_from_content_and_publish(params.text_document.uri)
            .await;
    }

    async fn did_change(&self, params: DidChangeTextDocumentParams) {
        if let Some(change) = params.content_changes.into_iter().next() {
            {
                let mut docs = self.documents.write().await;
                docs.insert(params.text_document.uri.clone(), change.text);
            }
            self.validate_from_content_and_publish(params.text_document.uri)
                .await;
        }
    }

    async fn did_save(&self, params: DidSaveTextDocumentParams) {
        self.validate_from_content_and_publish(params.text_document.uri)
            .await;
    }

    async fn did_close(&self, params: DidCloseTextDocumentParams) {
        {
            let mut docs = self.documents.write().await;
            docs.remove(&params.text_document.uri);
        }
        self.client
            .publish_diagnostics(params.text_document.uri, vec![], None)
            .await;
    }

    async fn code_action(&self, params: CodeActionParams) -> Result<Option<CodeActionResponse>> {
        let uri = &params.text_document.uri;

        // Get document content for byte-to-position conversion
        let content = match self.get_document_content(uri).await {
            Some(c) => c,
            None => return Ok(None),
        };

        let mut actions = Vec::new();

        // Extract fixes from diagnostics that overlap with the request range
        for diag in &params.context.diagnostics {
            // Check if this diagnostic overlaps with the requested range
            let diag_range = &diag.range;
            let req_range = &params.range;

            let overlaps = diag_range.start.line <= req_range.end.line
                && diag_range.end.line >= req_range.start.line;

            if !overlaps {
                continue;
            }

            // Deserialize fixes from diagnostic.data
            let fixes = deserialize_fixes(diag.data.as_ref());
            if !fixes.is_empty() {
                actions.extend(fixes_to_code_actions(uri, &fixes, &content));
            }
        }

        if actions.is_empty() {
            Ok(None)
        } else {
            Ok(Some(
                actions
                    .into_iter()
                    .map(CodeActionOrCommand::CodeAction)
                    .collect(),
            ))
        }
    }

    async fn hover(&self, params: HoverParams) -> Result<Option<Hover>> {
        let uri = &params.text_document_position_params.text_document.uri;
        let position = params.text_document_position_params.position;

        // Get document content
        let content = match self.get_document_content(uri).await {
            Some(c) => c,
            None => return Ok(None),
        };

        // Get hover info for the position
        Ok(hover_at_position(&content, position))
    }
}

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

    /// Test that Backend::new creates a valid Backend instance.
    /// We verify this by creating a service and checking initialize returns proper capabilities.
    #[tokio::test]
    async fn test_backend_new_creates_valid_instance() {
        let (service, _socket) = LspService::new(Backend::new);

        // The service was created successfully, meaning Backend::new worked
        // We can verify by calling initialize
        let init_params = InitializeParams::default();
        let result = service.inner().initialize(init_params).await;

        assert!(result.is_ok());
    }

    /// Test that initialize() returns correct server capabilities.
    #[tokio::test]
    async fn test_initialize_returns_correct_capabilities() {
        let (service, _socket) = LspService::new(Backend::new);

        let init_params = InitializeParams::default();
        let result = service.inner().initialize(init_params).await;

        let init_result = result.expect("initialize should succeed");

        // Verify text document sync capability
        match init_result.capabilities.text_document_sync {
            Some(TextDocumentSyncCapability::Kind(kind)) => {
                assert_eq!(kind, TextDocumentSyncKind::FULL);
            }
            _ => panic!("Expected FULL text document sync capability"),
        }

        // Verify server info
        let server_info = init_result
            .server_info
            .expect("server_info should be present");
        assert_eq!(server_info.name, "agnix-lsp");
        assert!(server_info.version.is_some());
    }

    /// Test that shutdown() returns Ok.
    #[tokio::test]
    async fn test_shutdown_returns_ok() {
        let (service, _socket) = LspService::new(Backend::new);

        let result = service.inner().shutdown().await;
        assert!(result.is_ok());
    }

    /// Test validation error diagnostic has correct code.
    /// We test the diagnostic structure directly since we can't easily mock the validation.
    #[test]
    fn test_validation_error_diagnostic_structure() {
        // Simulate what validate_file returns on validation error
        let error_message = "Failed to parse file";
        let diagnostic = Diagnostic {
            range: Range {
                start: Position {
                    line: 0,
                    character: 0,
                },
                end: Position {
                    line: 0,
                    character: 0,
                },
            },
            severity: Some(DiagnosticSeverity::ERROR),
            code: Some(NumberOrString::String(
                "agnix::validation-error".to_string(),
            )),
            code_description: None,
            source: Some("agnix".to_string()),
            message: format!("Validation error: {}", error_message),
            related_information: None,
            tags: None,
            data: None,
        };

        assert_eq!(
            diagnostic.code,
            Some(NumberOrString::String(
                "agnix::validation-error".to_string()
            ))
        );
        assert_eq!(diagnostic.source, Some("agnix".to_string()));
        assert_eq!(diagnostic.severity, Some(DiagnosticSeverity::ERROR));
        assert!(diagnostic.message.contains("Validation error:"));
    }

    /// Test internal error diagnostic has correct code.
    #[test]
    fn test_internal_error_diagnostic_structure() {
        // Simulate what validate_file returns on panic/internal error
        let error_message = "task panicked";
        let diagnostic = Diagnostic {
            range: Range {
                start: Position {
                    line: 0,
                    character: 0,
                },
                end: Position {
                    line: 0,
                    character: 0,
                },
            },
            severity: Some(DiagnosticSeverity::ERROR),
            code: Some(NumberOrString::String("agnix::internal-error".to_string())),
            code_description: None,
            source: Some("agnix".to_string()),
            message: format!("Internal error: {}", error_message),
            related_information: None,
            tags: None,
            data: None,
        };

        assert_eq!(
            diagnostic.code,
            Some(NumberOrString::String("agnix::internal-error".to_string()))
        );
        assert_eq!(diagnostic.source, Some("agnix".to_string()));
        assert_eq!(diagnostic.severity, Some(DiagnosticSeverity::ERROR));
        assert!(diagnostic.message.contains("Internal error:"));
    }

    /// Test that invalid URIs are identified correctly.
    /// Non-file URIs should fail to_file_path().
    #[test]
    fn test_invalid_uri_detection() {
        // Non-file URIs should fail to_file_path()
        let http_uri = Url::parse("http://example.com/file.md").unwrap();
        assert!(http_uri.to_file_path().is_err());

        let data_uri = Url::parse("data:text/plain;base64,SGVsbG8=").unwrap();
        assert!(data_uri.to_file_path().is_err());

        // File URIs should succeed - use platform-appropriate path
        #[cfg(windows)]
        let file_uri = Url::parse("file:///C:/tmp/test.md").unwrap();
        #[cfg(not(windows))]
        let file_uri = Url::parse("file:///tmp/test.md").unwrap();
        assert!(file_uri.to_file_path().is_ok());
    }

    /// Test validate_file with a valid file returns diagnostics.
    #[tokio::test]
    async fn test_validate_file_valid_skill() {
        let (service, _socket) = LspService::new(Backend::new);

        // Create a valid skill file
        let temp_dir = tempfile::tempdir().unwrap();
        let skill_path = temp_dir.path().join("SKILL.md");
        std::fs::write(
            &skill_path,
            r#"---
name: test-skill
version: 1.0.0
model: sonnet
---

# Test Skill

This is a valid skill.
"#,
        )
        .unwrap();

        // We can't directly call validate_file since it's private,
        // but we can verify the validation logic works through did_open
        // The Backend will log messages to the client
        let uri = Url::from_file_path(&skill_path).unwrap();

        // Call did_open which triggers validate_and_publish internally
        service
            .inner()
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri,
                    language_id: "markdown".to_string(),
                    version: 1,
                    text: String::new(), // Content is read from file
                },
            })
            .await;

        // If we get here without panicking, the validation completed
    }

    /// Test validate_file with an invalid skill file.
    #[tokio::test]
    async fn test_validate_file_invalid_skill() {
        let (service, _socket) = LspService::new(Backend::new);

        // Create an invalid skill file (invalid name with spaces)
        let temp_dir = tempfile::tempdir().unwrap();
        let skill_path = temp_dir.path().join("SKILL.md");
        std::fs::write(
            &skill_path,
            r#"---
name: Invalid Name With Spaces
version: 1.0.0
model: sonnet
---

# Invalid Skill

This skill has an invalid name.
"#,
        )
        .unwrap();

        let uri = Url::from_file_path(&skill_path).unwrap();

        // Call did_open which triggers validation
        service
            .inner()
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri,
                    language_id: "markdown".to_string(),
                    version: 1,
                    text: String::new(),
                },
            })
            .await;

        // Validation should complete and publish diagnostics
    }

    /// Test did_save triggers validation.
    #[tokio::test]
    async fn test_did_save_triggers_validation() {
        let (service, _socket) = LspService::new(Backend::new);

        let temp_dir = tempfile::tempdir().unwrap();
        let skill_path = temp_dir.path().join("SKILL.md");
        std::fs::write(
            &skill_path,
            r#"---
name: test-skill
version: 1.0.0
model: sonnet
---

# Test Skill
"#,
        )
        .unwrap();

        let uri = Url::from_file_path(&skill_path).unwrap();

        // Call did_save which triggers validate_and_publish
        service
            .inner()
            .did_save(DidSaveTextDocumentParams {
                text_document: TextDocumentIdentifier { uri },
                text: None,
            })
            .await;

        // Validation should complete without error
    }

    /// Test did_close clears diagnostics.
    #[tokio::test]
    async fn test_did_close_clears_diagnostics() {
        let (service, _socket) = LspService::new(Backend::new);

        let temp_dir = tempfile::tempdir().unwrap();
        let skill_path = temp_dir.path().join("SKILL.md");
        std::fs::write(&skill_path, "# Test").unwrap();

        let uri = Url::from_file_path(&skill_path).unwrap();

        // Call did_close which publishes empty diagnostics
        service
            .inner()
            .did_close(DidCloseTextDocumentParams {
                text_document: TextDocumentIdentifier { uri },
            })
            .await;

        // Should complete without error
    }

    /// Test initialized() completes without error.
    #[tokio::test]
    async fn test_initialized_completes() {
        let (service, _socket) = LspService::new(Backend::new);

        // Call initialized
        service.inner().initialized(InitializedParams {}).await;

        // Should complete without error (logs a message to client)
    }

    /// Test validate_and_publish with non-file URI is handled gracefully.
    /// Since validate_and_publish is private, we test the URI validation logic directly.
    #[tokio::test]
    async fn test_non_file_uri_handled_gracefully() {
        let (service, _socket) = LspService::new(Backend::new);

        // Create a non-file URI (http://)
        let http_uri = Url::parse("http://example.com/test.md").unwrap();

        // Call did_open with non-file URI
        // This should be handled gracefully (log warning and return early)
        service
            .inner()
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri: http_uri,
                    language_id: "markdown".to_string(),
                    version: 1,
                    text: String::new(),
                },
            })
            .await;

        // Should complete without panic
    }

    /// Test validation with non-existent file.
    #[tokio::test]
    async fn test_validate_nonexistent_file() {
        let (service, _socket) = LspService::new(Backend::new);

        // Create a URI for a file that doesn't exist
        let temp_dir = tempfile::tempdir().unwrap();
        let nonexistent_path = temp_dir.path().join("nonexistent.md");
        let uri = Url::from_file_path(&nonexistent_path).unwrap();

        // Call did_open - should handle missing file gracefully
        service
            .inner()
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri,
                    language_id: "markdown".to_string(),
                    version: 1,
                    text: String::new(),
                },
            })
            .await;

        // Should complete without panic (will publish error diagnostic)
    }

    /// Test server info contains version from Cargo.toml.
    #[tokio::test]
    async fn test_server_info_version() {
        let (service, _socket) = LspService::new(Backend::new);

        let init_params = InitializeParams::default();
        let result = service.inner().initialize(init_params).await.unwrap();

        let server_info = result.server_info.unwrap();
        let version = server_info.version.unwrap();

        // Version should be a valid semver string
        assert!(!version.is_empty());
        // Should match the crate version pattern (e.g., "0.1.0")
        assert!(version.contains('.'));
    }

    /// Test that initialize captures workspace root from root_uri.
    #[tokio::test]
    async fn test_initialize_captures_workspace_root() {
        let (service, _socket) = LspService::new(Backend::new);

        let temp_dir = tempfile::tempdir().unwrap();
        let root_uri = Url::from_file_path(temp_dir.path()).unwrap();

        let init_params = InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        };

        let result = service.inner().initialize(init_params).await;
        assert!(result.is_ok());

        // The workspace root should now be set (we can't directly access it,
        // but the test verifies initialize handles root_uri without error)
    }

    /// Test that initialize loads config from .agnix.toml when present.
    #[tokio::test]
    async fn test_initialize_loads_config_from_file() {
        let (service, _socket) = LspService::new(Backend::new);

        let temp_dir = tempfile::tempdir().unwrap();

        // Create a .agnix.toml config file
        let config_path = temp_dir.path().join(".agnix.toml");
        std::fs::write(
            &config_path,
            r#"
severity = "Warning"
target = "ClaudeCode"
exclude = []

[rules]
skills = false
"#,
        )
        .unwrap();

        let root_uri = Url::from_file_path(temp_dir.path()).unwrap();
        let init_params = InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        };

        let result = service.inner().initialize(init_params).await;
        assert!(result.is_ok());

        // The config should have been loaded (we can't directly access it,
        // but the test verifies initialize handles .agnix.toml without error)
    }

    /// Test that initialize handles invalid .agnix.toml gracefully.
    #[tokio::test]
    async fn test_initialize_handles_invalid_config() {
        let (service, _socket) = LspService::new(Backend::new);

        let temp_dir = tempfile::tempdir().unwrap();

        // Create an invalid .agnix.toml config file
        let config_path = temp_dir.path().join(".agnix.toml");
        std::fs::write(&config_path, "this is not valid toml [[[").unwrap();

        let root_uri = Url::from_file_path(temp_dir.path()).unwrap();
        let init_params = InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        };

        // Should still succeed (logs warning, uses default config)
        let result = service.inner().initialize(init_params).await;
        assert!(result.is_ok());
    }

    /// Test that files within workspace are validated normally.
    #[tokio::test]
    async fn test_file_within_workspace_validated() {
        let (service, _socket) = LspService::new(Backend::new);

        // Create workspace with a skill file
        let temp_dir = tempfile::tempdir().unwrap();
        let skill_path = temp_dir.path().join("SKILL.md");
        std::fs::write(
            &skill_path,
            r#"---
name: test-skill
version: 1.0.0
model: sonnet
---

# Test Skill
"#,
        )
        .unwrap();

        // Initialize with workspace root
        let root_uri = Url::from_file_path(temp_dir.path()).unwrap();
        let init_params = InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        };
        service.inner().initialize(init_params).await.unwrap();

        // File within workspace should be validated
        let uri = Url::from_file_path(&skill_path).unwrap();
        service
            .inner()
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri,
                    language_id: "markdown".to_string(),
                    version: 1,
                    text: String::new(),
                },
            })
            .await;

        // Should complete without error (file is within workspace)
    }

    /// Test that files outside workspace are rejected.
    /// This tests the workspace boundary validation security feature.
    #[tokio::test]
    async fn test_file_outside_workspace_rejected() {
        let (service, _socket) = LspService::new(Backend::new);

        // Create two separate directories
        let workspace_dir = tempfile::tempdir().unwrap();
        let outside_dir = tempfile::tempdir().unwrap();

        // Create a file outside the workspace
        let outside_file = outside_dir.path().join("SKILL.md");
        std::fs::write(
            &outside_file,
            r#"---
name: outside-skill
version: 1.0.0
model: sonnet
---

# Outside Skill
"#,
        )
        .unwrap();

        // Initialize with workspace root
        let root_uri = Url::from_file_path(workspace_dir.path()).unwrap();
        let init_params = InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        };
        service.inner().initialize(init_params).await.unwrap();

        // Try to validate file outside workspace
        let uri = Url::from_file_path(&outside_file).unwrap();
        service
            .inner()
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri,
                    language_id: "markdown".to_string(),
                    version: 1,
                    text: String::new(),
                },
            })
            .await;

        // Should complete without error (logs warning and returns early)
        // The file is rejected but no panic occurs
    }

    /// Test validation without workspace root (backwards compatibility).
    /// When no workspace root is set, all files should be accepted.
    #[tokio::test]
    async fn test_validation_without_workspace_root() {
        let (service, _socket) = LspService::new(Backend::new);

        // Initialize without root_uri
        let init_params = InitializeParams::default();
        service.inner().initialize(init_params).await.unwrap();

        // Create a file anywhere
        let temp_dir = tempfile::tempdir().unwrap();
        let skill_path = temp_dir.path().join("SKILL.md");
        std::fs::write(
            &skill_path,
            r#"---
name: test-skill
version: 1.0.0
model: sonnet
---

# Test Skill
"#,
        )
        .unwrap();

        // Should validate normally (no workspace boundary check)
        let uri = Url::from_file_path(&skill_path).unwrap();
        service
            .inner()
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri,
                    language_id: "markdown".to_string(),
                    version: 1,
                    text: String::new(),
                },
            })
            .await;

        // Should complete without error
    }

    /// Test that cached config is used (performance optimization).
    /// We verify this indirectly by running multiple validations.
    #[tokio::test]
    async fn test_cached_config_used_for_multiple_validations() {
        let (service, _socket) = LspService::new(Backend::new);

        // Initialize
        service
            .inner()
            .initialize(InitializeParams::default())
            .await
            .unwrap();

        // Create multiple skill files
        let temp_dir = tempfile::tempdir().unwrap();
        for i in 0..3 {
            let skill_path = temp_dir.path().join(format!("skill{}/SKILL.md", i));
            std::fs::create_dir_all(skill_path.parent().unwrap()).unwrap();
            std::fs::write(
                &skill_path,
                format!(
                    r#"---
name: test-skill-{}
version: 1.0.0
model: sonnet
---

# Test Skill {}
"#,
                    i, i
                ),
            )
            .unwrap();

            let uri = Url::from_file_path(&skill_path).unwrap();
            service
                .inner()
                .did_open(DidOpenTextDocumentParams {
                    text_document: TextDocumentItem {
                        uri,
                        language_id: "markdown".to_string(),
                        version: 1,
                        text: String::new(),
                    },
                })
                .await;
        }

        // All validations should complete (config is reused internally)
    }

    /// Regression test: validates multiple files using the cached registry.
    /// Verifies the Arc<ValidatorRegistry> is thread-safe across spawn_blocking tasks.
    #[tokio::test]
    async fn test_cached_registry_used_for_multiple_validations() {
        let (service, _socket) = LspService::new(Backend::new);

        // Initialize
        service
            .inner()
            .initialize(InitializeParams::default())
            .await
            .unwrap();

        let temp_dir = tempfile::tempdir().unwrap();

        // Skill file
        let skill_path = temp_dir.path().join("SKILL.md");
        std::fs::write(
            &skill_path,
            r#"---
name: test-skill
version: 1.0.0
model: sonnet
---

# Test Skill
"#,
        )
        .unwrap();

        // CLAUDE.md file
        let claude_path = temp_dir.path().join("CLAUDE.md");
        std::fs::write(
            &claude_path,
            r#"# Project Memory

This is a test project.
"#,
        )
        .unwrap();

        for path in [&skill_path, &claude_path] {
            let uri = Url::from_file_path(path).unwrap();
            service
                .inner()
                .did_open(DidOpenTextDocumentParams {
                    text_document: TextDocumentItem {
                        uri,
                        language_id: "markdown".to_string(),
                        version: 1,
                        text: String::new(),
                    },
                })
                .await;
        }
    }

    // ===== Cache Invalidation Tests =====

    /// Test that document cache is cleared when document is closed.
    #[tokio::test]
    async fn test_document_cache_cleared_on_close() {
        let (service, _socket) = LspService::new(Backend::new);

        let temp_dir = tempfile::tempdir().unwrap();
        let skill_path = temp_dir.path().join("SKILL.md");
        std::fs::write(
            &skill_path,
            "---\nname: test\ndescription: Test\n---\n# Test",
        )
        .unwrap();

        let uri = Url::from_file_path(&skill_path).unwrap();

        // Open document
        service
            .inner()
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri: uri.clone(),
                    language_id: "markdown".to_string(),
                    version: 1,
                    text: "---\nname: test\ndescription: Test\n---\n# Test".to_string(),
                },
            })
            .await;

        // Verify document is cached (hover should work)
        let hover_before = service
            .inner()
            .hover(HoverParams {
                text_document_position_params: TextDocumentPositionParams {
                    text_document: TextDocumentIdentifier { uri: uri.clone() },
                    position: Position {
                        line: 1,
                        character: 0,
                    },
                },
                work_done_progress_params: WorkDoneProgressParams::default(),
            })
            .await;
        assert!(hover_before.is_ok());
        assert!(hover_before.unwrap().is_some());

        // Close document
        service
            .inner()
            .did_close(DidCloseTextDocumentParams {
                text_document: TextDocumentIdentifier { uri: uri.clone() },
            })
            .await;

        // Verify document cache is cleared (hover should return None)
        let hover_after = service
            .inner()
            .hover(HoverParams {
                text_document_position_params: TextDocumentPositionParams {
                    text_document: TextDocumentIdentifier { uri },
                    position: Position {
                        line: 1,
                        character: 0,
                    },
                },
                work_done_progress_params: WorkDoneProgressParams::default(),
            })
            .await;
        assert!(hover_after.is_ok());
        assert!(hover_after.unwrap().is_none());
    }

    /// Test that document cache is updated on change.
    #[tokio::test]
    async fn test_document_cache_updated_on_change() {
        let (service, _socket) = LspService::new(Backend::new);

        let temp_dir = tempfile::tempdir().unwrap();
        let skill_path = temp_dir.path().join("SKILL.md");
        std::fs::write(&skill_path, "# Initial").unwrap();

        let uri = Url::from_file_path(&skill_path).unwrap();

        // Open with initial content
        service
            .inner()
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri: uri.clone(),
                    language_id: "markdown".to_string(),
                    version: 1,
                    text: "# Initial".to_string(),
                },
            })
            .await;

        // Change to content with frontmatter
        service
            .inner()
            .did_change(DidChangeTextDocumentParams {
                text_document: VersionedTextDocumentIdentifier {
                    uri: uri.clone(),
                    version: 2,
                },
                content_changes: vec![TextDocumentContentChangeEvent {
                    range: None,
                    range_length: None,
                    text: "---\nname: updated\ndescription: Updated\n---\n# Updated".to_string(),
                }],
            })
            .await;

        // Verify cache has new content (hover should work on frontmatter)
        let hover = service
            .inner()
            .hover(HoverParams {
                text_document_position_params: TextDocumentPositionParams {
                    text_document: TextDocumentIdentifier { uri },
                    position: Position {
                        line: 1,
                        character: 0,
                    },
                },
                work_done_progress_params: WorkDoneProgressParams::default(),
            })
            .await;
        assert!(hover.is_ok());
        assert!(hover.unwrap().is_some());
    }

    /// Test that multiple documents have independent caches.
    #[tokio::test]
    async fn test_multiple_documents_independent_caches() {
        let (service, _socket) = LspService::new(Backend::new);

        let temp_dir = tempfile::tempdir().unwrap();

        // Create two skill files
        let skill1_path = temp_dir.path().join("skill1").join("SKILL.md");
        let skill2_path = temp_dir.path().join("skill2").join("SKILL.md");
        std::fs::create_dir_all(skill1_path.parent().unwrap()).unwrap();
        std::fs::create_dir_all(skill2_path.parent().unwrap()).unwrap();

        std::fs::write(
            &skill1_path,
            "---\nname: skill-one\ndescription: First\n---\n# One",
        )
        .unwrap();
        std::fs::write(
            &skill2_path,
            "---\nname: skill-two\ndescription: Second\n---\n# Two",
        )
        .unwrap();

        let uri1 = Url::from_file_path(&skill1_path).unwrap();
        let uri2 = Url::from_file_path(&skill2_path).unwrap();

        // Open both documents
        service
            .inner()
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri: uri1.clone(),
                    language_id: "markdown".to_string(),
                    version: 1,
                    text: "---\nname: skill-one\ndescription: First\n---\n# One".to_string(),
                },
            })
            .await;

        service
            .inner()
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri: uri2.clone(),
                    language_id: "markdown".to_string(),
                    version: 1,
                    text: "---\nname: skill-two\ndescription: Second\n---\n# Two".to_string(),
                },
            })
            .await;

        // Close first document
        service
            .inner()
            .did_close(DidCloseTextDocumentParams {
                text_document: TextDocumentIdentifier { uri: uri1.clone() },
            })
            .await;

        // First document should be cleared
        let hover1 = service
            .inner()
            .hover(HoverParams {
                text_document_position_params: TextDocumentPositionParams {
                    text_document: TextDocumentIdentifier { uri: uri1 },
                    position: Position {
                        line: 1,
                        character: 0,
                    },
                },
                work_done_progress_params: WorkDoneProgressParams::default(),
            })
            .await;
        assert!(hover1.is_ok());
        assert!(hover1.unwrap().is_none());

        // Second document should still be cached
        let hover2 = service
            .inner()
            .hover(HoverParams {
                text_document_position_params: TextDocumentPositionParams {
                    text_document: TextDocumentIdentifier { uri: uri2 },
                    position: Position {
                        line: 1,
                        character: 0,
                    },
                },
                work_done_progress_params: WorkDoneProgressParams::default(),
            })
            .await;
        assert!(hover2.is_ok());
        assert!(hover2.unwrap().is_some());
    }
}